Control Flow 9
This commit is contained in:
parent
e749367886
commit
f0ff14e5b5
6 changed files with 133 additions and 14 deletions
|
|
@ -75,6 +75,12 @@ class Interpreter : Stmt.Visitor!void, Expr.Visitor!TValue {
|
|||
void visit(Stmt.Expression stmt){
|
||||
evaluate(stmt.expression);
|
||||
}
|
||||
void visit(Stmt.If stmt){
|
||||
if(isTruthy(evaluate(stmt.condition)))
|
||||
execute(stmt.thenBranch);
|
||||
else if(stmt.elseBranch)
|
||||
execute(stmt.elseBranch);
|
||||
}
|
||||
void visit(Stmt.Print stmt){
|
||||
TValue value = evaluate(stmt.expression);
|
||||
writeln(tvalueToString(value));
|
||||
|
|
@ -82,6 +88,10 @@ class Interpreter : Stmt.Visitor!void, Expr.Visitor!TValue {
|
|||
void visit(Stmt.Var stmt){
|
||||
environment.define(stmt.name.lexeme, stmt.initialiser is null ? TValue.nil(0) : evaluate(stmt.initialiser));
|
||||
}
|
||||
void visit(Stmt.While stmt){
|
||||
while(isTruthy(evaluate(stmt.condition)))
|
||||
execute(stmt.body);
|
||||
}
|
||||
|
||||
TValue visit(Expr.Literal expr){
|
||||
return expr.value;
|
||||
|
|
@ -101,6 +111,17 @@ class Interpreter : Stmt.Visitor!void, Expr.Visitor!TValue {
|
|||
assert(0);
|
||||
}
|
||||
}
|
||||
TValue visit(Expr.Logical expr){
|
||||
TValue left = evaluate(expr.left);
|
||||
if(expr.operator.type == TokenType.OR){
|
||||
if(isTruthy(left))
|
||||
return left;
|
||||
} else {
|
||||
if(!isTruthy(left))
|
||||
return left;
|
||||
}
|
||||
return evaluate(expr.right);
|
||||
}
|
||||
TValue visit(Expr.Binary expr){
|
||||
TValue left = evaluate(expr.left);
|
||||
TValue right = evaluate(expr.right);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue