Skip to content

Commit d4b5779

Browse files
authored
[lab2] Give a sketch of an interpreter (#14)
* [lab2] Give a sketch of an interpreter * [lab2] Give a sketch of an interpreter
1 parent 5a5e263 commit d4b5779

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

notes/java.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,4 +164,47 @@ One thing that could be added here (or somewhere else) is, that there should be
164164
}
165165
return checkedFunDefs;
166166
167+
```
168+
169+
Now we will give an oversimplified sketch of the interpreter. All the functions below should be changed to solve lab 2 and the interface `Value` and its implementations (e.g. `Value.Void`) have to be defined.
170+
171+
```java
172+
void interpret(TypeChecker.AnnotatedProgram p) {
173+
defs = p.defs();
174+
if (!defs.containsKey("main")) {
175+
throw new RuntimeException("Main function not found");
176+
}
177+
runFunction(defs.get("main")); // TODO: deal with arguments...
178+
}
179+
180+
// TODO: Extends to functions with arguments
181+
Value runFunction(TypeChecker.TypedFunDef f) {
182+
var env = new Environment();
183+
for (var s : f.stms()) {
184+
run(s, env);
185+
}
186+
return new Value.Void();
187+
}
188+
189+
// TODO: Instead of 'env' there should be a stack or list of environments
190+
void run(Statement s, Environment env) {
191+
switch (s) {
192+
case Statement.Decl decl -> env.setVar(decl.name(), decl.type());
193+
case Statement.Expr expr -> evalExpr(expr.typedExpr(), env);
194+
};
195+
}
196+
197+
```
198+
199+
Depending on how `return` statements are implemented, it might be reasonable to return more information here than just `Value`s. For the following evaluation function for expressions, it should however be enough to return only a `Value`:
200+
201+
```java
202+
Value evalExpr(TypedExpr expr, Environment env) {
203+
return switch(expr) {
204+
case TypedExpr.Int anInt -> new Value.Int(anInt.i());
205+
case TypedExpr.Var var -> env.getVar(var.id());
206+
case TypedExpr.Assign assign -> // TODO: update environment(s);
207+
case TypedExpr.App app -> // TODO: run a function;
208+
};
209+
}
167210
```

0 commit comments

Comments
 (0)