|
| 1 | +package scalaxy |
| 2 | + |
| 3 | +import scala.language.dynamics |
| 4 | +import scala.language.experimental.macros |
| 5 | + |
| 6 | +import scala.reflect.ClassTag |
| 7 | +import scala.reflect.NameTransformer |
| 8 | +import scala.reflect.macros.Context |
| 9 | + |
| 10 | +/** |
| 11 | + Syntactic sugar to instantiate Java beans with a very Scala-friendly syntax. |
| 12 | +
|
| 13 | + The following expression: |
| 14 | +
|
| 15 | + import scalaxy.beans |
| 16 | +
|
| 17 | + new MyBean().set( |
| 18 | + foo = 10, |
| 19 | + bar = 12 |
| 20 | + ) |
| 21 | +
|
| 22 | + Gets replaced (and type-checked) at compile time by: |
| 23 | +
|
| 24 | + { |
| 25 | + val bean = new MyBean |
| 26 | + bean.setFoo(10) |
| 27 | + bean.setBar(12) |
| 28 | + bean |
| 29 | + } |
| 30 | +
|
| 31 | + Doesn't bring any runtime dependency (macro is self-erasing). |
| 32 | + Don't expect code completion from your IDE as of yet. |
| 33 | +*/ |
| 34 | +package object beans |
| 35 | +{ |
| 36 | + implicit def beansExtensions[T <: AnyRef](bean: T) = new { |
| 37 | + def set = new Dynamic { |
| 38 | + def applyDynamicNamed(name: String)(args: (String, Any)*): T = |
| 39 | + macro impl.applyDynamicNamedImpl[T] |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +package beans |
| 45 | +{ |
| 46 | + package object impl |
| 47 | + { |
| 48 | + // This needs to be public and statically accessible. |
| 49 | + def applyDynamicNamedImpl[T : c.WeakTypeTag] |
| 50 | + (c: Context) |
| 51 | + (name: c.Expr[String]) |
| 52 | + (args: c.Expr[(String, Any)]*) : c.Expr[T] = |
| 53 | + { |
| 54 | + import c.universe._ |
| 55 | + |
| 56 | + // Check that the method name is "create". |
| 57 | + name.tree match { |
| 58 | + case Literal(Constant(n)) => |
| 59 | + if (n != "apply") |
| 60 | + c.error(name.tree.pos, s"Expected 'apply', got '$n'") |
| 61 | + } |
| 62 | + |
| 63 | + // Get the bean. |
| 64 | + val Select(Apply(_, List(bean)), _) = c.typeCheck(c.prefix.tree) |
| 65 | + |
| 66 | + // Choose a non-existing name for our bean's val. |
| 67 | + val beanName = newTermName(c.fresh("bean")) |
| 68 | + |
| 69 | + // Create a declaration for our bean's val. |
| 70 | + val beanDef = ValDef(NoMods, beanName, TypeTree(bean.tpe), bean) |
| 71 | + |
| 72 | + // Try to find a setter in the bean type that can take values of the type we've got. |
| 73 | + def getSetter(name: String) = { |
| 74 | + bean.tpe.member(newTermName(name)) |
| 75 | + .filter(s => s.isMethod && s.asMethod.paramss.flatten.size == 1) |
| 76 | + } |
| 77 | + |
| 78 | + // Try to find a setter in the bean type that can take values of the type we've got. |
| 79 | + def getVarTypeFromSetter(s: Symbol) = { |
| 80 | + val Seq(param) = s.asMethod.paramss.flatten |
| 81 | + param.typeSignature |
| 82 | + } |
| 83 | + |
| 84 | + val values = args.map(_.tree).map { |
| 85 | + // Match Tuple2.apply[String, Any](fieldName, value). |
| 86 | + case Apply(_, List(Literal(Constant(fieldName: String)), value)) => |
| 87 | + (fieldName, value) |
| 88 | + } |
| 89 | + |
| 90 | + // Forbid duplicates. |
| 91 | + for ((fieldName, dupes) <- values.groupBy(_._1); if dupes.size > 1) { |
| 92 | + for ((_, value) <- dupes.drop(1)) |
| 93 | + c.error(value.pos, s"Duplicate value for property '$fieldName'") |
| 94 | + } |
| 95 | + |
| 96 | + // Generate one setter call per argument. |
| 97 | + val setterCalls = values map |
| 98 | + { |
| 99 | + case (fieldName, value) => |
| 100 | + |
| 101 | + // Check that all parameters are named. |
| 102 | + if (fieldName == null || fieldName == "") |
| 103 | + c.error(value.pos, "Please use named parameters.") |
| 104 | + |
| 105 | + // Get beans-style setter or Scala-style var setter. |
| 106 | + val setterSymbol = |
| 107 | + getSetter("set" + fieldName.capitalize) |
| 108 | + .orElse(getSetter(NameTransformer.encode(fieldName + "_="))) |
| 109 | + |
| 110 | + if (setterSymbol == NoSymbol) |
| 111 | + c.error(value.pos, s"Couldn't find a setter for property '$fieldName' in type ${bean.tpe}") |
| 112 | + |
| 113 | + val varTpe = getVarTypeFromSetter(setterSymbol) |
| 114 | + if (!(value.tpe weak_<:< varTpe)) |
| 115 | + c.error(value.pos, s"Setter ${bean.tpe}.${setterSymbol.name}($varTpe) does not accept values of type ${value.tpe}") |
| 116 | + |
| 117 | + Apply(Select(Ident(beanName), setterSymbol), List(value)) |
| 118 | + } |
| 119 | + // Build a block with the bean declaration, the setter calls and return the bean. |
| 120 | + c.Expr[T](Block(Seq(beanDef) ++ setterCalls :+ Ident(beanName): _*)) |
| 121 | + } |
| 122 | + } |
| 123 | +} |
0 commit comments