#include #include #include #include #include #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 #define RETURN_BUFFER 16 #define BREAK_BUFFER 32 #define DT_OPERATION(op) \ case DT_INT: cAddOperation(OP_##op##_INT); break; \ case DT_BOOL: cAddOperation(OP_##op##_BOOL); break; \ case DT_FLOAT: cAddOperation(OP_##op##_FLOAT); break; typedef DataType (*Parser)(void); static jmp_buf errorJump; static char error[ERROR_LENGTH] = {'\0'}; static ByteCode* code; static int16 line = 1; static bool onLine = false; static Variables vars; 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 boolOp; Operation pointerOp; const char* name; } TypedOp; #define TYPE_OP(NAME, INT, FLOAT, BOOL, POINTER, text) \ static const TypedOp TYPED_##NAME = {OP_##INT, OP_##FLOAT, OP_##BOOL, \ OP_##POINTER, text}; TYPE_OP(MUL, MUL_INT, MUL_FLOAT, NOTHING, NOTHING, "*") TYPE_OP(DIV, DIV_INT, DIV_FLOAT, NOTHING, NOTHING, "/") TYPE_OP(MOD, MOD_INT, NOTHING, NOTHING, NOTHING, "%") TYPE_OP(ADD, ADD_INT, ADD_FLOAT, NOTHING, NOTHING, "+") TYPE_OP(SUB, SUB_INT, SUB_FLOAT, NOTHING, NOTHING, "-") TYPE_OP(LESS, LESS_INT, LESS_FLOAT, NOTHING, NOTHING, "<") TYPE_OP(LESS_EQUAL, GREATER_INT, GREATER_FLOAT, NOTHING, NOTHING, "<=") TYPE_OP(GREATER, GREATER_INT, GREATER_FLOAT, NOTHING, NOTHING, ">") TYPE_OP(GREATER_EQUAL, LESS_INT, LESS_FLOAT, NOTHING, NOTHING, ">=") TYPE_OP(EQUAL, EQUAL_INT, EQUAL_FLOAT, EQUAL_BOOL, EQUAL_POINTER, "==") TYPE_OP(NOT_EQUAL, EQUAL_INT, EQUAL_FLOAT, EQUAL_BOOL, EQUAL_POINTER, "!=") TYPE_OP(BIT_OR, BIT_OR, NOTHING, NOTHING, NOTHING, "|") TYPE_OP(BIT_XOR, BIT_XOR, NOTHING, NOTHING, NOTHING, "^") TYPE_OP(BIT_AND, BIT_AND, NOTHING, NOTHING, NOTHING, "&") TYPE_OP(LEFT_SHIFT, LEFT_SHIFT, NOTHING, NOTHING, NOTHING, "<<") TYPE_OP(RIGHT_SHIFT, RIGHT_SHIFT, NOTHING, 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)); } static void cAddOperation(Operation token) { unsigned char c = token; bcAddBytes(code, &c, 1); } static int cReserveInt() { return bcReserveBytes(code, sizeof(int)); } static void cSetInt(int p, int i) { bcSetBytes(code, p, &i, sizeof(int)); } static void cAddInt(int i) { bcAddBytes(code, &i, sizeof(int)); } static void cAddIntOperation(Operation token, int i) { cAddOperation(token); cAddInt(i); } static void cAddByteOperation(Operation token, char c) { cAddOperation(token); bcAddBytes(code, &c, sizeof(char)); } static void cAddLine(int16 i) { cAddOperation(OP_LINE); bcAddBytes(code, &i, sizeof(int16)); } static Token cReadTokenAndLine() { hasReturn--; Token t = tReadToken(); if(tReadInt16(&line)) { return t; } return T_END; } 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 cConstantInt() { int value; if(!tReadInt(&value)) { cError("int token without an int"); } cAddIntOperation(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 cDereference(DataType dt) { if(dtDereference(&dt)) { cError("%s dereferenced too often", cGetName(dt)); } return dt; } static DataType cExtendType(DataType dt) { while(cConsumeTokenIf(T_MUL)) { dt = cDereference(dt); } return dt; } static DataType cReadType(Token t) { switch(t) { case T_INT: return cExtendType(dtInt()); case T_BOOL: return cExtendType(dtBool()); case T_FLOAT: return cExtendType(dtFloat()); case T_LITERAL: { Struct* st = stsSearch(&structs, cReadString()); if(st == NULL) { cError("struct %s does not exist"); } return cExtendType(dtStruct(st)); } default: cUnexpectedToken(t); return dtVoid(); } } static DataType cExpression(); static void cLoadRef(DataType type) { if(dtIsPointer(type)) { cAddOperation(OP_REFERENCE); return; } switch(type.type) { DT_OPERATION(LOAD); case DT_STRUCT: cAddIntOperation(OP_LOAD, cGetSize(type)); break; default: cError("cannot load type %s", cGetName(type)); } } static DataType cUnpack(DataType dt) { if(dtRemoveVariable(&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) { cAddIntOperation(OP_PUSH_INT, 0); Function f; fInit(&f, name, line); int oldOnLine = onLine; onLine = false; cCallFunctionArguments(&f); onLine = oldOnLine; cAddOperation(OP_GOSUB); Function* found = fsSearch(&functions, &f); if(found == NULL) { cError("unknown function"); } else if(found->address == -1) { f.returnType = found->returnType; f.address = cReserveInt(); fsAdd(&functionQueue, &f); } else { cAddInt(found->address); } cAddInt(found->size); return found->returnType; } static void cStore(DataType left, DataType right, const char* name) { if(!dtCompare(left, right)) { cInvalidOperation(left, right, name); } else if(dtIsPointer(left)) { cAddOperation(OP_STORE_POINTER); return; } 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)) { cNotDeclared(literal); } cAddIntOperation(OP_DEREFERENCE_VAR, v.address); return dtToVariable(v.type); } static DataType cBracketPrimary() { DataType result = cExpression(); cConsumeToken(T_CLOSE_BRACKET); return result; } static void cArrayIndex(const char* name) { if(!dtIsInt(cUnpackedExpression())) { cError("array %s must be an int", name); } } static DataType cAllocArray() { DataType dt = cReadType(cReadTokenAndLine()); cConsumeToken(T_OPEN_SQUARE_BRACKET); cArrayIndex("size"); cConsumeToken(T_CLOSE_SQUARE_BRACKET); cAddIntOperation(OP_NEW, cGetSize(dt)); return cDereference(dt); } static DataType cLength() { DataType pointer = cUnpackedExpression(); if(!dtIsPointer(pointer)) { cError("length expects a pointer"); } cAddOperation(OP_LENGTH); return dtInt(); } static DataType cPrimary() { Token t = cReadTokenAndLine(); switch(t) { case T_CONST_INT: cConstantInt(); return dtInt(); case T_CONST_FLOAT: cConstantFloat(); return dtFloat(); case T_TRUE: cAddOperation(OP_PUSH_TRUE); return dtBool(); case T_FALSE: cAddOperation(OP_PUSH_FALSE); return dtBool(); 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(!dtRemoveVariable(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 cPostChange(DataType* dt, int change, const char* name) { cRemoveReference(dt, name); cExpectType(*dt, dtInt(), name); if(onLine) { cAddByteOperation(OP_INT_CHANGE, change); *dt = dtVoid(); } else { cAddByteOperation(OP_PUSH_POST_INT_CHANGE, change); } } static DataType cStructAccess(DataType dt, int pointers) { Struct* st = dtGetStruct(&structs, dt); if(st == NULL || dt.pointers != pointers) { cError(pointers == 0 ? ". expects a struct" : "-> expects a struct*"); } 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) { cAddIntOperation(OP_PUSH_INT, inner.address); cAddIntOperation(OP_ADD_REFERENCE, 1); } return dtToVariable(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, 0); } else if(cConsumeTokenIf(T_ARROW)) { dt = cStructAccess(cUnpack(dt), 1); } else if(cConsumeTokenIf(T_OPEN_SQUARE_BRACKET)) { dt = cUnpack(dt); if(!dtIsPointer(dt)) { cError("[] needs a pointer"); } cArrayIndex("index"); cConsumeToken(T_CLOSE_SQUARE_BRACKET); dt = dtReference(dt); cAddIntOperation(OP_ADD_REFERENCE, cGetSize(dt)); dt = dtToVariable(dt); } else { return dt; } } } static DataType cPreChange(DataType dt, int change, const char* name) { cRemoveReference(&dt, name); cExpectType(dt, dtInt(), name); if(onLine) { cAddByteOperation(OP_INT_CHANGE, change); return dtVoid(); } cAddByteOperation(OP_PUSH_PRE_INT_CHANGE, change); 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 cPreUnary() { 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)) { DataType dt = cPreUnary(); cExpectType(dt, dtBool(), "!"); cAddOperation(OP_NOT); return dt; } else if(cConsumeTokenIf(T_BIT_NOT)) { DataType dt = cPreUnary(); cExpectType(dt, dtInt(), "!"); cAddOperation(OP_BIT_NOT); return dt; } else if(cConsumeTokenIf(T_BIT_AND)) { DataType dt = cPreUnary(); cRemoveReference(&dt, "&"); return cDereference(dt); } else if(cConsumeTokenIf(T_MUL)) { DataType dt = cPreUnary(); if(!dtIsPointer(dt)) { cError("* expects a pointer"); } dt = dtReference(dt); if(!dtIsPointer(dt) && !dtIsVariable(dt)) { dt = dtToVariable(dt); } else { cAddOperation(OP_REFERENCE); } return dt; } 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(dtIsBool(*a) && op->boolOp != OP_NOTHING) { cAddOperation(op->boolOp); } else if(dtIsPointer(*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 = dtBool(); } else if(cConsumeTokenIf(T_LESS_EQUAL)) { cAddTypeOperation(&a, cShift, &TYPED_LESS_EQUAL); cAddOperation(OP_NOT); a = dtBool(); } else if(cConsumeTokenIf(T_GREATER)) { cAddTypeOperation(&a, cShift, &TYPED_GREATER); a = dtBool(); } else if(cConsumeTokenIf(T_GREATER_EQUAL)) { cAddTypeOperation(&a, cShift, &TYPED_GREATER_EQUAL); cAddOperation(OP_NOT); a = dtBool(); } else { return a; } } } static DataType cEqual() { DataType a = cComparison(); while(true) { if(cConsumeTokenIf(T_EQUAL)) { cAddTypeOperation(&a, cComparison, &TYPED_EQUAL); a = dtBool(); } else if(cConsumeTokenIf(T_NOT_EQUAL)) { cAddTypeOperation(&a, cComparison, &TYPED_NOT_EQUAL); cAddOperation(OP_NOT); a = dtBool(); } 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)) { a = cUnpack(a); cAddOperation(jump); int p = cReserveInt(); DataType b = cUnpack(f()); if(!dtIsBool(a) || !dtIsBool(b)) { cInvalidOperation(a, b, tGetName(t)); } cAddOperation(op); cSetInt(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++] = cReserveInt(); } static void cReturn() { if(dtIsVoid(returnType)) { cConsumeToken(T_SEMICOLON); cAddReturn(OP_RETURN); hasReturn = 2; return; } DataType dt = cUnpackedExpression(); if(!dtCompare(dt, returnType)) { cError("wrong return type, should be %s", cGetName(returnType)); } else if(dtIsInt(dt)) { cAddReturn(OP_RETURN_INT); } else if(dtIsBool(dt)) { cAddReturn(OP_RETURN_BOOL); } else if(dtIsFloat(dt)) { cAddReturn(OP_RETURN_FLOAT); } else if(dtIsPointer(dt)) { cAddReturn(OP_RETURN_POINTER); } else { cError("cannot return %s", cGetName(dt)); } cConsumeToken(T_SEMICOLON); hasReturn = 2; } static void cPrint() { DataType dt = cUnpackedExpression(); if(dtIsPointer(dt)) { cAddOperation(OP_PRINT_POINTER); cConsumeToken(T_SEMICOLON); return; } switch(dt.type) { DT_OPERATION(PRINT); default: cError("cannot print type %s", cGetName(dt)); } cConsumeToken(T_SEMICOLON); } static void cIf() { cConsumeToken(T_OPEN_BRACKET); cExpectType(cUnpackedExpression(), dtBool(), "if"); cConsumeToken(T_CLOSE_BRACKET); cAddOperation(OP_IF_GOTO); int ifP = cReserveInt(); cConsumeToken(T_OPEN_CURVED_BRACKET); cConsumeScope(); cSetInt(ifP, code->length); if(cConsumeTokenIf(T_ELSE)) { cAddOperation(OP_GOTO); int elseP = cReserveInt(); cSetInt(ifP, code->length); if(cConsumeTokenIf(T_IF)) { cIf(); } else { cConsumeToken(T_OPEN_CURVED_BRACKET); cConsumeScope(); } cSetInt(elseP, code->length); } } static void cConsumeBreaks(int start, int address) { for(int i = start; i < breakIndex; i++) { cSetInt(breaks[i], address); } breakIndex = start; } static void cWhile() { int start = code->length; cConsumeToken(T_OPEN_BRACKET); cExpectType(cUnpackedExpression(), dtBool(), "while"); cConsumeToken(T_CLOSE_BRACKET); cAddOperation(OP_IF_GOTO); int ifP = cReserveInt(); int breakStart = breakIndex; forWhileStack++; int oldContinue = continueAt; continueAt = start; cConsumeToken(T_OPEN_CURVED_BRACKET); cConsumeScope(); continueAt = oldContinue; forWhileStack--; cAddIntOperation(OP_GOTO, start); cSetInt(ifP, code->length); cConsumeBreaks(breakStart, code->length); } static void cDelete() { DataType pointer = cUnpackedExpression(); if(!dtIsPointer(pointer)) { cError("delete expects a pointer"); } cAddOperation(OP_DELETE); } 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 cDeclare(DataType dt) { dt = cExtendType(dt); cConsumeToken(T_LITERAL); const char* var = cReadString(); if(vsInScope(&vars, var)) { cDeclared(var); } Variable* v = vsAdd(&vars, var, dt, &structs); if(dt.type != DT_STRUCT || dtIsPointer(dt)) { cConsumeToken(T_SET); cAddIntOperation(OP_DEREFERENCE_VAR, v->address); cStore(v->type, cUnpackedExpression(), "="); } } static void cLineExpression() { int marker = tGetMarker(); Token t = cReadTokenAndLine(); if(t == T_LITERAL) { const char* literal = cReadString(); Struct* st = stsSearch(&structs, literal); if(st != NULL) { cDeclare(dtStruct(st)); return; } } switch(t) { case T_INT: cDeclare(dtInt()); break; case T_BOOL: cDeclare(dtBool()); break; case T_FLOAT: cDeclare(dtFloat()); break; case T_DELETE: cDelete(); break; default: tReset(marker); cSetVariable(); } } static void cFor() { Scope scope; vsEnterScope(&vars, &scope); cConsumeToken(T_OPEN_BRACKET); cLineExpression(); cConsumeToken(T_SEMICOLON); int startCheck = code->length; cExpectType(cUnpackedExpression(), dtBool(), "for"); cConsumeToken(T_SEMICOLON); cAddOperation(OP_IF_GOTO); int end = cReserveInt(); cAddOperation(OP_GOTO); int beginBody = cReserveInt(); int startPerLoop = code->length; cLineExpression(); cAddIntOperation(OP_GOTO, startCheck); cConsumeToken(T_CLOSE_BRACKET); cSetInt(beginBody, code->length); int breakStart = breakIndex; forWhileStack++; int oldContinue = continueAt; continueAt = startPerLoop; cConsumeToken(T_OPEN_CURVED_BRACKET); cConsumeBody(); continueAt = oldContinue; forWhileStack--; cAddIntOperation(OP_GOTO, startPerLoop); cSetInt(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++] = cReserveInt(); cConsumeToken(T_SEMICOLON); } static void cContinue() { if(forWhileStack == 0) { cError("continue without for or while"); } cAddIntOperation(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_PRINT: cPrint(); 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) { cConsumeToken(T_LITERAL); fInit(f, cReadString(), line); f->returnType = rType; vsReset(&vars); cConsumeToken(T_OPEN_BRACKET); if(cConsumeTokenIf(T_CLOSE_BRACKET)) { return; } while(true) { DataType dt = cReadType(cReadTokenAndLine()); cConsumeToken(T_LITERAL); const char* name = cReadString(); if(vsInScope(&vars, name)) { cDeclared(name); } 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->address != -1 || f->address == -1) { 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); int p = cReserveInt(); cAddInt(f->size); returnIndex = 0; cConsumeScope(); if(!dtIsVoid(returnType) && hasReturn <= 0) { cError("missing return"); } cAddIntOperation(OP_RETURN, vars.maxAddress); cSetInt(p, vars.maxAddress); for(int i = 0; i < returnIndex; i++) { cSetInt(returns[i], vars.maxAddress); } returnIndex = 0; } static void cFunction(DataType rType) { rType = cExtendType(rType); Function f; cBuildFunction(&f, rType); Function* found = fsSearch(&functions, &f); if(cConsumeTokenIf(T_SEMICOLON)) { cAddFunction(found, &f); return; } cAddLine(line); cAddOperation(OP_GOTO); int end = cReserveInt(); f.address = code->length; cAddFunction(found, &f); returnType = rType; cInnerFunction(&f); cSetInt(end, code->length); } static void cStruct() { cConsumeToken(T_LITERAL); const char* name = cReadString(); if(stsSearch(&structs, name) != NULL) { cError("struct registered twice"); } Struct* st = stsAdd(&structs, name); DataType self = dtStruct(st); cConsumeToken(T_OPEN_CURVED_BRACKET); while(!cConsumeTokenIf(T_CLOSE_CURVED_BRACKET)) { DataType dt = cReadType(cReadTokenAndLine()); 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) { switch(t) { case T_VOID: cFunction(dtVoid()); break; case T_STRUCT: cStruct(); break; default: cFunction(cReadType(t)); } } static void cCallMain() { Function f; fInit(&f, "main", line); Function* found = fsSearch(&functions, &f); if(found != NULL && dtIsVoid(found->returnType)) { cAddIntOperation(OP_PUSH_INT, 0); cAddIntOperation(OP_GOSUB, found->address); cAddInt(found->size); } } static void cForEachLine() { while(true) { Token t = cReadTokenAndLine(); if(t == T_END) { break; } cGlobalScope(t); } cCallMain(); } 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; cError("unknown function"); } cSetInt(f->address, found->address); } } static void cAllocAndCompile() { forWhileStack = 0; breakIndex = 0; returnType = dtVoid(); onLine = false; vsInit(&vars); fsInit(&functions); fsInit(&functionQueue); stsInit(&structs); if(!setjmp(errorJump)) { cForEachLine(); cLinkQueuedFunctions(); } stsDelete(&structs); fsDelete(&functionQueue); fsDelete(&functions); 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; }