Implement variable declaration

This commit is contained in:
2019-12-16 22:41:58 +01:00
parent ee19cb9a00
commit 1c686fb0ea
5 changed files with 42 additions and 1 deletions

View File

@@ -101,6 +101,17 @@ public class EvalVisitor implements Visitor<Value> {
return null;
}
@Override
public Value visit(VariableDeclaration e) {
Value initialValue = null;
if (e.expression != null) {
initialValue = e.expression.welcome(this);
}
this.env.put(e.name, initialValue);
return null;
}
@Override
public Value visit(VariableAssignment e) {
Value result = e.expression.welcome(this);

View File

@@ -162,6 +162,18 @@ public class GenASM implements Visitor<Void> {
throw new RuntimeException("Das machen wir mal nicht, ne?!");
}
@Override
public Void visit(VariableDeclaration e) {
// If there is an initialization present,
// push it to the location of the local var
if (e.expression != null) {
e.expression.welcome(this);
int offset = this.env.get(e.name);
this.ex.write(" movq %rax, " + offset + "(%rbp)\n");
}
return null;
}
@Override
public Void visit(VariableAssignment e) {
e.expression.welcome(this);

View File

@@ -84,8 +84,13 @@ class GetVars implements Visitor<Void> {
}
@Override
public Void visit(VariableAssignment e) {
public Void visit(VariableDeclaration e) {
vars.add(e.name);
return null;
}
@Override
public Void visit(VariableAssignment e) {
e.expression.welcome(this);
return null;
}

View File

@@ -153,6 +153,18 @@ public class PrettyPrintVisitor implements Visitor<Void> {
return null;
}
@Override
public Void visit(VariableDeclaration e) {
ex.write("let " + e.name);
if (e.expression != null) {
ex.write(" = " + e.expression.welcome(this));
}
ex.write(";");
return null;
}
@Override
public Void visit(VariableAssignment e) {
ex.write(e.name + " = ");

View File

@@ -17,6 +17,7 @@ public interface Visitor<R> {
R visit(NegateExpression e);
R visit(IfStatement e);
R visit(PrintStatement e);
R visit(VariableDeclaration e);
R visit(VariableAssignment e);
R visit(ReturnStatement e);
R visit(Block e);