Skip to content

Instantly share code, notes, and snippets.

@mads-hartmann
Created February 17, 2012 19:43
Show Gist options
  • Save mads-hartmann/1855077 to your computer and use it in GitHub Desktop.
Save mads-hartmann/1855077 to your computer and use it in GitHub Desktop.
AST Transformation
/*
* A PROBLEM.
*
* EXECUTIVE SUMMARY
*
* I have an AST. I want to map over it with _one_ function. The function
* should produce a valid AST i.e. the function should return an instance
* of the same class as the one it receives.
*
*/
object Test {
def main(args: Array[String]): Unit = {
trait Transformable {
// def transform(pf: PartialFuncton[?,?]) = ???
}
// AST definition
sealed trait Definition extends Transformable
case class Class(name: String, body: List[Statement]) extends Definition
sealed trait Statement extends Transformable
case class VariableWrite(id: String, value: Expression) extends Statement
case class Return(expr: Expression) extends Statement
sealed trait Expression extends Transformable
case class VariableAccess(id: String) extends Expression
case class Value(value: Int) extends Expression
// Build a simple test AST
val ast = Class("Thingy", List(
VariableWrite("foo", Value(42)),
Return(VariableAccess("foo"))
))
// ast transform {
// case x: Class => x.copy( name = x.name.reverse )
// case x: VariableWrite => x.copy( id = x.id.reverse )
// case x: VariableAccess => x.copy( id = x.id.reverse )
// case x: VariableAccess => VariableWrite(...) // Should NOT be allowed.
// }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment