Skip to content

Commit 2a004b3

Browse files
committed
Check for division by zero and some code refactor
1 parent eef6d3f commit 2a004b3

File tree

2 files changed

+18
-9
lines changed

2 files changed

+18
-9
lines changed

source/calcool/expression.d

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,18 @@ class OperatorExpression(string op) : Expression
7373
}
7474
}
7575

76-
private enum str = "left.evaluate()" ~ op ~ "right.evaluate()";
7776
override real evaluate() {
78-
return mixin(str);
77+
const rhs = right.evaluate();
78+
static if (op == "/") {
79+
if (rhs == 0) {
80+
throw new ParseException("Devide by zero");
81+
}
82+
}
83+
return mixin("left.evaluate()" ~ op ~ "rhs");
7984
}
8085

8186
override string toString() @safe const {
82-
return str;
87+
return left.toString() ~ op ~ right.toString();
8388
}
8489
}
8590

source/calcool/parser.d

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ private:
3535

3636
public:
3737
Token[] input;
38+
private static const syntaxError = new ParseException("Syntax error");
3839

3940
this() {
4041
lexer = new Lexer();
@@ -83,15 +84,14 @@ public:
8384
}
8485

8586
if (start && input.length > 0 && input.front().type != TokenType.EOL) {
86-
input.length = 0;
87-
throw new ParseException("Syntax error");
87+
error();
8888
}
8989
return left;
9090

9191
} else {
92-
input.length = 0;
93-
throw new ParseException("Syntax error");
92+
error();
9493
}
94+
assert(false);
9595
}
9696

9797
private Precedence getPrecedence() {
@@ -106,14 +106,18 @@ public:
106106
} else if (t == TokenType.EOL) {
107107
return Precedence.START;
108108
} else {
109-
input.length = 0;
110-
throw new ParseException("Invalid syntax");
109+
error();
111110
}
112111
}
113112

114113
return Precedence.START;
115114
}
116115

116+
private void error() {
117+
input.length = 0;
118+
throw syntaxError;
119+
}
120+
117121
void expect(TokenType t) {
118122
if ((input.length > 0 && input.front().type != t) || input.length == 0) {
119123
import std.format : format;

0 commit comments

Comments
 (0)