Skip to content

Instantly share code, notes, and snippets.

@isovector
Created February 27, 2015 18:29
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 isovector/2d51f09084f36d4ef59c to your computer and use it in GitHub Desktop.
Save isovector/2d51f09084f36d4ef59c to your computer and use it in GitHub Desktop.
package juicy.source.ast
trait Expression extends Visitable
trait Statement extends Visitable
trait BinOp extends Expression {
val lhs: Expression
val rhs: Expression
protected def rewriter[T <: BinOp]
(ctor: (Expression, Expression) => T)
(implicit rule: Rewriter) = {
rule(
ctor(
lhs.rewrite.asInstanceOf[Expression],
rhs.rewrite.asInstanceOf[Expression]
))
}
}
case class Add(lhs: Expression, rhs: Expression) extends BinOp {
def rewrite(implicit rule: Rewriter) = rewriter(Add.apply _)
}
case class Sub(lhs: Expression, rhs: Expression) extends BinOp {
def rewrite(implicit rule: Rewriter) = rewriter(Sub.apply _)
}
case class WhileStmnt(
cond: Expression,
body: Statement
) extends Statement {
def rewrite(implicit rule: Rewriter) =
rule(
WhileStmnt(
cond.rewrite.asInstanceOf[Expression],
body.rewrite.asInstanceOf[Statement]
))
}
case class ExprStmnt(
expr: Expression
) extends Statement {
def rewrite(implicit rule: Rewriter) =
rule(
ExprStmnt(
expr.rewrite.asInstanceOf[Expression]
))
}
ast.rewrite(Rewriter {
case stmnt@ExprStmnt(expr) =>
WhileStmnt(
expr,
stmnt)
case otherwise => otherwise
})
case class Rewriter(rule: Visitable => Visitable) {
def apply(node: Visitable): Visitable = rule(node)
}
trait Visitable {
def rewrite(implicit rule: Rewriter): Visitable
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment