Compiler.c 32 KB

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