Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. package h4
  2.  
  3. import scala.language.experimental.macros
  4. import scala.reflect.macros.blackbox.Context
  5.  
  6. abstract class Expression
  7. case class Var(name: String) extends Expression
  8. case class Number(num: Double) extends Expression
  9. case class BinOp(operator: String, left: Expression, right: Expression) extends Expression
  10.  
  11.  
  12. class ExpressionImplicitsImpl(val c: Context) {
  13. import c.universe._
  14.  
  15. def getExpr(tree: Tree): Tree = {
  16. return tree match {
  17. case Ident(TermName(name)) => q"""Var(${name})"""
  18. case Literal(Constant(name: Int)) => q"""Number($name)"""
  19. case Literal(Constant(name: Double)) => q"""Number($name)"""
  20. case Apply(Select(left, operator), List(right)) => q"""BinOp(${operator.toString()}, ${getExpr(left)}, ${getExpr(right)})"""
  21. case _ => throw new UnsupportedOperationException()
  22. }
  23. }
  24.  
  25. def expr(exprTree: c.Expr[AnyRef]): c.Expr[Expression] = {
  26. val e = exprTree.tree match {
  27. case Function(params, tree) => getExpr(tree)
  28. case _ => throw new Exception("Not supported.")
  29. }
  30. return c.Expr[Expression](e)
  31. }
  32. }
  33.  
  34. object ExpressionImplicits {
  35. def expr(exprTree: AnyRef): Expression = macro ExpressionImplicitsImpl.expr
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement