Subato

Resource Files

Interpreter einer While-Sprache

Gegeben seien Records, die einen abstrakten Syntaxbaum von Ausdrücken einer kleinen Programmiersprache, mit Variablen, Konstanten, Operatorausdrücken, Fallunterscheidungen und einer While-Schleife bestehen.

Sie sollen mit Hilfe eines instanceof-Pattern des Java 15 Previews eine Methode schreiben, die ein Programm auswertet. Dabei soll die Auswertung ein Wert des Typs long ergeben. Bei Bedingungen wird 0L als false und alle anderen Werte als true interpretiert werden.


package name.panitz; import java.util.function.LongBinaryOperator; import java.util.List; import java.util.Map; import java.util.TreeMap; public class Interpreter{ public static enum Op{plus,minus,div,mod,mult; public LongBinaryOperator fun(){ return switch(this) { case plus -> (x,y)->x+y; case minus -> (x,y)->x-y; case div -> (x,y)->x/y; case mod -> (x,y)->x%y; case mult -> (x,y)->x*y; }; } } public static record Var(String name){} public static record Num(long n){} public static record OpEx(Object l,Op op, Object r){} public static record Assign(String name,Object o){} public static record If(Object cond,Object then,Object otherwise){} public static record While(Object cond,Object body){} public static record Sequence(List<Object> sts){} Map<String,Long> env = new TreeMap<>(); public long eval(Object o){ if (o instanceof Num n) return n.n; if (o instanceof Var v) return env.get(v.name); /* TODO fill in the other expression types. */ throw new RuntimeException("Unknown expression: "+o); } }
java
You are not logged in and therefore you cannot submit a solution.