Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
AST construction with data typed in Xtend
package basepack.exmaple2
import java.util.Map
import org.eclipse.xtend.lib.Data
class Eval {
def static void main(String...args) { new Eval().run } // run inside an instance instead of statically so we can operator overloading (and use extensions)
def evaluate(Map<String,Integer> it, Expression exp) {
switch exp {
Variable: get(
Number: exp.value
Multiply: evaluate(exp.x) * evaluate(exp.y)
Add: evaluate(exp.x) + evaluate(exp.y)
// for convenient AST construction:
def $(String varName) { new Variable(varName) }
def $(int value) { new Number(value) }
def operator_plus(Expression left, Expression right) { new Add(left, right) }
def operator_multiply(Expression left, Expression right) { new Multiply(left, right) }
def run() {
val env = newHashMap("a" -> 3, "b" -> 4, "c" -> 5)
val expressionTree = $('a') + $(2) * $('b')
println(evaluate(env, expressionTree))
abstract class Expression {}
@Data class Number extends Expression {
int value
@Data class Add extends Expression {
Expression x
Expression y
@Data class Multiply extends Add {}
@Data class Variable extends Expression {
String name
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.