Browse Source

line information in compiler

Kajetan Johannes Hammerle 4 years ago
parent
commit
c24a784034
2 changed files with 15 additions and 6 deletions
  1. 14 5
      Compiler.c
  2. 1 1
      Tokenizer.c

+ 14 - 5
Compiler.c

@@ -14,6 +14,7 @@ static char error[ERROR_LENGTH] = {'\0'};
 
 static unsigned char byteCode[MAX_BYTES];
 static int writeIndex = 0;
+static int line = 1;
 
 static void cError(const char* format, ...) {
     va_list args;
@@ -37,18 +38,26 @@ static bool cAddOperation(Operation token) {
     return cAddBytes(&c, 1);
 }
 
-static bool cConsumeToken(Token wanted) {
+static Token tReadTokenAndLine() {
     Token t = tReadToken();
+    if(tReadInt(&line)) {
+        return t;
+    }
+    return T_END;
+}
+
+static bool cConsumeToken(Token wanted) {
+    Token t = tReadTokenAndLine();
     if(wanted == t) {
         return true;
     }
-    cError("unexpected token: expected '%s' got '%s'", tGetTokenName(wanted), tGetTokenName(t));
+    cError("unexpected token on line %d: expected '%s' got '%s'", line, tGetTokenName(wanted), tGetTokenName(t));
     return false;
 }
 
 static bool cConsumeTokenIf(Token t) {
     if(tPeekToken() == t) {
-        tReadToken();
+        tReadTokenAndLine();
         return true;
     }
     return false;
@@ -91,13 +100,13 @@ static bool cPrint() {
 }
 
 static bool cLine() {
-    Token t = tReadToken();
+    Token t = tReadTokenAndLine();
     if(t == T_END) {
         return false;
     } else if(t == T_PRINT) {
         return cPrint();
     }
-    cError("unexpected token: %s", tGetTokenName(t));
+    cError("unexpected token on line %d: %s", line, tGetTokenName(t));
     return false;
 }
 

+ 1 - 1
Tokenizer.c

@@ -33,7 +33,7 @@ static bool tAdd(const void* data, int length) {
 
 static bool tAddToken(Token token) {
     unsigned char c = token;
-    return tAdd(&c, 1);
+    return tAdd(&c, 1) && tAdd(&line, sizeof(int));
 }
 
 static bool tReadTokens(void* dest, int length) {