Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package h4
- import scala.language.experimental.macros
- import scala.reflect.macros.blackbox.Context
- abstract class Expression
- case class Var(name: String) extends Expression
- case class Number(num: Double) extends Expression
- case class BinOp(operator: String, left: Expression, right: Expression) extends Expression
- class ExpressionImplicitsImpl(val c: Context) {
- import c.universe._
- def getExpr(tree: Tree): Tree = {
- return tree match {
- case Ident(TermName(name)) => q"""Var(${name})"""
- case Literal(Constant(name: Int)) => q"""Number($name)"""
- case Literal(Constant(name: Double)) => q"""Number($name)"""
- case Apply(Select(left, operator), List(right)) => q"""BinOp(${operator.toString()}, ${getExpr(left)}, ${getExpr(right)})"""
- case _ => throw new UnsupportedOperationException()
- }
- }
- def expr(exprTree: c.Expr[AnyRef]): c.Expr[Expression] = {
- val e = exprTree.tree match {
- case Function(params, tree) => getExpr(tree)
- case _ => throw new Exception("Not supported.")
- }
- return c.Expr[Expression](e)
- }
- }
- object ExpressionImplicits {
- def expr(exprTree: AnyRef): Expression = macro ExpressionImplicitsImpl.expr
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement