aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/scala/magnolia.scala
blob: d2978b55c17bef64bb95d9397b8ee820613e3efe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package magnolia

import scala.reflect._, macros._
import macrocompat.bundle
import scala.util.Try
import scala.collection.immutable.ListMap
import language.existentials
import language.higherKinds

@bundle
class Macros(val c: whitebox.Context) {
  import c.universe._
  import CompileTimeState._

  private def findType(key: Type): Option[TermName] =
    recursionStack(c.enclosingPosition).frames.find(_.genericType == key).map(_.termName(c))

  private def recurse[T](path: TypePath, key: Type, value: TermName)(fn: => T):
      Option[T] = {
    recursionStack = recursionStack.updated(
      c.enclosingPosition,
      recursionStack.get(c.enclosingPosition).map(_.push(path, key, value)).getOrElse(
          Stack(List(Frame(path, key, value)), Nil))
    )
    
    try Some(fn) catch { case e: Exception => None } finally {
      val currentStack = recursionStack(c.enclosingPosition)
      recursionStack = recursionStack.updated(c.enclosingPosition,
          currentStack.pop())
    }
  }
  
  private val removeLazy: Transformer = new Transformer {
    override def transform(tree: Tree): Tree = tree match {
      case q"_root_.magnolia.Lazy.apply[$returnType](${Literal(Constant(method: String))})" =>
        q"${TermName(method)}"
      case _ =>
        super.transform(tree)
    }
  }
  
  private def getImplicit(paramName: Option[String],
                          genericType: Type,
                          typeConstructor: Type,
                          assignedName: TermName,
                          derivationImplicit: Either[Tree, Tree]): Tree = {
    
    findType(genericType).map { methodName =>
      val methodAsString = methodName.encodedName.toString
      val searchType = appliedType(typeConstructor, genericType)
      q"_root_.magnolia.Lazy.apply[$searchType]($methodAsString)"
    }.orElse {
      val searchType = appliedType(typeConstructor, genericType)
      findType(genericType).map { _ =>
        directInferImplicit(genericType, typeConstructor, derivationImplicit)
      }.getOrElse {
        scala.util.Try {
          val genericTypeName: String = genericType.typeSymbol.name.encodedName.toString.toLowerCase
          val assignedName: TermName = TermName(c.freshName(s"${genericTypeName}Typeclass"))
          recurse(ChainedImplicit(genericType.toString), genericType, assignedName) {
            val inferredImplicit = c.inferImplicitValue(searchType, false, false)
            q"""{
              def $assignedName: $searchType = $inferredImplicit
              $assignedName
            }"""
          }.get
        }.toOption.orElse(directInferImplicit(genericType, typeConstructor, derivationImplicit))
      }
    }.getOrElse {
      val currentStack: Stack = recursionStack(c.enclosingPosition)
      
      val error = ImplicitNotFound(genericType.toString,
          recursionStack(c.enclosingPosition).frames.map(_.path))
      
      val updatedStack = currentStack.copy(errors = error :: currentStack.errors) 
      recursionStack = recursionStack.updated(c.enclosingPosition, updatedStack)
      c.abort(c.enclosingPosition, s"Could not find type class for type $genericType")
    }
  }
  
  private def directInferImplicit(genericType: Type,
         typeConstructor: Type,
         derivationImplicit: Either[Tree, Tree]): Option[Tree] = {

    val genericTypeName: String = genericType.typeSymbol.name.encodedName.toString.toLowerCase
    val assignedName: TermName = TermName(c.freshName(s"${genericTypeName}Typeclass"))
    val typeSymbol = genericType.typeSymbol
    val classType = if(typeSymbol.isClass) Some(typeSymbol.asClass) else None
    val isCaseClass = classType.map(_.isCaseClass).getOrElse(false)
    val isSealedTrait = classType.map(_.isSealed).getOrElse(false)
    val isValueClass = genericType <:< typeOf[AnyVal]
    
    val resultType = appliedType(typeConstructor, genericType)

    val construct = if(isCaseClass) {
      val caseClassParameters = genericType.decls.collect {
        case m: MethodSymbol if m.isCaseAccessor => m.asMethod
      }

      val implicits = caseClassParameters.map { param =>
        val paramName = param.name.encodedName.toString
        
        val derivedImplicit = recurse(ProductType(paramName, genericType.toString), genericType,
            assignedName) {
          
          getImplicit(Some(paramName), param.returnType, typeConstructor, assignedName,
              derivationImplicit)
        
        }.getOrElse {
          c.abort(c.enclosingPosition, s"failed to get implicit for type $genericType")
        }
        
        derivationImplicit match {
          case Left(impl) =>
            val dereferencedValue = q"$impl.dereference(sourceParameter, ${param.name.toString})"
            q"$impl.call($derivedImplicit, $dereferencedValue)"
          case Right(impl) => 
            val paramName = TermName(param.name.toString)
            val dereferencedValue = q"sourceParameter.$paramName"
            q"$impl.call($derivedImplicit, $dereferencedValue)"
        }
      }

      derivationImplicit match {
        case Left(_) =>
          Some(q"new $genericType(..$implicits)")
        case Right(impl) =>
          val namedImplicits = caseClassParameters.zip(implicits).map { case (param, tree) =>
            q"(${param.name.encodedName.toString}, $tree)"
          }
          
          Some(q"$impl.join(_root_.scala.collection.immutable.ListMap(..$namedImplicits))")
      }
    } else if(isSealedTrait) {

      val subtypes = classType.get.knownDirectSubclasses.to[List]

      if(subtypes.isEmpty) {
        c.info(c.enclosingPosition, s"could not find any direct subtypes of $typeSymbol", true)
        c.abort(c.enclosingPosition, "")
      }
      
      Some {
        val components = subtypes.map(_.asType.toType).map { searchType =>
          recurse(CoproductType(genericType.toString), genericType, assignedName) {
            getImplicit(None, searchType, typeConstructor, assignedName, derivationImplicit)
          }.getOrElse {
            c.abort(c.enclosingPosition, s"failed to get implicit for type $searchType")
          }
        }
        
        derivationImplicit match {
          case Left(impl) =>
            val reduction = components.reduce { (left, right) => q"$impl.combine($left, $right)" }
            q"$impl.call($reduction, sourceParameter)"
          case Right(impl) =>
            val parts = subtypes.tail.zip(components.tail)
            
            val base = q"""
              $impl.call(${components.head}, sourceParameter.asInstanceOf[${subtypes.head}])
            """
            
            parts.foldLeft(base) { case (aggregated, (componentType, derivedImplicit)) =>
              q"""
                if(sourceParameter.isInstanceOf[$componentType])
                  $impl.call($derivedImplicit, sourceParameter.asInstanceOf[$componentType])
                else $aggregated"""
            }
        }
      }
    } else None

    construct.map { const =>
      val impl = derivationImplicit.merge
      q"""{
        def $assignedName: $resultType = $impl.construct { sourceParameter => $const }
        $assignedName
      }"""
    }
  }
  
  def magnolia[T: WeakTypeTag, Typeclass: WeakTypeTag]: Tree = {

    val genericType: Type = weakTypeOf[T]
    val currentStack: Stack = recursionStack.get(c.enclosingPosition).getOrElse(Stack(List(), List()))
    val directlyReentrant = Some(genericType) == currentStack.frames.headOption.map(_.genericType)
    val typeConstructor: Type = weakTypeOf[Typeclass].typeConstructor
    
    val coDerivationTypeclass = weakTypeOf[CovariantDerivation[_]].typeConstructor
    val contraDerivationTypeclass = weakTypeOf[ContravariantDerivation[_]].typeConstructor
    
    val coDerivationType = appliedType(coDerivationTypeclass, List(typeConstructor))
    val contraDerivationType = appliedType(contraDerivationTypeclass, List(typeConstructor))
    val derivationImplicit = try {
      Left(c.untypecheck(c.inferImplicitValue(coDerivationType, false, false)))
    } catch {
      case e: Exception =>
        try Right(c.untypecheck(c.inferImplicitValue(contraDerivationType, false, false))) catch {
          case e: Exception =>
            c.info(c.enclosingPosition, s"could not find an implicit instance of "+
                s"CovariantDerivation[$typeConstructor] or "+
                s"ContravariantDerivation[$typeConstructor]", true)

            throw e
        }
    }
    
    if(directlyReentrant) throw DirectlyReentrantException()
   
    currentStack.errors.foreach { error =>
      if(!emittedErrors.contains(error)) {
        emittedErrors += error
        val trace = error.path.mkString("\n    in ", "\n    in ", "\n \n")
        val msg = s"could not derive ${typeConstructor} instance for type ${error.genericType}"
        c.info(c.enclosingPosition, msg+trace, true)
      }
    }

    val result: Option[Tree] = if(!currentStack.frames.isEmpty) {
      findType(genericType) match {
        case None =>
          directInferImplicit(genericType, typeConstructor, derivationImplicit)
        case Some(enclosingRef) =>
          val methodAsString = enclosingRef.toString
          val searchType = appliedType(typeConstructor, genericType)
          Some(q"_root_.magnolia.Lazy[$searchType]($methodAsString)")
      }
    } else {
      val typeConstructor: Type = weakTypeOf[Typeclass].typeConstructor
      directInferImplicit(genericType, typeConstructor, derivationImplicit)
    }
   
    if(currentStack.frames.isEmpty) recursionStack = Map()

    result.map { tree =>
      if(currentStack.frames.isEmpty) {
        val res = c.untypecheck(removeLazy.transform(tree))
        res
      } else tree
    }.getOrElse {
      c.abort(c.enclosingPosition, "could not infer typeclass for type $genericType")
    }

  }
}

private[magnolia] case class DirectlyReentrantException() extends
    Exception("attempt to recurse directly")

private[magnolia] object Lazy { def apply[T](method: String): T = ??? }

private[magnolia] object CompileTimeState {

  sealed trait TypePath
  case class CoproductType(typeName: String) extends TypePath {
    override def toString = s"coproduct type $typeName"
  }

  case class ProductType(paramName: String, typeName: String) extends TypePath {
    override def toString = s"parameter '$paramName' of product type $typeName"
  }

  case class ChainedImplicit(typeName: String) extends TypePath {
    override def toString = s"chained implicit of type $typeName"
  }

  case class ImplicitNotFound(genericType: String, path: List[TypePath])

  case class Stack(frames: List[Frame], errors: List[ImplicitNotFound]) {
    
    def push(path: TypePath, key: whitebox.Context#Type,
        value: whitebox.Context#TermName): Stack =
      Stack(Frame(path, key, value) :: frames, errors)
    
    def pop(): Stack = Stack(frames.tail, errors)
  }

  case class Frame(path: TypePath, genericType: whitebox.Context#Type,
      term: whitebox.Context#TermName) {
    def termName(c: whitebox.Context): c.TermName = term.asInstanceOf[c.TermName]
  }

  private[magnolia] var recursionStack: Map[api.Position, Stack] =
    Map()
  
  private[magnolia] var emittedErrors: Set[ImplicitNotFound] = Set()
}

trait CovariantDerivation[Typeclass[_]] {
  type Value
  def dereference(value: Value, param: String): Value
  def call[T](typeclass: Typeclass[T], value: Value): T
  def construct[T](body: Value => T): Typeclass[T]
  
  def combine[Supertype, Right <: Supertype](left: Typeclass[_ <: Supertype],
      right: Typeclass[Right]): Typeclass[Supertype]
}

trait ContravariantDerivation[Typeclass[_]] {
  type Return
  def call[T](typeclass: Typeclass[T], value: T): Return
  def construct[T](body: T => Return): Typeclass[T]
  def join(elements: ListMap[String, Return]): Return

}