Skip to content

Instantly share code, notes, and snippets.

@svenefftinge
Created September 4, 2012 13:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svenefftinge/3621045 to your computer and use it in GitHub Desktop.
Save svenefftinge/3621045 to your computer and use it in GitHub Desktop.
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(exp.name)
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