Compiler.c 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  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) {
  176. while(cConsumeTokenIf(T_MUL)) {
  177. dt = cDereference(dt);
  178. }
  179. return dt;
  180. }
  181. static DataType cReadType(Token t) {
  182. switch(t) {
  183. case T_INT32: return cExtendType(dtInt32());
  184. case T_INT64: return cExtendType(dtInt64());
  185. case T_BOOL: return cExtendType(dtBool());
  186. case T_FLOAT: return cExtendType(dtFloat());
  187. case T_LITERAL:
  188. {
  189. Struct* st = stsSearch(&structs, cReadString());
  190. if(st == NULL) {
  191. cError("struct %s does not exist");
  192. }
  193. return cExtendType(dtStruct(st));
  194. }
  195. default: cUnexpectedToken(t); return dtVoid();
  196. }
  197. }
  198. static DataType cExpression();
  199. static void cLoadRef(DataType type) {
  200. if(dtIsPointer(type)) {
  201. cAddOperation(OP_REFERENCE);
  202. return;
  203. }
  204. switch(type.type) {
  205. DT_OPERATION(LOAD);
  206. case DT_STRUCT: cAddInt32Operation(OP_LOAD, cGetSize(type)); break;
  207. default: cError("cannot load type %s", cGetName(type));
  208. }
  209. }
  210. static DataType cUnpack(DataType dt) {
  211. if(dtRemoveVariable(&dt)) {
  212. cLoadRef(dt);
  213. }
  214. return dt;
  215. }
  216. static DataType cUnpackedExpression() {
  217. return cUnpack(cExpression());
  218. }
  219. static void cCallFunctionArguments(Function* f) {
  220. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  221. return;
  222. }
  223. while(true) {
  224. DataType dt = cUnpackedExpression();
  225. if(fAddArgument(f, dt, &structs)) {
  226. cTooMuchArguments();
  227. } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  228. return;
  229. }
  230. cConsumeToken(T_COMMA);
  231. }
  232. }
  233. static DataType cCallFunction(const char* name) {
  234. int returnAddress = bcGetAddress(code);
  235. Function f;
  236. fInit(&f, name, line);
  237. int oldOnLine = onLine;
  238. onLine = false;
  239. cCallFunctionArguments(&f);
  240. onLine = oldOnLine;
  241. Function* found = fsSearch(&functions, &f);
  242. if(found == NULL) {
  243. cError("unknown function");
  244. } else if(found->global) {
  245. cAddInt32Operation(OP_CALL, found->line);
  246. return found->returnType;
  247. }
  248. char push[1 + sizeof(int32)] = {OP_PUSH_INT32};
  249. bcInsertBytes(code, push, sizeof(push), returnAddress);
  250. cAddOperation(OP_GOSUB);
  251. if(found->address == -1) {
  252. f.returnType = found->returnType;
  253. f.address = cReserveInt32();
  254. fsAdd(&functionQueue, &f);
  255. } else {
  256. cAddInt32(found->address);
  257. }
  258. cAddInt32(found->size);
  259. return found->returnType;
  260. }
  261. static bool cCompare(DataType left, DataType right) {
  262. return dtCompare(left, right) || (dtIsPointer(left) && dtIsNull(right));
  263. }
  264. static void cStore(DataType left, DataType right, const char* name) {
  265. if(!cCompare(left, right)) {
  266. cInvalidOperation(left, right, name);
  267. } else if(dtIsPointer(left)) {
  268. cAddOperation(OP_STORE_POINTER);
  269. return;
  270. }
  271. switch(left.type) {
  272. DT_OPERATION(STORE);
  273. default: cError("cannot store type %s", cGetName(left));
  274. }
  275. }
  276. static DataType cLiteral() {
  277. const char* literal = cReadString();
  278. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  279. return cCallFunction(literal);
  280. }
  281. Variable v;
  282. if(vsSearch(&vars, &v, literal)) {
  283. cNotDeclared(literal);
  284. }
  285. cAddInt32Operation(OP_DEREFERENCE_VAR, v.address);
  286. return dtToVariable(v.type);
  287. }
  288. static DataType cBracketPrimary() {
  289. DataType result = cExpression();
  290. cConsumeToken(T_CLOSE_BRACKET);
  291. return result;
  292. }
  293. static void cArrayIndex(const char* name) {
  294. if(!dtIsInt32(cUnpackedExpression())) {
  295. cError("array %s must be an int", name);
  296. }
  297. }
  298. static DataType cAllocArray() {
  299. DataType dt = cReadType(cReadTokenAndLine());
  300. cConsumeToken(T_OPEN_SQUARE_BRACKET);
  301. cArrayIndex("size");
  302. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  303. cAddInt32Operation(OP_NEW, cGetSize(dt));
  304. return cDereference(dt);
  305. }
  306. static DataType cLength() {
  307. DataType pointer = cUnpackedExpression();
  308. if(!dtIsPointer(pointer)) {
  309. cError("length expects a pointer");
  310. }
  311. cAddOperation(OP_LENGTH);
  312. return dtInt32();
  313. }
  314. static DataType cPrimary() {
  315. Token t = cReadTokenAndLine();
  316. switch(t) {
  317. case T_CONST_INT32: cConstantInt32(); return dtInt32();
  318. case T_CONST_INT64: cConstantInt64(); return dtInt64();
  319. case T_CONST_FLOAT: cConstantFloat(); return dtFloat();
  320. case T_TRUE: cAddOperation(OP_PUSH_TRUE); return dtBool();
  321. case T_FALSE: cAddOperation(OP_PUSH_FALSE); return dtBool();
  322. case T_NULLPTR: cAddOperation(OP_PUSH_NULLPTR); return dtNull();
  323. case T_OPEN_BRACKET: return cBracketPrimary();
  324. case T_LITERAL: return cLiteral();
  325. case T_NEW: return cAllocArray();
  326. case T_LENGTH: return cLength();
  327. default: cUnexpectedToken(t); return dtVoid();
  328. }
  329. }
  330. static void cRemoveReference(DataType* dt, const char* name) {
  331. if(!dtRemoveVariable(dt)) {
  332. cError("%s needs a reference not %s", name, cGetName(*dt));
  333. }
  334. }
  335. static void cExpectType(DataType actual, DataType wanted, const char* name) {
  336. if(!dtCompare(actual, wanted)) {
  337. cError("%s needs %s not %s", name, cGetName(wanted), cGetName(actual));
  338. }
  339. }
  340. static void cChangeType(DataType* dt, Operation op, Operation pushOp,
  341. int change) {
  342. if(onLine) {
  343. cAddByteOperation(op, change);
  344. *dt = dtVoid();
  345. } else {
  346. cAddByteOperation(pushOp, change);
  347. }
  348. }
  349. static void cPostChange(DataType* dt, int change, const char* name) {
  350. cRemoveReference(dt, name);
  351. if(dtCompare(*dt, dtInt32())) {
  352. cChangeType(dt, OP_CHANGE_INT32, OP_PUSH_POST_CHANGE_INT32, change);
  353. } else if(dtCompare(*dt, dtInt64())) {
  354. cChangeType(dt, OP_CHANGE_INT64, OP_PUSH_POST_CHANGE_INT64, change);
  355. } else {
  356. cError("%s needs an int or long not %s", name, cGetName(*dt));
  357. }
  358. }
  359. static DataType cStructAccess(DataType dt, int pointers) {
  360. Struct* st = dtGetStruct(&structs, dt);
  361. if(st == NULL || dt.pointers != pointers) {
  362. cError(pointers == 0 ? ". expects a struct" : "-> expects a struct*");
  363. }
  364. cConsumeToken(T_LITERAL);
  365. const char* name = cReadString();
  366. Variable inner;
  367. if(vSearchStruct(&inner, &structs, st, name)) {
  368. cError("%s has no member %s", st->name, name);
  369. } else if(inner.address > 0) {
  370. cAddInt32Operation(OP_PUSH_INT32, inner.address);
  371. cAddInt32Operation(OP_ADD_REFERENCE, 1);
  372. }
  373. return dtToVariable(inner.type);
  374. }
  375. static DataType cAccess() {
  376. DataType dt = cPrimary();
  377. while(true) {
  378. if(cConsumeTokenIf(T_INCREMENT)) {
  379. cPostChange(&dt, 1, "++");
  380. } else if(cConsumeTokenIf(T_DECREMENT)) {
  381. cPostChange(&dt, -1, "--");
  382. } else if(cConsumeTokenIf(T_POINT)) {
  383. cRemoveReference(&dt, ".");
  384. dt = cStructAccess(dt, 0);
  385. } else if(cConsumeTokenIf(T_ARROW)) {
  386. dt = cStructAccess(cUnpack(dt), 1);
  387. } else if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) {
  388. dt = cUnpack(dt);
  389. if(!dtIsPointer(dt)) {
  390. cError("[] needs a pointer");
  391. }
  392. cArrayIndex("index");
  393. cConsumeToken(T_CLOSE_SQUARE_BRACKET);
  394. dt = dtReference(dt);
  395. cAddInt32Operation(OP_ADD_REFERENCE, cGetSize(dt));
  396. dt = dtToVariable(dt);
  397. } else {
  398. return dt;
  399. }
  400. }
  401. }
  402. static DataType cPreChange(DataType dt, int change, const char* name) {
  403. cRemoveReference(&dt, name);
  404. if(dtCompare(dt, dtInt32())) {
  405. cChangeType(&dt, OP_CHANGE_INT32, OP_PUSH_PRE_CHANGE_INT32, change);
  406. } else if(dtCompare(dt, dtInt64())) {
  407. cChangeType(&dt, OP_CHANGE_INT64, OP_PUSH_PRE_CHANGE_INT64, change);
  408. } else {
  409. cError("%s needs an int or long not %s", name, cGetName(dt));
  410. }
  411. return dt;
  412. }
  413. static DataType cInvertSign(DataType dt) {
  414. if(dtIsInt32(dt)) {
  415. cAddOperation(OP_INVERT_SIGN_INT32);
  416. } else if(dtIsInt64(dt)) {
  417. cAddOperation(OP_INVERT_SIGN_INT64);
  418. } else if(dtIsFloat(dt)) {
  419. cAddOperation(OP_INVERT_SIGN_FLOAT);
  420. } else {
  421. cError("cannot invert sign of %s", cGetName(dt));
  422. }
  423. return dt;
  424. }
  425. static DataType cCast(DataType in, DataType a, Operation aOp, DataType b,
  426. Operation bOp, DataType out) {
  427. if(dtCompare(in, a)) {
  428. cAddOperation(aOp);
  429. } else if(dtCompare(in, b)) {
  430. cAddOperation(bOp);
  431. } else {
  432. cError("cannot cast %s to %s", cGetName(in), cGetName(out));
  433. }
  434. return out;
  435. }
  436. static DataType cPreUnary() {
  437. int marker = tGetMarker();
  438. if(cConsumeTokenIf(T_OPEN_BRACKET)) {
  439. if(cConsumeTokenIf(T_FLOAT) && cConsumeTokenIf(T_CLOSE_BRACKET)) {
  440. return cCast(cUnpack(cPreUnary()), dtInt32(), OP_INT32_TO_FLOAT,
  441. dtInt64(), OP_INT64_TO_FLOAT, dtFloat());
  442. } else if(cConsumeTokenIf(T_INT32) &&
  443. cConsumeTokenIf(T_CLOSE_BRACKET)) {
  444. return cCast(cUnpack(cPreUnary()), dtFloat(), OP_FLOAT_TO_INT32,
  445. dtInt64(), OP_INT64_TO_INT32, dtInt32());
  446. } else if(cConsumeTokenIf(T_INT64) &&
  447. cConsumeTokenIf(T_CLOSE_BRACKET)) {
  448. return cCast(cUnpack(cPreUnary()), dtInt32(), OP_INT32_TO_INT64,
  449. dtFloat(), OP_FLOAT_TO_INT64, dtInt64());
  450. }
  451. }
  452. tReset(marker);
  453. if(cConsumeTokenIf(T_INCREMENT)) {
  454. return cPreChange(cPreUnary(), 1, "++");
  455. } else if(cConsumeTokenIf(T_DECREMENT)) {
  456. return cPreChange(cPreUnary(), -1, "--");
  457. } else if(cConsumeTokenIf(T_SUB)) {
  458. return cInvertSign(cUnpack(cPreUnary()));
  459. } else if(cConsumeTokenIf(T_NOT)) {
  460. DataType dt = cPreUnary();
  461. cExpectType(dt, dtBool(), "!");
  462. cAddOperation(OP_NOT);
  463. return dt;
  464. } else if(cConsumeTokenIf(T_BIT_NOT)) {
  465. DataType dt = cPreUnary();
  466. if(dtCompare(dt, dtInt32())) {
  467. cAddOperation(OP_BIT_NOT_INT32);
  468. } else if(dtCompare(dt, dtInt64())) {
  469. cAddOperation(OP_BIT_NOT_INT64);
  470. } else {
  471. cError("~ needs an int or long not %s", cGetName(dt));
  472. }
  473. return dt;
  474. } else if(cConsumeTokenIf(T_BIT_AND)) {
  475. DataType dt = cPreUnary();
  476. cRemoveReference(&dt, "&");
  477. return cDereference(dt);
  478. } else if(cConsumeTokenIf(T_MUL)) {
  479. DataType dt = cPreUnary();
  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. return cAccess();
  492. }
  493. static void cAddTypeOperation(DataType* a, Parser bf, const TypedOp* op) {
  494. *a = cUnpack(*a);
  495. DataType b = cUnpack(bf());
  496. if(!dtCompare(*a, b)) {
  497. cInvalidOperation(*a, b, op->name);
  498. } else if(dtIsInt32(*a) && op->intOp != OP_NOTHING) {
  499. cAddOperation(op->intOp);
  500. } else if(dtIsInt64(*a) && op->longOp != OP_NOTHING) {
  501. cAddOperation(op->longOp);
  502. } else if(dtIsFloat(*a) && op->floatOp != OP_NOTHING) {
  503. cAddOperation(op->floatOp);
  504. } else if(dtIsBool(*a) && op->boolOp != OP_NOTHING) {
  505. cAddOperation(op->boolOp);
  506. } else if(dtIsPointer(*a) && op->pointerOp != OP_NOTHING) {
  507. cAddOperation(op->pointerOp);
  508. } else {
  509. cInvalidOperation(*a, b, op->name);
  510. }
  511. }
  512. static DataType cMul() {
  513. DataType a = cPreUnary();
  514. while(true) {
  515. if(cConsumeTokenIf(T_MUL)) {
  516. cAddTypeOperation(&a, cPreUnary, &TYPED_MUL);
  517. } else if(cConsumeTokenIf(T_DIV)) {
  518. cAddTypeOperation(&a, cPreUnary, &TYPED_DIV);
  519. } else if(cConsumeTokenIf(T_MOD)) {
  520. cAddTypeOperation(&a, cPreUnary, &TYPED_MOD);
  521. } else {
  522. return a;
  523. }
  524. }
  525. }
  526. static DataType cAdd() {
  527. DataType a = cMul();
  528. while(true) {
  529. if(cConsumeTokenIf(T_ADD)) {
  530. cAddTypeOperation(&a, cMul, &TYPED_ADD);
  531. } else if(cConsumeTokenIf(T_SUB)) {
  532. cAddTypeOperation(&a, cMul, &TYPED_SUB);
  533. } else {
  534. return a;
  535. }
  536. }
  537. }
  538. static DataType cShift() {
  539. DataType a = cAdd();
  540. while(true) {
  541. if(cConsumeTokenIf(T_LEFT_SHIFT)) {
  542. cAddTypeOperation(&a, cAdd, &TYPED_LEFT_SHIFT);
  543. } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
  544. cAddTypeOperation(&a, cAdd, &TYPED_RIGHT_SHIFT);
  545. } else {
  546. return a;
  547. }
  548. }
  549. }
  550. static DataType cComparison() {
  551. DataType a = cShift();
  552. while(true) {
  553. if(cConsumeTokenIf(T_LESS)) {
  554. cAddTypeOperation(&a, cShift, &TYPED_LESS);
  555. a = dtBool();
  556. } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
  557. cAddTypeOperation(&a, cShift, &TYPED_LESS_EQUAL);
  558. a = dtBool();
  559. } else if(cConsumeTokenIf(T_GREATER)) {
  560. cAddTypeOperation(&a, cShift, &TYPED_GREATER);
  561. a = dtBool();
  562. } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
  563. cAddTypeOperation(&a, cShift, &TYPED_GREATER_EQUAL);
  564. a = dtBool();
  565. } else {
  566. return a;
  567. }
  568. }
  569. }
  570. static DataType cEqual() {
  571. DataType a = cComparison();
  572. while(true) {
  573. if(cConsumeTokenIf(T_EQUAL)) {
  574. cAddTypeOperation(&a, cComparison, &TYPED_EQUAL);
  575. a = dtBool();
  576. } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
  577. cAddTypeOperation(&a, cComparison, &TYPED_NOT_EQUAL);
  578. a = dtBool();
  579. } else {
  580. return a;
  581. }
  582. }
  583. }
  584. static DataType cRepeat(Token t, Parser f, const TypedOp* op) {
  585. DataType a = f();
  586. while(cConsumeTokenIf(t)) {
  587. cAddTypeOperation(&a, f, op);
  588. }
  589. return a;
  590. }
  591. static DataType cBitAnd() {
  592. return cRepeat(T_BIT_AND, cEqual, &TYPED_BIT_AND);
  593. }
  594. static DataType cBitXor() {
  595. return cRepeat(T_BIT_XOR, cBitAnd, &TYPED_BIT_XOR);
  596. }
  597. static DataType cBitOr() {
  598. return cRepeat(T_BIT_OR, cBitXor, &TYPED_BIT_OR);
  599. }
  600. static DataType cLogical(Parser f, Token t, Operation jump, Operation op) {
  601. DataType a = f();
  602. while(cConsumeTokenIf(t)) {
  603. a = cUnpack(a);
  604. cAddOperation(jump);
  605. int32 p = cReserveInt32();
  606. DataType b = cUnpack(f());
  607. if(!dtIsBool(a) || !dtIsBool(b)) {
  608. cInvalidOperation(a, b, tGetName(t));
  609. }
  610. cAddOperation(op);
  611. cSetInt32(p, code->length);
  612. }
  613. return a;
  614. }
  615. static DataType cAnd() {
  616. return cLogical(cBitOr, T_AND, OP_PEEK_FALSE_GOTO, OP_AND);
  617. }
  618. static DataType cExpression() {
  619. return cLogical(cAnd, T_OR, OP_PEEK_TRUE_GOTO, OP_OR);
  620. }
  621. static void cLine();
  622. static void cConsumeBody() {
  623. int oldLine = line;
  624. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  625. if(tPeekToken() == T_END) {
  626. line = oldLine;
  627. cError("non closed curved bracket");
  628. }
  629. cLine();
  630. }
  631. }
  632. static void cConsumeScope() {
  633. Scope scope;
  634. vsEnterScope(&vars, &scope);
  635. cConsumeBody();
  636. vsLeaveScope(&vars, &scope);
  637. }
  638. static void cAddReturn(Operation op) {
  639. if(returnIndex >= RETURN_BUFFER) {
  640. cError("too much returns in function");
  641. }
  642. cAddOperation(op);
  643. returns[returnIndex++] = cReserveInt32();
  644. }
  645. static void cReturn() {
  646. if(dtIsVoid(returnType)) {
  647. cConsumeToken(T_SEMICOLON);
  648. cAddReturn(OP_RETURN);
  649. hasReturn = 2;
  650. return;
  651. }
  652. DataType dt = cUnpackedExpression();
  653. if(!cCompare(returnType, dt)) {
  654. cError("wrong return type, should be %s", cGetName(returnType));
  655. } else if(dtIsInt32(dt)) {
  656. cAddReturn(OP_RETURN_INT32);
  657. } else if(dtIsInt64(dt)) {
  658. cAddReturn(OP_RETURN_INT64);
  659. } else if(dtIsBool(dt)) {
  660. cAddReturn(OP_RETURN_BOOL);
  661. } else if(dtIsFloat(dt)) {
  662. cAddReturn(OP_RETURN_FLOAT);
  663. } else if(dtIsPointer(dt) || dtIsNull(dt)) {
  664. cAddReturn(OP_RETURN_POINTER);
  665. } else {
  666. cError("cannot return %s", cGetName(dt));
  667. }
  668. cConsumeToken(T_SEMICOLON);
  669. hasReturn = 2;
  670. }
  671. static void cIf() {
  672. cConsumeToken(T_OPEN_BRACKET);
  673. cExpectType(cUnpackedExpression(), dtBool(), "if");
  674. cConsumeToken(T_CLOSE_BRACKET);
  675. cAddOperation(OP_IF_GOTO);
  676. int32 ifP = cReserveInt32();
  677. cConsumeToken(T_OPEN_CURVED_BRACKET);
  678. cConsumeScope();
  679. cSetInt32(ifP, code->length);
  680. if(cConsumeTokenIf(T_ELSE)) {
  681. cAddOperation(OP_GOTO);
  682. int32 elseP = cReserveInt32();
  683. cSetInt32(ifP, code->length);
  684. if(cConsumeTokenIf(T_IF)) {
  685. cIf();
  686. } else {
  687. cConsumeToken(T_OPEN_CURVED_BRACKET);
  688. cConsumeScope();
  689. }
  690. cSetInt32(elseP, code->length);
  691. }
  692. }
  693. static void cConsumeBreaks(int start, int address) {
  694. for(int i = start; i < breakIndex; i++) {
  695. cSetInt32(breaks[i], address);
  696. }
  697. breakIndex = start;
  698. }
  699. static void cWhile() {
  700. int start = code->length;
  701. cConsumeToken(T_OPEN_BRACKET);
  702. cExpectType(cUnpackedExpression(), dtBool(), "while");
  703. cConsumeToken(T_CLOSE_BRACKET);
  704. cAddOperation(OP_IF_GOTO);
  705. int32 ifP = cReserveInt32();
  706. int breakStart = breakIndex;
  707. forWhileStack++;
  708. int oldContinue = continueAt;
  709. continueAt = start;
  710. cConsumeToken(T_OPEN_CURVED_BRACKET);
  711. cConsumeScope();
  712. continueAt = oldContinue;
  713. forWhileStack--;
  714. cAddInt32Operation(OP_GOTO, start);
  715. cSetInt32(ifP, code->length);
  716. cConsumeBreaks(breakStart, code->length);
  717. }
  718. static void cDelete() {
  719. DataType pointer = cUnpackedExpression();
  720. if(!dtIsPointer(pointer)) {
  721. cError("delete expects a pointer");
  722. }
  723. cAddOperation(OP_DELETE);
  724. }
  725. static void cOperationSet(DataType left, const TypedOp* op) {
  726. cAddOperation(OP_DUPLICATE_REFERENCE);
  727. cLoadRef(left);
  728. cAddTypeOperation(&left, cUnpackedExpression, op);
  729. cStore(left, left, "=");
  730. }
  731. static void cSetVariable() {
  732. onLine = true;
  733. DataType dt = cPreUnary();
  734. onLine = false;
  735. if(dtIsVoid(dt)) {
  736. return;
  737. }
  738. cRemoveReference(&dt, "setter");
  739. Token t = cReadTokenAndLine();
  740. switch(t) {
  741. case T_SET: cStore(dt, cUnpackedExpression(), "="); break;
  742. case T_ADD_SET: cOperationSet(dt, &TYPED_ADD); break;
  743. case T_SUB_SET: cOperationSet(dt, &TYPED_SUB); break;
  744. case T_MUL_SET: cOperationSet(dt, &TYPED_MUL); break;
  745. case T_DIV_SET: cOperationSet(dt, &TYPED_DIV); break;
  746. case T_MOD_SET: cOperationSet(dt, &TYPED_MOD); break;
  747. case T_BIT_AND_SET: cOperationSet(dt, &TYPED_BIT_AND); break;
  748. case T_BIT_OR_SET: cOperationSet(dt, &TYPED_BIT_OR); break;
  749. case T_BIT_XOR_SET: cOperationSet(dt, &TYPED_BIT_XOR); break;
  750. case T_LEFT_SHIFT_SET: cOperationSet(dt, &TYPED_LEFT_SHIFT); break;
  751. case T_RIGHT_SHIFT_SET: cOperationSet(dt, &TYPED_RIGHT_SHIFT); break;
  752. default: cUnexpectedToken(t);
  753. }
  754. }
  755. static void cDeclare(DataType dt) {
  756. dt = cExtendType(dt);
  757. cConsumeToken(T_LITERAL);
  758. const char* var = cReadString();
  759. if(vsInScope(&vars, var)) {
  760. cDeclared(var);
  761. }
  762. Variable* v = vsAdd(&vars, var, dt, &structs);
  763. if(dt.type != DT_STRUCT || dtIsPointer(dt)) {
  764. cConsumeToken(T_SET);
  765. cAddInt32Operation(OP_DEREFERENCE_VAR, v->address);
  766. cStore(v->type, cUnpackedExpression(), "=");
  767. }
  768. }
  769. static void cLineExpression() {
  770. int marker = tGetMarker();
  771. Token t = cReadTokenAndLine();
  772. if(t == T_LITERAL) {
  773. const char* literal = cReadString();
  774. Struct* st = stsSearch(&structs, literal);
  775. if(st != NULL) {
  776. cDeclare(dtStruct(st));
  777. return;
  778. }
  779. }
  780. switch(t) {
  781. case T_INT32: cDeclare(dtInt32()); break;
  782. case T_INT64: cDeclare(dtInt64()); break;
  783. case T_BOOL: cDeclare(dtBool()); break;
  784. case T_FLOAT: cDeclare(dtFloat()); break;
  785. case T_DELETE: cDelete(); break;
  786. default: tReset(marker); cSetVariable();
  787. }
  788. }
  789. static void cFor() {
  790. Scope scope;
  791. vsEnterScope(&vars, &scope);
  792. cConsumeToken(T_OPEN_BRACKET);
  793. cLineExpression();
  794. cConsumeToken(T_SEMICOLON);
  795. int startCheck = code->length;
  796. cExpectType(cUnpackedExpression(), dtBool(), "for");
  797. cConsumeToken(T_SEMICOLON);
  798. cAddOperation(OP_IF_GOTO);
  799. int32 end = cReserveInt32();
  800. cAddOperation(OP_GOTO);
  801. int32 beginBody = cReserveInt32();
  802. int startPerLoop = code->length;
  803. cLineExpression();
  804. cAddInt32Operation(OP_GOTO, startCheck);
  805. cConsumeToken(T_CLOSE_BRACKET);
  806. cSetInt32(beginBody, code->length);
  807. int breakStart = breakIndex;
  808. forWhileStack++;
  809. int oldContinue = continueAt;
  810. continueAt = startPerLoop;
  811. cConsumeToken(T_OPEN_CURVED_BRACKET);
  812. cConsumeBody();
  813. continueAt = oldContinue;
  814. forWhileStack--;
  815. cAddInt32Operation(OP_GOTO, startPerLoop);
  816. cSetInt32(end, code->length);
  817. cConsumeBreaks(breakStart, code->length);
  818. vsLeaveScope(&vars, &scope);
  819. }
  820. static void cBreak() {
  821. if(forWhileStack == 0) {
  822. cError("break without for or while");
  823. } else if(breakIndex >= BREAK_BUFFER) {
  824. cError("too much breaks");
  825. }
  826. cAddOperation(OP_GOTO);
  827. breaks[breakIndex++] = cReserveInt32();
  828. cConsumeToken(T_SEMICOLON);
  829. }
  830. static void cContinue() {
  831. if(forWhileStack == 0) {
  832. cError("continue without for or while");
  833. }
  834. cAddInt32Operation(OP_GOTO, continueAt);
  835. cConsumeToken(T_SEMICOLON);
  836. }
  837. static void cLine() {
  838. int marker = tGetMarker();
  839. Token t = cReadTokenAndLine();
  840. cAddLine(line);
  841. switch(t) {
  842. case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
  843. case T_RETURN: cReturn(); break;
  844. case T_IF: cIf(); break;
  845. case T_WHILE: cWhile(); break;
  846. case T_FOR: cFor(); break;
  847. case T_BREAK: cBreak(); break;
  848. case T_CONTINUE: cContinue(); break;
  849. default:
  850. tReset(marker);
  851. cLineExpression();
  852. cConsumeToken(T_SEMICOLON);
  853. }
  854. }
  855. static void cBuildFunction(Function* f, DataType rType) {
  856. cConsumeToken(T_LITERAL);
  857. fInit(f, cReadString(), line);
  858. f->returnType = rType;
  859. vsReset(&vars);
  860. cConsumeToken(T_OPEN_BRACKET);
  861. if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  862. return;
  863. }
  864. while(true) {
  865. DataType dt = cReadType(cReadTokenAndLine());
  866. cConsumeToken(T_LITERAL);
  867. const char* name = cReadString();
  868. if(vsInScope(&vars, name)) {
  869. cDeclared(name);
  870. }
  871. vsAdd(&vars, name, dt, &structs);
  872. if(fAddArgument(f, dt, &structs)) {
  873. cTooMuchArguments();
  874. } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
  875. return;
  876. }
  877. cConsumeToken(T_COMMA);
  878. }
  879. }
  880. static void cAddFunction(Function* found, Function* f) {
  881. if(found == NULL) {
  882. fsAdd(&functions, f);
  883. } else if(found->global) {
  884. cError("system functions cannot be overwritten");
  885. } else if(found->address != -1 || f->address == -1 || found->global) {
  886. cError("function registered twice");
  887. } else if(!dtCompare(found->returnType, f->returnType)) {
  888. cError("function redeclared with different return type");
  889. } else {
  890. found->address = f->address;
  891. }
  892. }
  893. static void cInnerFunction(Function* f) {
  894. cConsumeToken(T_OPEN_CURVED_BRACKET);
  895. cAddOperation(OP_RESERVE);
  896. int32 p = cReserveInt32();
  897. cAddInt32(f->size);
  898. returnIndex = 0;
  899. cConsumeScope();
  900. if(!dtIsVoid(returnType) && hasReturn <= 0) {
  901. cError("missing return");
  902. }
  903. cAddInt32Operation(OP_RETURN, vars.maxAddress);
  904. cSetInt32(p, vars.maxAddress);
  905. for(int i = 0; i < returnIndex; i++) {
  906. cSetInt32(returns[i], vars.maxAddress);
  907. }
  908. returnIndex = 0;
  909. }
  910. static void cFunction(DataType rType) {
  911. rType = cExtendType(rType);
  912. Function f;
  913. cBuildFunction(&f, rType);
  914. Function* found = fsSearch(&functions, &f);
  915. if(cConsumeTokenIf(T_SEMICOLON)) {
  916. cAddFunction(found, &f);
  917. return;
  918. }
  919. cAddLine(line);
  920. cAddOperation(OP_GOTO);
  921. int32 end = cReserveInt32();
  922. f.address = code->length;
  923. cAddFunction(found, &f);
  924. returnType = rType;
  925. cInnerFunction(&f);
  926. cSetInt32(end, code->length);
  927. }
  928. static void cStruct() {
  929. cConsumeToken(T_LITERAL);
  930. const char* name = cReadString();
  931. if(stsSearch(&structs, name) != NULL) {
  932. cError("struct '%s' registered twice", name);
  933. }
  934. Struct* st = stsAdd(&structs, name);
  935. DataType self = dtStruct(st);
  936. cConsumeToken(T_OPEN_CURVED_BRACKET);
  937. while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
  938. DataType dt = cReadType(cReadTokenAndLine());
  939. if(dtCompare(dt, self)) {
  940. cError("struct %s contains itself", name);
  941. }
  942. cConsumeToken(T_LITERAL);
  943. stAddVariable(st, cReadString(), dt);
  944. cConsumeToken(T_SEMICOLON);
  945. }
  946. cConsumeToken(T_SEMICOLON);
  947. }
  948. static void cGlobalScope(Token t) {
  949. switch(t) {
  950. case T_VOID: cFunction(dtVoid()); break;
  951. case T_STRUCT: cStruct(); break;
  952. default: cFunction(cReadType(t));
  953. }
  954. }
  955. static void cCallMain() {
  956. Function f;
  957. fInit(&f, "main", line);
  958. Function* found = fsSearch(&functions, &f);
  959. if(found != NULL && dtIsVoid(found->returnType)) {
  960. cAddInt32Operation(OP_PUSH_INT32, 0);
  961. cAddInt32Operation(OP_GOSUB, found->address);
  962. cAddInt32(found->size);
  963. }
  964. }
  965. static void cForEachLine() {
  966. while(true) {
  967. Token t = cReadTokenAndLine();
  968. if(t == T_END) {
  969. break;
  970. }
  971. cGlobalScope(t);
  972. }
  973. cCallMain();
  974. }
  975. static void cLinkQueuedFunctions() {
  976. for(int i = 0; i < functionQueue.entries; i++) {
  977. Function* f = functionQueue.data + i;
  978. Function* found = fsSearch(&functions, f);
  979. if(found == NULL || found->address == -1) {
  980. line = f->line;
  981. cError("unknown function");
  982. }
  983. cSetInt32(f->address, found->address);
  984. }
  985. }
  986. static void cAllocAndCompile() {
  987. forWhileStack = 0;
  988. breakIndex = 0;
  989. returnType = dtVoid();
  990. onLine = false;
  991. vsInit(&vars);
  992. fsInit(&functions);
  993. fsInit(&functionQueue);
  994. stsInit(&structs);
  995. if(!setjmp(errorJump)) {
  996. cForEachLine();
  997. cLinkQueuedFunctions();
  998. }
  999. stsDelete(&structs);
  1000. fsDelete(&functionQueue);
  1001. fsDelete(&functions);
  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. }