123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128 |
- #include <setjmp.h>
- #include <stdarg.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "Compiler.h"
- #include "DataType.h"
- #include "tokenizer/Tokenizer.h"
- #include "utils/Functions.h"
- #include "utils/Variables.h"
- #include "vm/Operation.h"
- #define ERROR_LENGTH 256
- static char error[ERROR_LENGTH] = {'\0'};
- static ByteCode* code;
- static int16 line = 1;
- static jmp_buf errorJump;
- #define RETURN_BUFFER 16
- #define BREAK_BUFFER 32
- #define DT_OPERATION(op) \
- case DT_INT: cAddOperation(OP_##op##_INT); break; \
- case DT_FLOAT: cAddOperation(OP_##op##_FLOAT); break;
- typedef DataType (*Parser)(void);
- static bool onLine = false;
- static Variables vars;
- static Variables globalVars;
- static Functions functions;
- static Functions functionQueue;
- static Structs structs;
- static int returns[RETURN_BUFFER];
- static int returnIndex = 0;
- static int hasReturn = 0;
- static DataType returnType;
- static int breaks[BREAK_BUFFER];
- static int breakIndex = 0;
- static int forWhileStack = 0;
- static int continueAt = 0;
- typedef struct {
- Operation intOp;
- Operation floatOp;
- Operation pointerOp;
- const char* name;
- } TypedOp;
- #define TYPE_OP(NAME, FLOAT, POINTER, text) \
- static const TypedOp TYPED_##NAME = {OP_##NAME##_INT, OP_##FLOAT, \
- OP_##POINTER, text};
- TYPE_OP(MUL, MUL_FLOAT, NOTHING, "*")
- TYPE_OP(DIV, DIV_FLOAT, NOTHING, "/")
- TYPE_OP(MOD, NOTHING, NOTHING, "%")
- TYPE_OP(ADD, ADD_FLOAT, NOTHING, "+")
- TYPE_OP(SUB, SUB_FLOAT, NOTHING, "-")
- TYPE_OP(LESS, LESS_FLOAT, NOTHING, "<")
- TYPE_OP(LESS_EQUAL, LESS_EQUAL_FLOAT, NOTHING, "<=")
- TYPE_OP(GREATER, GREATER_FLOAT, NOTHING, ">")
- TYPE_OP(GREATER_EQUAL, GREATER_EQUAL_FLOAT, NOTHING, ">=")
- TYPE_OP(EQUAL, EQUAL_FLOAT, EQUAL_POINTER, "==")
- TYPE_OP(NOT_EQUAL, NOT_EQUAL_FLOAT, NOT_EQUAL_POINTER, "!=")
- TYPE_OP(BIT_OR, NOTHING, NOTHING, "|")
- TYPE_OP(BIT_XOR, NOTHING, NOTHING, "^")
- TYPE_OP(BIT_AND, NOTHING, NOTHING, "&")
- TYPE_OP(LEFT_SHIFT, NOTHING, NOTHING, "<<")
- TYPE_OP(RIGHT_SHIFT, NOTHING, NOTHING, ">>")
- static void cError(const char* format, ...) {
- va_list args;
- va_start(args, format);
- vsnprintf(error, ERROR_LENGTH, format, args);
- va_end(args);
- longjmp(errorJump, 0);
- }
- static const char* cGetName(DataType dt) {
- return dtGetName(&structs, dt);
- }
- static void cInvalidOperation(DataType a, DataType b, const char* op) {
- cError("invalid operation: %s %s %s", cGetName(a), op, cGetName(b));
- }
- static void cNotDeclared(const char* name) {
- cError("variable %s has not been declared", name);
- }
- static void cDeclared(const char* name) {
- cError("%s has already been declared", name);
- }
- static void cTooMuchArguments() {
- cError("too much function arguments");
- }
- static void cUnexpectedToken(Token t) {
- cError("unexpected token: %s", tGetName(t));
- }
- #define BUFFER_SIZE 256
- static void cUnknownFunction(Function* f) {
- int max = 0;
- char buffer[BUFFER_SIZE] = {'\0'};
- for(int i = 0; i < f->arguments; i++) {
- const char* name = dtGetName(&structs, f->argumentTypes[i]);
- max += snprintf(buffer + max, BUFFER_SIZE - max, i > 0 ? ", %s" : "%s",
- name);
- }
- cError("unknown function: %s(%s)", f->name, buffer);
- }
- static void cAddOperation(Operation token) {
- unsigned char c = token;
- bcAddBytes(code, &c, 1);
- }
- static int32 cReserveInt32() {
- return bcReserveBytes(code, sizeof(int32));
- }
- static void cSetInt32(int p, int32 i) {
- bcSetBytes(code, p, &i, sizeof(int32));
- }
- static void cAddInt32(int32 i) {
- bcAddBytes(code, &i, sizeof(int32));
- }
- static void cAddInt32Operation(Operation token, int32 i) {
- cAddOperation(token);
- cAddInt32(i);
- }
- static void cAddByteOperation(Operation token, int8 i) {
- cAddOperation(token);
- bcAddBytes(code, &i, sizeof(int8));
- }
- static void cAddLine(int16 line) {
- cAddOperation(OP_LINE);
- bcAddBytes(code, &line, sizeof(int16));
- }
- static Token cReadTokenAndLine() {
- hasReturn--;
- Token t;
- if(tReadTokenAndLine(&t, &line)) {
- return T_END;
- }
- return t;
- }
- static void cConsumeToken(Token wanted) {
- Token t = cReadTokenAndLine();
- if(wanted != t) {
- cError("expected '%s' got '%s'", tGetName(wanted), tGetName(t));
- }
- }
- static bool cConsumeTokenIf(Token t) {
- return tPeekToken() == t && cReadTokenAndLine() == t;
- }
- static void cConstantInt32() {
- int32 value;
- if(tReadInt32(&value)) {
- cError("int token without an int");
- }
- cAddInt32Operation(OP_PUSH_INT, value);
- }
- static void cConstantFloat() {
- float value;
- if(tReadFloat(&value)) {
- cError("float token without a float");
- }
- cAddOperation(OP_PUSH_FLOAT);
- bcAddBytes(code, &value, sizeof(float));
- }
- static const char* cReadString() {
- const char* literal = tReadString();
- if(literal == NULL) {
- cError("literal without string on line %d", line);
- }
- return literal;
- }
- static int cGetSize(DataType dt) {
- return dtGetSize(dt, &structs);
- }
- static DataType cExtendType(DataType dt) {
- if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) {
- cConsumeToken(T_CLOSE_SQUARE_BRACKET);
- dt = dtToArray(dt);
- }
- return dt;
- }
- static DataType cReadType(Token t, bool force) {
- switch(t) {
- case T_INT: return dtInt();
- case T_FLOAT: return dtFloat();
- case T_LITERAL: {
- Struct* st = stsSearch(&structs, cReadString());
- if(st == NULL) {
- if(force) {
- cError("struct %s does not exist");
- } else {
- return dtVoid();
- }
- }
- return dtStruct(st);
- }
- default:
- if(force) {
- cUnexpectedToken(t);
- }
- return dtVoid();
- }
- }
- static DataType cReadExtendedType(Token t, bool force) {
- DataType dt = cReadType(t, force);
- if(!dtIsVoid(dt)) {
- dt = cExtendType(dt);
- }
- return dt;
- }
- static DataType cExpression();
- static void cLoadRef(DataType type) {
- if(dtIsArray(type)) {
- cAddOperation(OP_LOAD_ARRAY);
- return;
- }
- switch(type.type) {
- DT_OPERATION(LOAD);
- default: cError("cannot load type %s", cGetName(type));
- }
- }
- static DataType cUnpack(DataType dt) {
- if(dt.type != DT_STRUCT && dtRemovePointer(&dt)) {
- cLoadRef(dt);
- }
- return dt;
- }
- static DataType cUnpackedExpression() {
- return cUnpack(cExpression());
- }
- static void cCallFunctionArguments(Function* f) {
- if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return;
- }
- while(true) {
- DataType dt = cUnpackedExpression();
- if(fAddArgument(f, dt, &structs)) {
- cTooMuchArguments();
- } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return;
- }
- cConsumeToken(T_COMMA);
- }
- }
- static DataType cCallFunction(const char* name) {
- int returnAddress = bcGetAddress(code);
- Function f;
- fInit(&f, name, line);
- int oldOnLine = onLine;
- onLine = false;
- cCallFunctionArguments(&f);
- onLine = oldOnLine;
- Function* found = fsSearch(&functions, &f);
- if(found == NULL) {
- cUnknownFunction(&f);
- } else if(found->global) {
- cAddInt32Operation(OP_CALL, found->line);
- return found->returnType;
- }
- char push[1 + sizeof(int32)] = {OP_PUSH_INT};
- bcInsertBytes(code, push, sizeof(push), returnAddress);
- cAddOperation(OP_GOSUB);
- if(found->address == -1) {
- f.returnType = found->returnType;
- f.address = cReserveInt32();
- fsAdd(&functionQueue, &f);
- } else {
- cAddInt32(found->address);
- }
- cAddInt32(found->size);
- return found->returnType;
- }
- static void cStore(DataType left, DataType right, const char* name) {
- if(dtIsArray(left)) {
- if(!dtCompare(left, right)) {
- cInvalidOperation(left, right, name);
- }
- cAddOperation(OP_STORE_ARRAY);
- return;
- }
- if(!dtCompare(left, right)) {
- cInvalidOperation(left, right, name);
- }
- switch(left.type) {
- DT_OPERATION(STORE);
- default: cError("cannot store type %s", cGetName(left));
- }
- }
- static DataType cLiteral() {
- const char* literal = cReadString();
- if(cConsumeTokenIf(T_OPEN_BRACKET)) {
- return cCallFunction(literal);
- }
- Variable v;
- if(!vsSearch(&vars, &v, literal)) {
- if(v.type.pointer != 0) {
- if(v.type.type != DT_STRUCT) {
- cError("non struct type %s should not be a pointer here",
- cGetName(v.type));
- }
- cAddInt32Operation(OP_PUSH_STRUCT_REFERENCE, v.address);
- } else {
- cAddInt32Operation(OP_DEREFERENCE_VAR, v.address);
- }
- return dtToPointer(v.type);
- } else if(!vsSearch(&globalVars, &v, literal)) {
- cAddInt32Operation(OP_DEREFERENCE_GVAR, v.address);
- return dtToPointer(v.type);
- }
- cNotDeclared(literal);
- return dtVoid();
- }
- static DataType cText() {
- cAddOperation(OP_PUSH_TEXT);
- int32 lengthAddress = cReserveInt32();
- int32 length = 0;
- int32 c;
- while(!tReadInt32(&c) && c != 0) {
- cAddInt32(c);
- length++;
- }
- cSetInt32(lengthAddress, length);
- return dtText();
- }
- static DataType cBracketPrimary() {
- DataType result = cExpression();
- cConsumeToken(T_CLOSE_BRACKET);
- return result;
- }
- static void cArrayIndex() {
- if(!dtIsInt(cUnpackedExpression())) {
- cError("array index must be an int");
- }
- }
- static DataType cAllocArray() {
- DataType dt = cReadType(cReadTokenAndLine(), true);
- if(dt.array != 0) {
- cError("array type must not be an array");
- }
- cConsumeToken(T_OPEN_SQUARE_BRACKET);
- cArrayIndex();
- cConsumeToken(T_CLOSE_SQUARE_BRACKET);
- cAddInt32Operation(OP_NEW, cGetSize(dt));
- return dtToArray(dt);
- }
- static DataType cLength() {
- DataType array = cUnpackedExpression();
- if(!dtIsArray(array)) {
- cError("length expects an array");
- }
- cAddOperation(OP_LENGTH);
- return dtInt();
- }
- static DataType cPrimary() {
- Token t = cReadTokenAndLine();
- switch(t) {
- case T_INT_VALUE: cConstantInt32(); return dtInt();
- case T_FLOAT_VALUE: cConstantFloat(); return dtFloat();
- case T_TEXT: return cText();
- case T_OPEN_BRACKET: return cBracketPrimary();
- case T_LITERAL: return cLiteral();
- case T_NEW: return cAllocArray();
- case T_LENGTH: return cLength();
- default: cUnexpectedToken(t); return dtVoid();
- }
- }
- static void cRemoveReference(DataType* dt, const char* name) {
- if(!dtRemovePointer(dt)) {
- cError("%s needs a reference not %s", name, cGetName(*dt));
- }
- }
- static void cExpectType(DataType actual, DataType wanted, const char* name) {
- if(!dtCompare(actual, wanted)) {
- cError("%s needs %s not %s", name, cGetName(wanted), cGetName(actual));
- }
- }
- static void cChangeType(DataType* dt, Operation op, Operation pushOp,
- int change) {
- if(onLine) {
- cAddByteOperation(op, change);
- *dt = dtVoid();
- } else {
- cAddByteOperation(pushOp, change);
- }
- }
- static void cPostChange(DataType* dt, int change, const char* name) {
- cRemoveReference(dt, name);
- if(dtIsInt(*dt)) {
- cChangeType(dt, OP_CHANGE_INT, OP_PUSH_POST_CHANGE_INT, change);
- } else {
- cError("%s needs an int not %s", name, cGetName(*dt));
- }
- }
- static DataType cStructAccess(DataType dt) {
- Struct* st = dtGetStruct(&structs, dt);
- if(st == NULL) {
- cError(". expects a struct not %s", cGetName(dt));
- }
- cConsumeToken(T_LITERAL);
- const char* name = cReadString();
- Variable inner;
- if(vSearchStruct(&inner, &structs, st, name)) {
- cError("%s has no member %s", st->name, name);
- } else if(inner.address > 0) {
- cAddInt32Operation(OP_PUSH_INT, inner.address);
- cAddInt32Operation(OP_ADD_REFERENCE, 1);
- }
- return dtToPointer(inner.type);
- }
- static DataType cAccess() {
- DataType dt = cPrimary();
- while(true) {
- if(cConsumeTokenIf(T_INCREMENT)) {
- cPostChange(&dt, 1, "++");
- } else if(cConsumeTokenIf(T_DECREMENT)) {
- cPostChange(&dt, -1, "--");
- } else if(cConsumeTokenIf(T_POINT)) {
- cRemoveReference(&dt, ".");
- dt = cStructAccess(dt);
- } else if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) {
- if(!dtIsArray(dt)) {
- cError("[] needs an array");
- }
- cAddOperation(OP_LOAD_ARRAY);
- dtRemovePointer(&dt);
- cArrayIndex("index");
- cConsumeToken(T_CLOSE_SQUARE_BRACKET);
- cAddInt32Operation(OP_ADD_REFERENCE, cGetSize(dt));
- dt = dtToPointer(dtRemoveArray(dt));
- } else {
- return dt;
- }
- }
- }
- static DataType cPreChange(DataType dt, int change, const char* name) {
- cRemoveReference(&dt, name);
- if(dtIsInt(dt)) {
- cChangeType(&dt, OP_CHANGE_INT, OP_PUSH_PRE_CHANGE_INT, change);
- } else {
- cError("%s needs an int not %s", name, cGetName(dt));
- }
- return dt;
- }
- static DataType cInvertSign(DataType dt) {
- if(dtIsInt(dt)) {
- cAddOperation(OP_INVERT_SIGN_INT);
- } else if(dtIsFloat(dt)) {
- cAddOperation(OP_INVERT_SIGN_FLOAT);
- } else {
- cError("cannot invert sign of %s", cGetName(dt));
- }
- return dt;
- }
- static DataType cCast(DataType in, DataType a, Operation aOp, DataType out) {
- if(dtCompare(in, a)) {
- cAddOperation(aOp);
- } else {
- cError("cannot cast %s to %s", cGetName(in), cGetName(out));
- }
- return out;
- }
- static DataType cUnaryNot(DataType dt) {
- cExpectType(dt, dtInt(), "!");
- cAddOperation(OP_NOT);
- return dt;
- }
- static DataType cUnaryBitNot(DataType dt) {
- if(dtIsInt(dt)) {
- cAddOperation(OP_BIT_NOT_INT);
- } else {
- cError("~ needs an int not %s", cGetName(dt));
- }
- return dt;
- }
- static DataType cPreUnary() {
- int marker = tGetMarker();
- if(cConsumeTokenIf(T_OPEN_BRACKET)) {
- if(cConsumeTokenIf(T_FLOAT) && cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return cCast(cUnpack(cPreUnary()), dtInt(), OP_INT_TO_FLOAT,
- dtFloat());
- } else if(cConsumeTokenIf(T_INT) && cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return cCast(cUnpack(cPreUnary()), dtFloat(), OP_FLOAT_TO_INT,
- dtInt());
- }
- }
- tReset(marker);
- if(cConsumeTokenIf(T_INCREMENT)) {
- return cPreChange(cPreUnary(), 1, "++");
- } else if(cConsumeTokenIf(T_DECREMENT)) {
- return cPreChange(cPreUnary(), -1, "--");
- } else if(cConsumeTokenIf(T_SUB)) {
- return cInvertSign(cUnpack(cPreUnary()));
- } else if(cConsumeTokenIf(T_NOT)) {
- return cUnaryNot(cPreUnary());
- } else if(cConsumeTokenIf(T_BIT_NOT)) {
- return cUnaryBitNot(cPreUnary());
- }
- return cAccess();
- }
- static void cAddTypeOperation(DataType* a, Parser bf, const TypedOp* op) {
- *a = cUnpack(*a);
- DataType b = cUnpack(bf());
- if(!dtCompare(*a, b)) {
- cInvalidOperation(*a, b, op->name);
- } else if(dtIsInt(*a) && op->intOp != OP_NOTHING) {
- cAddOperation(op->intOp);
- } else if(dtIsFloat(*a) && op->floatOp != OP_NOTHING) {
- cAddOperation(op->floatOp);
- } else if(dtIsArray(*a) && op->pointerOp != OP_NOTHING) {
- cAddOperation(op->pointerOp);
- } else {
- cInvalidOperation(*a, b, op->name);
- }
- }
- static DataType cMul() {
- DataType a = cPreUnary();
- while(true) {
- if(cConsumeTokenIf(T_MUL)) {
- cAddTypeOperation(&a, cPreUnary, &TYPED_MUL);
- } else if(cConsumeTokenIf(T_DIV)) {
- cAddTypeOperation(&a, cPreUnary, &TYPED_DIV);
- } else if(cConsumeTokenIf(T_MOD)) {
- cAddTypeOperation(&a, cPreUnary, &TYPED_MOD);
- } else {
- return a;
- }
- }
- }
- static DataType cAdd() {
- DataType a = cMul();
- while(true) {
- if(cConsumeTokenIf(T_ADD)) {
- cAddTypeOperation(&a, cMul, &TYPED_ADD);
- } else if(cConsumeTokenIf(T_SUB)) {
- cAddTypeOperation(&a, cMul, &TYPED_SUB);
- } else {
- return a;
- }
- }
- }
- static DataType cShift() {
- DataType a = cAdd();
- while(true) {
- if(cConsumeTokenIf(T_LEFT_SHIFT)) {
- cAddTypeOperation(&a, cAdd, &TYPED_LEFT_SHIFT);
- } else if(cConsumeTokenIf(T_RIGHT_SHIFT)) {
- cAddTypeOperation(&a, cAdd, &TYPED_RIGHT_SHIFT);
- } else {
- return a;
- }
- }
- }
- static DataType cComparison() {
- DataType a = cShift();
- while(true) {
- if(cConsumeTokenIf(T_LESS)) {
- cAddTypeOperation(&a, cShift, &TYPED_LESS);
- a = dtInt();
- } else if(cConsumeTokenIf(T_LESS_EQUAL)) {
- cAddTypeOperation(&a, cShift, &TYPED_LESS_EQUAL);
- a = dtInt();
- } else if(cConsumeTokenIf(T_GREATER)) {
- cAddTypeOperation(&a, cShift, &TYPED_GREATER);
- a = dtInt();
- } else if(cConsumeTokenIf(T_GREATER_EQUAL)) {
- cAddTypeOperation(&a, cShift, &TYPED_GREATER_EQUAL);
- a = dtInt();
- } else {
- return a;
- }
- }
- }
- static DataType cEqual() {
- DataType a = cComparison();
- while(true) {
- if(cConsumeTokenIf(T_EQUAL)) {
- cAddTypeOperation(&a, cComparison, &TYPED_EQUAL);
- a = dtInt();
- } else if(cConsumeTokenIf(T_NOT_EQUAL)) {
- cAddTypeOperation(&a, cComparison, &TYPED_NOT_EQUAL);
- a = dtInt();
- } else {
- return a;
- }
- }
- }
- static DataType cRepeat(Token t, Parser f, const TypedOp* op) {
- DataType a = f();
- while(cConsumeTokenIf(t)) {
- cAddTypeOperation(&a, f, op);
- }
- return a;
- }
- static DataType cBitAnd() {
- return cRepeat(T_BIT_AND, cEqual, &TYPED_BIT_AND);
- }
- static DataType cBitXor() {
- return cRepeat(T_BIT_XOR, cBitAnd, &TYPED_BIT_XOR);
- }
- static DataType cBitOr() {
- return cRepeat(T_BIT_OR, cBitXor, &TYPED_BIT_OR);
- }
- static DataType cLogical(Parser f, Token t, Operation jump, Operation op) {
- DataType a = f();
- while(cConsumeTokenIf(t)) {
- cAddOperation(jump);
- int32 p = cReserveInt32();
- DataType b = f();
- if(!dtIsInt(a) || !dtIsInt(b)) {
- cInvalidOperation(a, b, tGetName(t));
- }
- cAddOperation(op);
- cSetInt32(p, code->length);
- }
- return a;
- }
- static DataType cAnd() {
- return cLogical(cBitOr, T_AND, OP_PEEK_FALSE_GOTO, OP_AND);
- }
- static DataType cExpression() {
- return cLogical(cAnd, T_OR, OP_PEEK_TRUE_GOTO, OP_OR);
- }
- static void cLine();
- static void cConsumeBody() {
- int oldLine = line;
- while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
- if(tPeekToken() == T_END) {
- line = oldLine;
- cError("non closed curved bracket");
- }
- cLine();
- }
- }
- static void cConsumeScope() {
- Scope scope;
- vsEnterScope(&vars, &scope);
- cConsumeBody();
- vsLeaveScope(&vars, &scope);
- }
- static void cAddReturn(Operation op) {
- if(returnIndex >= RETURN_BUFFER) {
- cError("too much returns in function");
- }
- cAddOperation(op);
- returns[returnIndex++] = cReserveInt32();
- }
- static void cReturn() {
- if(dtIsVoid(returnType)) {
- cConsumeToken(T_SEMICOLON);
- cAddReturn(OP_RETURN);
- hasReturn = 2;
- return;
- }
- DataType dt = cUnpackedExpression();
- if(!dtCompare(returnType, dt)) {
- cError("wrong return type, should be %s", cGetName(returnType));
- } else if(dtIsInt(dt)) {
- cAddReturn(OP_RETURN_INT);
- } else if(dtIsFloat(dt)) {
- cAddReturn(OP_RETURN_FLOAT);
- } else if(dtIsArray(dt)) {
- cAddReturn(OP_RETURN_POINTER);
- } else {
- cError("cannot return %s", cGetName(dt));
- }
- cConsumeToken(T_SEMICOLON);
- hasReturn = 2;
- }
- static void cIf() {
- cConsumeToken(T_OPEN_BRACKET);
- cExpectType(cExpression(), dtInt(), "if");
- cConsumeToken(T_CLOSE_BRACKET);
- cAddOperation(OP_IF_GOTO);
- int32 ifP = cReserveInt32();
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- cConsumeScope();
- cSetInt32(ifP, code->length);
- if(cConsumeTokenIf(T_ELSE)) {
- cAddOperation(OP_GOTO);
- int32 elseP = cReserveInt32();
- cSetInt32(ifP, code->length);
- if(cConsumeTokenIf(T_IF)) {
- cIf();
- } else {
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- cConsumeScope();
- }
- cSetInt32(elseP, code->length);
- }
- }
- static void cConsumeBreaks(int start, int address) {
- for(int i = start; i < breakIndex; i++) {
- cSetInt32(breaks[i], address);
- }
- breakIndex = start;
- }
- static void cWhile() {
- int start = code->length;
- cConsumeToken(T_OPEN_BRACKET);
- cExpectType(cExpression(), dtInt(), "while");
- cConsumeToken(T_CLOSE_BRACKET);
- cAddOperation(OP_IF_GOTO);
- int32 ifP = cReserveInt32();
- int breakStart = breakIndex;
- forWhileStack++;
- int oldContinue = continueAt;
- continueAt = start;
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- cConsumeScope();
- continueAt = oldContinue;
- forWhileStack--;
- cAddInt32Operation(OP_GOTO, start);
- cSetInt32(ifP, code->length);
- cConsumeBreaks(breakStart, code->length);
- }
- static void cOperationSet(DataType left, const TypedOp* op) {
- cAddOperation(OP_DUPLICATE_REFERENCE);
- cLoadRef(left);
- cAddTypeOperation(&left, cUnpackedExpression, op);
- cStore(left, left, "=");
- }
- static void cSetVariable() {
- onLine = true;
- DataType dt = cPreUnary();
- onLine = false;
- if(dtIsVoid(dt)) {
- return;
- }
- cRemoveReference(&dt, "setter");
- Token t = cReadTokenAndLine();
- switch(t) {
- case T_SET: cStore(dt, cUnpackedExpression(), "="); break;
- case T_ADD_SET: cOperationSet(dt, &TYPED_ADD); break;
- case T_SUB_SET: cOperationSet(dt, &TYPED_SUB); break;
- case T_MUL_SET: cOperationSet(dt, &TYPED_MUL); break;
- case T_DIV_SET: cOperationSet(dt, &TYPED_DIV); break;
- case T_MOD_SET: cOperationSet(dt, &TYPED_MOD); break;
- case T_BIT_AND_SET: cOperationSet(dt, &TYPED_BIT_AND); break;
- case T_BIT_OR_SET: cOperationSet(dt, &TYPED_BIT_OR); break;
- case T_BIT_XOR_SET: cOperationSet(dt, &TYPED_BIT_XOR); break;
- case T_LEFT_SHIFT_SET: cOperationSet(dt, &TYPED_LEFT_SHIFT); break;
- case T_RIGHT_SHIFT_SET: cOperationSet(dt, &TYPED_RIGHT_SHIFT); break;
- default: cUnexpectedToken(t);
- }
- }
- static void cDeclareSet(Variables* vs, DataType dt, const char* var,
- Operation op) {
- if(vsInScope(vs, var)) {
- cDeclared(var);
- }
- Variable* v = vsAdd(vs, var, dt, &structs);
- if(dt.type != DT_STRUCT || dtIsArray(dt)) {
- cConsumeToken(T_SET);
- cAddInt32Operation(op, v->address);
- DataType right = cUnpackedExpression();
- cStore(dt, right, "=");
- }
- }
- static bool cDeclaration(Token t) {
- DataType dt = cReadExtendedType(t, false);
- if(dtIsVoid(dt)) {
- return false;
- }
- cConsumeToken(T_LITERAL);
- const char* var = cReadString();
- cDeclareSet(&vars, dt, var, OP_DEREFERENCE_VAR);
- return true;
- }
- static void cLineExpression() {
- int marker = tGetMarker();
- Token t = cReadTokenAndLine();
- if(cDeclaration(t)) {
- return;
- }
- tReset(marker);
- cSetVariable();
- }
- static void cFor() {
- Scope scope;
- vsEnterScope(&vars, &scope);
- cConsumeToken(T_OPEN_BRACKET);
- cLineExpression();
- cConsumeToken(T_SEMICOLON);
- int startCheck = code->length;
- cExpectType(cExpression(), dtInt(), "for");
- cConsumeToken(T_SEMICOLON);
- cAddOperation(OP_IF_GOTO);
- int32 end = cReserveInt32();
- cAddOperation(OP_GOTO);
- int32 beginBody = cReserveInt32();
- int startPerLoop = code->length;
- cLineExpression();
- cAddInt32Operation(OP_GOTO, startCheck);
- cConsumeToken(T_CLOSE_BRACKET);
- cSetInt32(beginBody, code->length);
- int breakStart = breakIndex;
- forWhileStack++;
- int oldContinue = continueAt;
- continueAt = startPerLoop;
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- cConsumeBody();
- continueAt = oldContinue;
- forWhileStack--;
- cAddInt32Operation(OP_GOTO, startPerLoop);
- cSetInt32(end, code->length);
- cConsumeBreaks(breakStart, code->length);
- vsLeaveScope(&vars, &scope);
- }
- static void cBreak() {
- if(forWhileStack == 0) {
- cError("break without for or while");
- } else if(breakIndex >= BREAK_BUFFER) {
- cError("too much breaks");
- }
- cAddOperation(OP_GOTO);
- breaks[breakIndex++] = cReserveInt32();
- cConsumeToken(T_SEMICOLON);
- }
- static void cContinue() {
- if(forWhileStack == 0) {
- cError("continue without for or while");
- }
- cAddInt32Operation(OP_GOTO, continueAt);
- cConsumeToken(T_SEMICOLON);
- }
- static void cLine() {
- int marker = tGetMarker();
- Token t = cReadTokenAndLine();
- cAddLine(line);
- switch(t) {
- case T_OPEN_CURVED_BRACKET: cConsumeScope(); break;
- case T_RETURN: cReturn(); break;
- case T_IF: cIf(); break;
- case T_WHILE: cWhile(); break;
- case T_FOR: cFor(); break;
- case T_BREAK: cBreak(); break;
- case T_CONTINUE: cContinue(); break;
- default:
- tReset(marker);
- cLineExpression();
- cConsumeToken(T_SEMICOLON);
- }
- }
- static void cBuildFunction(Function* f, DataType rType, const char* name) {
- if(rType.type == DT_STRUCT && rType.array == 0) {
- cError("structs cannot be returned");
- }
- fInit(f, name, line);
- f->returnType = rType;
- vsReset(&vars);
- cConsumeToken(T_OPEN_BRACKET);
- if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return;
- }
- while(true) {
- DataType dt = cReadExtendedType(cReadTokenAndLine(), true);
- cConsumeToken(T_LITERAL);
- const char* name = cReadString();
- if(vsInScope(&vars, name)) {
- cDeclared(name);
- }
- if(dt.type == DT_STRUCT) {
- dt = dtToPointer(dt);
- }
- vsAdd(&vars, name, dt, &structs);
- if(fAddArgument(f, dt, &structs)) {
- cTooMuchArguments();
- } else if(cConsumeTokenIf(T_CLOSE_BRACKET)) {
- return;
- }
- cConsumeToken(T_COMMA);
- }
- }
- static void cAddFunction(Function* found, Function* f) {
- if(found == NULL) {
- fsAdd(&functions, f);
- } else if(found->global) {
- cError("system functions cannot be overwritten");
- } else if(found->address != -1 || f->address == -1 || found->global) {
- cError("function registered twice");
- } else if(!dtCompare(found->returnType, f->returnType)) {
- cError("function redeclared with different return type");
- } else {
- found->address = f->address;
- }
- }
- static void cInnerFunction(Function* f) {
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- cAddOperation(OP_RESERVE);
- int32 p = cReserveInt32();
- cAddInt32(f->size);
- returnIndex = 0;
- cConsumeScope();
- if(!dtIsVoid(returnType) && hasReturn <= 0) {
- cError("missing return");
- }
- cAddInt32Operation(OP_RETURN, vars.maxAddress);
- cSetInt32(p, vars.maxAddress);
- for(int i = 0; i < returnIndex; i++) {
- cSetInt32(returns[i], vars.maxAddress);
- }
- returnIndex = 0;
- }
- static void cFunction(DataType rType, const char* name) {
- Function f;
- cBuildFunction(&f, rType, name);
- Function* found = fsSearch(&functions, &f);
- if(cConsumeTokenIf(T_SEMICOLON)) {
- cAddFunction(found, &f);
- return;
- }
- cAddLine(line);
- cAddOperation(OP_GOTO);
- int32 end = cReserveInt32();
- f.address = code->length;
- cAddFunction(found, &f);
- returnType = rType;
- cInnerFunction(&f);
- cSetInt32(end, code->length);
- }
- static void cStruct() {
- cConsumeToken(T_LITERAL);
- const char* name = cReadString();
- if(stsSearch(&structs, name) != NULL) {
- cError("struct '%s' registered twice", name);
- }
- Struct* st = stsAdd(&structs, name);
- DataType self = dtStruct(st);
- cConsumeToken(T_OPEN_CURVED_BRACKET);
- while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) {
- DataType dt = cReadExtendedType(cReadTokenAndLine(), true);
- if(dtCompare(dt, self)) {
- cError("struct %s contains itself", name);
- }
- cConsumeToken(T_LITERAL);
- stAddVariable(st, cReadString(), dt);
- cConsumeToken(T_SEMICOLON);
- }
- cConsumeToken(T_SEMICOLON);
- }
- static void cGlobalScope(Token t) {
- if(t == T_STRUCT) {
- cStruct();
- return;
- }
- DataType dt = dtVoid();
- if(t != T_VOID) {
- dt = cReadExtendedType(t, true);
- }
- cConsumeToken(T_LITERAL);
- const char* name = cReadString();
- if(tPeekToken() == T_OPEN_BRACKET) {
- cFunction(dt, name);
- return;
- }
- cDeclareSet(&globalVars, dt, name, OP_DEREFERENCE_GVAR);
- cConsumeToken(T_SEMICOLON);
- }
- static void cCallMain() {
- Function f;
- fInit(&f, "main", line);
- Function* found = fsSearch(&functions, &f);
- if(found != NULL && dtIsVoid(found->returnType)) {
- cAddInt32Operation(OP_PUSH_INT, 0);
- cAddInt32Operation(OP_GOSUB, found->address);
- cAddInt32(found->size);
- }
- }
- static void cForEachLine() {
- cAddOperation(OP_GRESERVE);
- int p = cReserveInt32();
- while(true) {
- Token t = cReadTokenAndLine();
- if(t == T_END) {
- break;
- }
- cGlobalScope(t);
- }
- cCallMain();
- cSetInt32(p, globalVars.maxAddress);
- cAddInt32Operation(OP_GRESERVE, -globalVars.maxAddress);
- }
- static void cLinkQueuedFunctions() {
- for(int i = 0; i < functionQueue.entries; i++) {
- Function* f = functionQueue.data + i;
- Function* found = fsSearch(&functions, f);
- if(found == NULL || found->address == -1) {
- line = f->line;
- cUnknownFunction(f);
- }
- cSetInt32(f->address, found->address);
- }
- }
- static void cAllocAndCompile() {
- forWhileStack = 0;
- breakIndex = 0;
- returnType = dtVoid();
- onLine = false;
- vsInit(&vars);
- vsInit(&globalVars);
- fsInit(&functions);
- fsInit(&functionQueue);
- stsInit(&structs);
- if(!setjmp(errorJump)) {
- cForEachLine();
- cLinkQueuedFunctions();
- }
- stsDelete(&structs);
- fsDelete(&functionQueue);
- fsDelete(&functions);
- vsDelete(&globalVars);
- vsDelete(&vars);
- }
- ByteCode* cCompile() {
- error[0] = '\0';
- code = bcInit();
- cAllocAndCompile();
- if(error[0] != '\0') {
- bcDelete(code);
- return NULL;
- }
- return code;
- }
- const char* cGetError() {
- return error;
- }
- int cGetLine() {
- return line;
- }
|