123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119 |
- #include <stdarg.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include "Compiler.h"
- #include "Operation.h"
- #include "Tokenizer.h"
- #define MAX_BYTES (1024 * 1024)
- #define ERROR_LENGTH 256
- static char error[ERROR_LENGTH] = {'\0'};
- static unsigned char byteCode[MAX_BYTES];
- static int writeIndex = 0;
- static void cError(const char* format, ...) {
- va_list args;
- va_start(args, format);
- vsnprintf(error, ERROR_LENGTH, format, args);
- va_end(args);
- }
- static bool cAddBytes(const void* data, int length) {
- if(writeIndex + length > MAX_BYTES) {
- cError("the compiler buffer is too small");
- return false;
- }
- memcpy(byteCode + writeIndex, data, length);
- writeIndex += length;
- return true;
- }
- static bool cAddOperation(Operation token) {
- unsigned char c = token;
- return cAddBytes(&c, 1);
- }
- static bool cConsumeToken(Token wanted) {
- Token t = tReadToken();
- if(wanted == t) {
- return true;
- }
- cError("unexpected token: expected '%s' got '%s'", tGetTokenName(wanted), tGetTokenName(t));
- return false;
- }
- static bool cConsumeTokenIf(Token t) {
- if(tPeekToken() == t) {
- tReadToken();
- return true;
- }
- return false;
- }
- static bool cConstant() {
- if(cConsumeToken(T_INT)) {
- int value;
- return tReadInt(&value) && cAddOperation(OP_PUSH_INT) && cAddBytes(&value, sizeof(int));
- }
- return false;
- }
- static bool cMul() {
- if(!cConstant()) {
- return false;
- }
- while(cConsumeTokenIf(T_MUL)) {
- if(!cConstant() || !cAddOperation(OP_MUL)) {
- return false;
- }
- }
- return true;
- }
- static bool cAdd() {
- if(!cMul()) {
- return false;
- }
- while(cConsumeTokenIf(T_ADD)) {
- if(!cMul() || !cAddOperation(OP_ADD)) {
- return false;
- }
- }
- return true;
- }
- static bool cPrint() {
- return cAdd() && cConsumeToken(T_SEMICOLON) && cAddOperation(OP_PRINT);
- }
- static bool cLine() {
- Token t = tReadToken();
- if(t == T_END) {
- return false;
- } else if(t == T_PRINT) {
- return cPrint();
- }
- cError("unexpected token: %s", tGetTokenName(t));
- return false;
- }
- unsigned char* cCompile(int* codeLength) {
- writeIndex = 0;
- while(cLine()) {
- }
- if(error[0] != '\0') {
- return NULL;
- }
- unsigned char* bytes = malloc(writeIndex);
- memcpy(bytes, byteCode, writeIndex);
- *codeLength = writeIndex;
- return bytes;
- }
- const char* cGetError() {
- return error;
- }
|