Created
September 4, 2012 13:14
-
-
Save svenefftinge/3621045 to your computer and use it in GitHub Desktop.
AST construction with data typed in Xtend
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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