Kajetan Johannes Hammerle 3 years ago
parent
commit
5666cea22e
7 changed files with 38 additions and 3 deletions
  1. 10 2
      Compiler.c
  2. 2 1
      Tokenizer.c
  3. 1 0
      Tokenizer.h
  4. 13 0
      tests/if/else
  5. 5 0
      tests/if/else.out
  6. 6 0
      tests/mix
  7. 1 0
      tests/mix.out

+ 10 - 2
Compiler.c

@@ -419,9 +419,17 @@ static void cIf() {
     cExpression();
     cConsumeToken(T_CLOSE_BRACKET);
     cAddOperation(OP_IF_GOTO);
-    int p = cReserveInt();
+    int ifP = cReserveInt();
     cConsumeBody();
-    cSetInt(p, code->length);
+    cSetInt(ifP, code->length);
+
+    if(cConsumeTokenIf(T_ELSE)) {
+        cAddOperation(OP_GOTO);
+        int elseP = cReserveInt();
+        cSetInt(ifP, code->length);
+        cConsumeBody();
+        cSetInt(elseP, code->length);
+    }
 }
 
 static void cLine(Token t) {

+ 2 - 1
Tokenizer.c

@@ -23,7 +23,7 @@ typedef struct Literal {
 } Literal;
 
 Literal LITERALS[] = {{"print", T_PRINT},       {"null", T_NULL},     {"true", T_TRUE}, {"false", T_FALSE},
-                      {"function", T_FUNCTION}, {"return", T_RETURN}, {"if", T_IF}};
+                      {"function", T_FUNCTION}, {"return", T_RETURN}, {"if", T_IF},     {"else", T_ELSE}};
 const int LITERAL_AMOUNT = sizeof(LITERALS) / sizeof(Literal);
 
 static void tError(const char* format, ...) {
@@ -269,6 +269,7 @@ const char* tGetTokenName(Token token) {
         case T_LITERAL: return "literal";
         case T_PRINT: return "print";
         case T_IF: return "if";
+        case T_ELSE: return "else";
         case T_FUNCTION: return "function";
         case T_RETURN: return "return";
         case T_COMMA: return ",";

+ 1 - 0
Tokenizer.h

@@ -30,6 +30,7 @@ typedef enum Token {
     T_LITERAL,
     T_PRINT,
     T_IF,
+    T_ELSE,
     T_FUNCTION,
     T_RETURN,
     T_COMMA,

+ 13 - 0
tests/if/else

@@ -0,0 +1,13 @@
+print 5;
+if(true) {
+    print 6;
+} else {
+    print 7;
+}
+print 8;
+if(false) {
+    print 9;
+} else {
+    print 10;
+}
+print 11;

+ 5 - 0
tests/if/else.out

@@ -0,0 +1,5 @@
+5
+6
+8
+10
+11

+ 6 - 0
tests/mix

@@ -0,0 +1,6 @@
+a = 5;
+b = 6;
+
+if(a + b < 20 && a > 3) {
+    print 1;
+}

+ 1 - 0
tests/mix.out

@@ -0,0 +1 @@
+1