Kajetan Johannes Hammerle 4 years ago
parent
commit
18c87bb02f
5 changed files with 21 additions and 5 deletions
  1. 12 4
      Compiler.c
  2. 4 0
      Tokenizer.c
  3. 1 1
      Tokenizer.h
  4. 2 0
      tests/calc/multiply
  5. 2 0
      tests/calc/multiply.out

+ 12 - 4
Compiler.c

@@ -63,22 +63,26 @@ static bool cConsumeTokenIf(Token t) {
     return false;
 }
 
-static bool cConstant() {
+static bool cExpression();
+
+static bool cPrimary() {
     if(cConsumeTokenIf(T_INT)) {
         int value;
         return tReadInt(&value) && cAddOperation(OP_PUSH_INT) && cAddBytes(&value, sizeof(int));
     } else if(cConsumeTokenIf(T_NULL)) {
         return cAddOperation(OP_PUSH_NULL);
+    } else if(cConsumeTokenIf(T_OPEN_BRACKET)) {
+        return cExpression() && cConsumeToken(T_CLOSE_BRACKET);
     }
     return false;
 }
 
 static bool cMul() {
-    if(!cConstant()) {
+    if(!cPrimary()) {
         return false;
     }
     while(cConsumeTokenIf(T_MUL)) {
-        if(!cConstant() || !cAddOperation(OP_MUL)) {
+        if(!cPrimary() || !cAddOperation(OP_MUL)) {
             return false;
         }
     }
@@ -97,8 +101,12 @@ static bool cAdd() {
     return true;
 }
 
+static bool cExpression() {
+    return cAdd();
+}
+
 static bool cPrint() {
-    return cAdd() && cConsumeToken(T_SEMICOLON) && cAddOperation(OP_PRINT);
+    return cExpression() && cConsumeToken(T_SEMICOLON) && cAddOperation(OP_PRINT);
 }
 
 static bool cLine() {

+ 4 - 0
Tokenizer.c

@@ -98,6 +98,8 @@ static bool tParseToken() {
         case '+': return tAddToken(T_ADD);
         case '*': return tAddToken(T_MUL);
         case ';': return tAddToken(T_SEMICOLON);
+        case '(': return tAddToken(T_OPEN_BRACKET);
+        case ')': return tAddToken(T_CLOSE_BRACKET);
     }
     tError("unknown character on line %d: %c", line, c);
     return false;
@@ -160,6 +162,8 @@ const char* tGetTokenName(Token token) {
         case T_MUL: return "*";
         case T_PRINT: return "print";
         case T_SEMICOLON: return ";";
+        case T_OPEN_BRACKET: return "(";
+        case T_CLOSE_BRACKET: return ")";
         case T_END: return "end";
     }
     return "Unknown";

+ 1 - 1
Tokenizer.h

@@ -3,7 +3,7 @@
 
 #include <stdbool.h>
 
-typedef enum Token { T_INT, T_NULL, T_ADD, T_MUL, T_PRINT, T_SEMICOLON, T_END } Token;
+typedef enum Token { T_INT, T_NULL, T_ADD, T_MUL, T_PRINT, T_SEMICOLON, T_OPEN_BRACKET, T_CLOSE_BRACKET, T_END } Token;
 
 bool tTokenize(const char* path);
 const char* tGetError();

+ 2 - 0
tests/calc/multiply

@@ -1,3 +1,5 @@
 print 2 * 3;
 print 3 + 4 * 5;
 print 6 + 7 * 8 + 9;
+print (3 + 4) * 5;
+print ((3 + 2) * (5 + 1));

+ 2 - 0
tests/calc/multiply.out

@@ -1,3 +1,5 @@
 6
 23
 71
+35
+30