Skip to content

Commit

Permalink
Check for division by zero and some code refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
TheWeirdDev committed May 10, 2020
1 parent eef6d3f commit 2a004b3
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
11 changes: 8 additions & 3 deletions source/calcool/expression.d
Original file line number Diff line number Diff line change
Expand Up @@ -73,13 +73,18 @@ class OperatorExpression(string op) : Expression
}
}

private enum str = "left.evaluate()" ~ op ~ "right.evaluate()";
override real evaluate() {
return mixin(str);
const rhs = right.evaluate();
static if (op == "/") {
if (rhs == 0) {
throw new ParseException("Devide by zero");
}
}
return mixin("left.evaluate()" ~ op ~ "rhs");
}

override string toString() @safe const {
return str;
return left.toString() ~ op ~ right.toString();
}
}

Expand Down
16 changes: 10 additions & 6 deletions source/calcool/parser.d
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ private:

public:
Token[] input;
private static const syntaxError = new ParseException("Syntax error");

this() {
lexer = new Lexer();
Expand Down Expand Up @@ -83,15 +84,14 @@ public:
}

if (start && input.length > 0 && input.front().type != TokenType.EOL) {
input.length = 0;
throw new ParseException("Syntax error");
error();
}
return left;

} else {
input.length = 0;
throw new ParseException("Syntax error");
error();
}
assert(false);
}

private Precedence getPrecedence() {
Expand All @@ -106,14 +106,18 @@ public:
} else if (t == TokenType.EOL) {
return Precedence.START;
} else {
input.length = 0;
throw new ParseException("Invalid syntax");
error();
}
}

return Precedence.START;
}

private void error() {
input.length = 0;
throw syntaxError;
}

void expect(TokenType t) {
if ((input.length > 0 && input.front().type != t) || input.length == 0) {
import std.format : format;
Expand Down

0 comments on commit 2a004b3

Please sign in to comment.