From 2cd897dd1bb05981fac1fc9d61ee32f26a16c35b Mon Sep 17 00:00:00 2001 From: Loic Descotte Date: Sat, 11 Nov 2017 08:04:42 +0100 Subject: scalajs cross build --- build.sbt | 14 +- core/shared/src/main/scala/interface.scala | 157 ++++++++ core/shared/src/main/scala/magnolia.scala | 522 +++++++++++++++++++++++++++ core/src/main/scala/interface.scala | 157 -------- core/src/main/scala/magnolia.scala | 522 --------------------------- examples/shared/src/main/scala/decode.scala | 79 ++++ examples/shared/src/main/scala/default.scala | 35 ++ examples/shared/src/main/scala/eq.scala | 41 +++ examples/shared/src/main/scala/show.scala | 63 ++++ examples/src/main/scala/decode.scala | 79 ---- examples/src/main/scala/default.scala | 35 -- examples/src/main/scala/eq.scala | 41 --- examples/src/main/scala/show.scala | 63 ---- 13 files changed, 907 insertions(+), 901 deletions(-) create mode 100644 core/shared/src/main/scala/interface.scala create mode 100644 core/shared/src/main/scala/magnolia.scala delete mode 100644 core/src/main/scala/interface.scala delete mode 100644 core/src/main/scala/magnolia.scala create mode 100644 examples/shared/src/main/scala/decode.scala create mode 100644 examples/shared/src/main/scala/default.scala create mode 100644 examples/shared/src/main/scala/eq.scala create mode 100644 examples/shared/src/main/scala/show.scala delete mode 100644 examples/src/main/scala/decode.scala delete mode 100644 examples/src/main/scala/default.scala delete mode 100644 examples/src/main/scala/eq.scala delete mode 100644 examples/src/main/scala/show.scala diff --git a/build.sbt b/build.sbt index 27c95b6..81930f2 100644 --- a/build.sbt +++ b/build.sbt @@ -1,31 +1,37 @@ import com.typesafe.sbt.pgp.PgpKeys.publishSigned -lazy val core = project +lazy val core = crossProject .in(file("core")) .settings(buildSettings: _*) .settings(publishSettings: _*) .settings(scalaMacroDependencies: _*) .settings(moduleName := "magnolia") -lazy val examples = project +lazy val coreJVM = core.jvm +lazy val coreJS = core.js + +lazy val examples = crossProject .in(file("examples")) .settings(buildSettings: _*) .settings(publishSettings: _*) .settings(moduleName := "magnolia-examples") .dependsOn(core) +lazy val examplesJVM = examples.jvm +lazy val examplesJS = examples.js + lazy val tests = project .in(file("tests")) .settings(buildSettings: _*) .settings(unmanagedSettings) .settings(moduleName := "magnolia-tests") - .dependsOn(examples) + .dependsOn(examplesJVM) lazy val benchmarks = project .in(file("benchmarks")) .settings(buildSettings: _*) .settings(moduleName := "magnolia-benchmarks") - .dependsOn(examples) + .dependsOn(examplesJVM) lazy val buildSettings = Seq( organization := "com.propensive", diff --git a/core/shared/src/main/scala/interface.scala b/core/shared/src/main/scala/interface.scala new file mode 100644 index 0000000..54f8ce3 --- /dev/null +++ b/core/shared/src/main/scala/interface.scala @@ -0,0 +1,157 @@ +package magnolia + +import language.higherKinds + +/** represents a subtype of a sealed trait + * + * @tparam Typeclass type constructor for the typeclass being derived + * @tparam Type generic type of this parameter */ +trait Subtype[Typeclass[_], Type] { + + /** the type of subtype */ + type SType <: Type + + /** the name of the subtype + * + * This is the fully-qualified name of the type of subclass. */ + def label: String + + /** the typeclass instance associated with this subtype + * + * This is the instance of the type `Typeclass[SType]` which will have been discovered by + * implicit search, or derived by Magnolia. */ + def typeclass: Typeclass[SType] + + /** partial function defined the subset of values of `Type` which have the type of this subtype */ + def cast: PartialFunction[Type, SType] +} + +/** represents a parameter of a case class + * + * @tparam Typeclass type constructor for the typeclass being derived + * @tparam Type generic type of this parameter */ +trait Param[Typeclass[_], Type] { + + /** the type of the parameter being represented + * + * For exmaple, for a case class, + *
+    *  case class Person(name: String, age: Int)
+    *  
+ * the [[Param]] instance corresponding to the `age` parameter would have a [[PType]] equal to + * the type [[scala.Int]]. However, in practice, this type will never be universally quantified. + */ + type PType + + /** the name of the parameter */ + def label: String + + /** the typeclass instance associated with this parameter + * + * This is the instance of the type `Typeclass[PType]` which will have been discovered by + * implicit search, or derived by Magnolia. + * + * Its type is existentially quantified on this [[Param]] instance, and depending on the + * nature of the particular typeclass, it may either accept or produce types which are also + * existentially quantified on this same [[Param]] instance. */ + def typeclass: Typeclass[PType] + + /** provides the default value for this parameter, as defined in the case class constructor */ + def default: Option[PType] + + /** dereferences a value of the case class type, `Type`, to access the value of the parameter + * being represented + * + * When programming generically, against an unknown case class, with unknown parameter names + * and types, it is not possible to directly access the parameter values without reflection, + * which is undesirable. This method, whose implementation is provided by the Magnolia macro, + * will dereference a case class instance to access the parameter corresponding to this + * [[Param]]. + * + * Whilst the type of the resultant parameter value cannot be universally known at the use, its + * type will be existentially quantified on this [[Param]] instance, and the return type of the + * corresponding `typeclass` method will be existentially quantified on the same value. This is + * sufficient for the compiler to determine that the two values are compatible, and the value may + * be applied to the typeclass (in whatever way that particular typeclass provides). + * + * @param param the instance of the case class to be dereferenced + * @return the parameter value */ + def dereference(param: Type): PType +} + +/** represents a case class or case object and the context required to construct a new typeclass + * instance corresponding to it + * + * Instances of [[CaseClass]] provide access to all of the parameters of the case class, the full + * name of the case class type, and a boolean to determine whether the type is a case class or case + * object. + * + * @param typeName the name of the case class + * @param isObject true only if this represents a case object rather than a case class + * @param parametersArray an array of [[Param]] values for this case class + * @tparam Typeclass type constructor for the typeclass being derived + * @tparam Type generic type of this parameter */ +abstract class CaseClass[Typeclass[_], Type] private[magnolia] ( + val typeName: String, + val isObject: Boolean, + val isValueClass: Boolean, + parametersArray: Array[Param[Typeclass, Type]] +) { + + /** constructs a new instance of the case class type + * + * This method will be implemented by the Magnolia macro to make it possible to construct + * instances of case classes generically in user code, that is, without knowing their type + * concretely. + * + * To construct a new case class instance, the method takes a lambda which defines how each + * parameter in the new case class should be constructed. See the [[Param]] class for more + * information on constructing parameter values from a [[Param]] instance. + * + * @param makeParam lambda for converting a generic [[Param]] into the value to be used for + * this parameter in the construction of a new instance of the case class + * @return a new instance of the case class */ + def construct[Return](makeParam: Param[Typeclass, Type] => Return): Type + + /** a sequence of [[Param]] objects representing all of the parameters in the case class + * + * For efficiency, this sequence is implemented by an `Array`, but upcast to a + * [[scala.collection.Seq]] to hide the mutable collection API. */ + def parameters: Seq[Param[Typeclass, Type]] = parametersArray +} + +/** represents a sealed trait and the context required to construct a new typeclass instance + * corresponding to it + * + * Instances of `SealedTrait` provide access to all of the component subtypes of the sealed trait + * which form a coproduct, and to the fully-qualified name of the sealed trait. + * + * @param typeName the name of the sealed trait + * @param subtypesArray an array of [[Subtype]] instances for each subtype in the sealed trait + * @tparam Typeclass type constructor for the typeclass being derived + * @tparam Type generic type of this parameter */ +final class SealedTrait[Typeclass[_], Type](val typeName: String, + subtypesArray: Array[Subtype[Typeclass, Type]]) { + + /** a sequence of all the subtypes of this sealed trait */ + def subtypes: Seq[Subtype[Typeclass, Type]] = subtypesArray + + /** convenience method for delegating typeclass application to the typeclass corresponding to the + * subtype of the sealed trait which matches the type of the `value` + * + * @tparam Return the return type of the lambda, which should be inferred + * @param value the instance of the generic type whose value should be used to match on a + * particular subtype of the sealed trait + * @param handle lambda for applying the value to the typeclass for the particular subtype which + * matches + * @return the result of applying the `handle` lambda to subtype of the sealed trait which + * matches the parameter `value` */ + def dispatch[Return](value: Type)(handle: Subtype[Typeclass, Type] => Return): Return = + subtypes + .map { sub => + sub.cast.andThen { v => + handle(sub) + } + } + .reduce(_ orElse _)(value) +} diff --git a/core/shared/src/main/scala/magnolia.scala b/core/shared/src/main/scala/magnolia.scala new file mode 100644 index 0000000..51f594d --- /dev/null +++ b/core/shared/src/main/scala/magnolia.scala @@ -0,0 +1,522 @@ +package magnolia + +import scala.reflect._, macros._ +import scala.collection.immutable.ListMap +import language.existentials +import language.higherKinds + +/** the object which defines the Magnolia macro */ +object Magnolia { + import CompileTimeState._ + + /** derives a generic typeclass instance for the type `T` + * + * This is a macro definition method which should be bound to a method defined inside a Magnolia + * generic derivation object, that is, one which defines the methods `combine`, `dispatch` and + * the type constructor, `Typeclass[_]`. This will typically look like, + *
+    *  object Derivation {
+    *    // other definitions
+    *    implicit def gen[T]: Typeclass[T] = Magnolia.gen[T]
+    *  }
+    *  
+ * which would support automatic derivation of typeclass instances by calling + * `Derivation.gen[T]` or with `implicitly[Typeclass[T]]`, if the implicit method is imported + * into the current scope. + * + * The definition expects a type constructor called `Typeclass`, taking one *-kinded type + * parameter to be defined on the same object as a means of determining how the typeclass should + * be genericized. While this may be obvious for typeclasses like `Show[T]` which take only a + * single type parameter, Magnolia can also derive typeclass instances for types such as + * `Decoder[Format, Type]` which would typically fix the `Format` parameter while varying the + * `Type` parameter. + * + * While there is no "interface" for a derivation, in the object-oriented sense, the Magnolia + * macro expects to be able to call certain methods on the object within which it is bound to a + * method. + * + * Specifically, for deriving case classes (product types), the macro will attempt to call the + * `combine` method with an instance of [[CaseClass]], like so, + *
+    *    <derivation>.combine(<caseClass>): Typeclass[T]
+    *  
+ * That is to say, the macro expects there to exist a method called `combine` on the derivation + * object, which may be called with the code above, and for it to return a type which conforms + * to the type `Typeclass[T]`. The implementation of `combine` will therefore typically look + * like this, + *
+    *    def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = ...
+    *  
+ * however, there is the flexibility to provide additional type parameters or additional + * implicit parameters to the definition, provided these do not affect its ability to be invoked + * as described above. + * + * Likewise, for deriving sealed traits (coproduct or sum types), the macro will attempt to call + * the `dispatch` method with an instance of [[SealedTrait]], like so, + *
+    *    <derivation>.dispatch(<sealedTrait>): Typeclass[T]
+    *  
+ * so a definition such as, + *
+    *    def dispatch[T](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ...
+    *  
+ * will suffice, however the qualifications regarding additional type parameters and implicit + * parameters apply equally to `dispatch` as to `combine`. + * */ + def gen[T: c.WeakTypeTag](c: whitebox.Context): c.Tree = { + import c.universe._ + import scala.util.{Try, Success, Failure} + + val magnoliaPkg = q"_root_.magnolia" + val magnoliaObj = q"$magnoliaPkg.Magnolia" + val arrayCls = tq"_root_.scala.Array" + + val prefixType = c.prefix.tree.tpe + + def companionRef(tpe: Type): Tree = { + val global = c.universe match { case global: scala.tools.nsc.Global => global } + val globalTpe = tpe.asInstanceOf[global.Type] + val companion = globalTpe.typeSymbol.companionSymbol + if (companion != NoSymbol) + global.gen.mkAttributedRef(globalTpe.prefix, companion).asInstanceOf[Tree] + else q"${tpe.typeSymbol.name.toTermName}" + } + + val typeDefs = prefixType.baseClasses.flatMap { cls => + cls.asType.toType.decls.filter(_.isType).find(_.name.toString == "Typeclass").map { tpe => + tpe.asType.toType.asSeenFrom(prefixType, cls) + } + } + + val typeConstructorOpt = + typeDefs.headOption.map(_.typeConstructor) + + val typeConstructor = typeConstructorOpt.getOrElse { + c.abort(c.enclosingPosition, + "magnolia: the derivation object does not define the Typeclass type constructor") + } + + def checkMethod(termName: String, category: String, expected: String) = { + val term = TermName(termName) + val combineClass = c.prefix.tree.tpe.baseClasses + .find { cls => + cls.asType.toType.decl(term) != NoSymbol + } + .getOrElse { + c.abort( + c.enclosingPosition, + s"magnolia: the method `$termName` must be defined on the derivation object to derive typeclasses for $category" + ) + } + val firstParamBlock = combineClass.asType.toType.decl(term).asTerm.asMethod.paramLists.head + if (firstParamBlock.length != 1) + c.abort(c.enclosingPosition, + s"magnolia: the method `combine` should take a single parameter of type $expected") + } + + // FIXME: Only run these methods if they're used, particularly `dispatch` + checkMethod("combine", "case classes", "CaseClass[Typeclass, _]") + checkMethod("dispatch", "sealed traits", "SealedTrait[Typeclass, _]") + + def findType(key: Type): Option[TermName] = + recursionStack(c.enclosingPosition).frames.find(_.genericType == key).map(_.termName(c)) + + case class Typeclass(typ: c.Type, tree: c.Tree) + + def recurse[T](path: TypePath, key: Type, value: TermName)(fn: => T): Option[T] = { + val oldRecursionStack = recursionStack.get(c.enclosingPosition) + recursionStack = recursionStack.updated( + c.enclosingPosition, + oldRecursionStack.map(_.push(path, key, value)).getOrElse { + Stack(Map(), 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()) + } + } + + val removeDeferred: Transformer = new Transformer { + override def transform(tree: Tree): Tree = tree match { + case q"$magnoliaPkg.Deferred.apply[$returnType](${Literal(Constant(method: String))})" => + q"${TermName(method)}" + case _ => + super.transform(tree) + } + } + + def typeclassTree(paramName: Option[String], + genericType: Type, + typeConstructor: Type, + assignedName: TermName): Tree = { + + val searchType = appliedType(typeConstructor, genericType) + + val deferredRef = findType(genericType).map { methodName => + val methodAsString = methodName.decodedName.toString + q"$magnoliaPkg.Deferred.apply[$searchType]($methodAsString)" + } + + val foundImplicit = deferredRef.orElse { + val (inferredImplicit, newStack) = + recursionStack(c.enclosingPosition).lookup(c)(searchType) { + val implicitSearchTry = scala.util.Try { + val genericTypeName: String = + genericType.typeSymbol.name.decodedName.toString.toLowerCase + + val assignedName: TermName = TermName(c.freshName(s"${genericTypeName}Typeclass")) + + recurse(ChainedImplicit(genericType.toString), genericType, assignedName) { + c.inferImplicitValue(searchType, false, false) + }.get + } + + implicitSearchTry.toOption.orElse( + directInferImplicit(genericType, typeConstructor).map(_.tree) + ) + } + recursionStack = recursionStack.updated(c.enclosingPosition, newStack) + inferredImplicit + } + + foundImplicit.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) + + val stackPaths = recursionStack(c.enclosingPosition).frames.map(_.path) + val stack = stackPaths.mkString(" in ", "\n in ", "\n") + + c.abort(c.enclosingPosition, + s"magnolia: could not find typeclass for type $genericType\n$stack") + } + } + + def directInferImplicit(genericType: c.Type, typeConstructor: Type): Option[Typeclass] = { + + val genericTypeName: String = genericType.typeSymbol.name.decodedName.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 isCaseObject = classType.map(_.isModuleClass).getOrElse(false) + val isSealedTrait = classType.map(_.isSealed).getOrElse(false) + + val primitives = Set(typeOf[Double], + typeOf[Float], + typeOf[Short], + typeOf[Byte], + typeOf[Int], + typeOf[Long], + typeOf[Char], + typeOf[Boolean]) + + val isValueClass = genericType <:< typeOf[AnyVal] && !primitives.exists(_ =:= genericType) + + val resultType = appliedType(typeConstructor, genericType) + + val result = if (isCaseObject) { + // FIXME: look for an alternative which isn't deprecated on Scala 2.12+ + val obj = companionRef(genericType) + val className = genericType.typeSymbol.name.decodedName.toString + + val impl = q""" + ${c.prefix}.combine($magnoliaObj.caseClass[$typeConstructor, $genericType]( + $className, true, false, new $arrayCls(0), _ => $obj) + ) + """ + Some(Typeclass(genericType, impl)) + } else if (isCaseClass || isValueClass) { + val caseClassParameters = genericType.decls.collect { + case m: MethodSymbol if m.isCaseAccessor || (isValueClass && m.isParamAccessor) => + m.asMethod + } + val className = genericType.typeSymbol.name.decodedName.toString + + case class CaseParam(sym: c.universe.MethodSymbol, + typeclass: c.Tree, + paramType: c.Type, + ref: c.TermName) + + val caseParamsReversed: List[CaseParam] = caseClassParameters.foldLeft(List[CaseParam]()) { + case (acc, param) => + val paramName = param.name.decodedName.toString + val paramType = param.returnType.substituteTypes(genericType.etaExpand.typeParams, + genericType.typeArgs) + + val predefinedRef = acc.find(_.paramType == paramType) + + val caseParamOpt = predefinedRef.map { backRef => + CaseParam(param, q"()", paramType, backRef.ref) :: acc + } + + caseParamOpt.getOrElse { + val derivedImplicit = + recurse(ProductType(paramName, genericType.toString), genericType, assignedName) { + typeclassTree(Some(paramName), paramType, typeConstructor, assignedName) + }.getOrElse( + c.abort(c.enclosingPosition, s"failed to get implicit for type $genericType") + ) + + val ref = TermName(c.freshName("paramTypeclass")) + val assigned = q"""val $ref = $derivedImplicit""" + CaseParam(param, assigned, paramType, ref) :: acc + } + } + + val caseParams = caseParamsReversed.reverse + + val paramsVal: TermName = TermName(c.freshName("parameters")) + val fnVal: TermName = TermName(c.freshName("fn")) + + val preAssignments = caseParams.map(_.typeclass) + + val defaults = if (!isValueClass) { + val caseClassCompanion = genericType.companion + val constructorMethod = caseClassCompanion.decl(TermName("apply")).asMethod + val indexedConstructorParams = + constructorMethod.paramLists.head.map(_.asTerm).zipWithIndex + + indexedConstructorParams.map { + case (p, idx) => + if (p.isParamWithDefault) { + val method = TermName("apply$default$" + (idx + 1)) + q"_root_.scala.Some(${genericType.typeSymbol.companion.asTerm}.$method)" + } else q"_root_.scala.None" + } + } else List(q"_root_.scala.None") + + val assignments = caseParams.zip(defaults).zipWithIndex.map { + case ((CaseParam(param, typeclass, paramType, ref), defaultVal), idx) => + q"""$paramsVal($idx) = $magnoliaObj.param[$typeConstructor, $genericType, + $paramType]( + ${param.name.decodedName.toString}, $ref, $defaultVal, _.${param.name} + )""" + } + + Some( + Typeclass( + genericType, + q"""{ + ..$preAssignments + val $paramsVal: $arrayCls[Param[$typeConstructor, $genericType]] = + new $arrayCls(${assignments.length}) + ..$assignments + + ${c.prefix}.combine($magnoliaObj.caseClass[$typeConstructor, $genericType]( + $className, + false, + $isValueClass, + $paramsVal, + ($fnVal: Param[$typeConstructor, $genericType] => Any) => + new $genericType(..${caseParams.zipWithIndex.map { + case (typeclass, idx) => + q"$fnVal($paramsVal($idx)).asInstanceOf[${typeclass.paramType}]" + }}) + )) + }""" + ) + ) + } else if (isSealedTrait) { + val genericSubtypes = classType.get.knownDirectSubclasses.to[List] + val subtypes = genericSubtypes.map { sub => + val typeArgs = sub.asType.typeSignature.baseType(genericType.typeSymbol).typeArgs + val mapping = typeArgs.zip(genericType.typeArgs).toMap + val newTypeParams = sub.asType.toType.typeArgs.map(mapping(_)) + appliedType(sub.asType.toType.typeConstructor, newTypeParams) + } + + if (subtypes.isEmpty) { + c.info(c.enclosingPosition, + s"magnolia: could not find any direct subtypes of $typeSymbol", + true) + + c.abort(c.enclosingPosition, "") + } + + val subtypesVal: TermName = TermName(c.freshName("subtypes")) + + val typeclasses = subtypes.map { searchType => + recurse(CoproductType(genericType.toString), genericType, assignedName) { + (searchType, typeclassTree(None, searchType, typeConstructor, assignedName)) + }.getOrElse { + c.abort(c.enclosingPosition, s"failed to get implicit for type $searchType") + } + } + + val assignments = typeclasses.zipWithIndex.map { + case ((typ, typeclass), idx) => + q"""$subtypesVal($idx) = $magnoliaObj.subtype[$typeConstructor, $genericType, $typ]( + ${typ.typeSymbol.fullName.toString}, + $typeclass, + (t: $genericType) => t.isInstanceOf[$typ], + (t: $genericType) => t.asInstanceOf[$typ] + )""" + } + + Some { + Typeclass( + genericType, + q"""{ + val $subtypesVal: $arrayCls[_root_.magnolia.Subtype[$typeConstructor, $genericType]] = + new $arrayCls(${assignments.size}) + + ..$assignments + + ${c.prefix}.dispatch(new _root_.magnolia.SealedTrait( + $genericTypeName, + $subtypesVal: $arrayCls[_root_.magnolia.Subtype[$typeConstructor, $genericType]]) + ): $resultType + }""" + ) + } + } else None + + result.map { + case Typeclass(t, r) => + Typeclass(t, q"""{ + def $assignedName: $resultType = $r + $assignedName + }""") + } + } + + val genericType: Type = weakTypeOf[T] + + val currentStack: Stack = + recursionStack.get(c.enclosingPosition).getOrElse(Stack(Map(), List(), List())) + + val directlyReentrant = Some(genericType) == currentStack.frames.headOption.map(_.genericType) + + 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"magnolia: could not derive ${typeConstructor} instance for type " + + s"${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).map(_.tree) + case Some(enclosingRef) => + val methodAsString = enclosingRef.toString + val searchType = appliedType(typeConstructor, genericType) + Some(q"_root_.magnolia.Deferred[$searchType]($methodAsString)") + } + } else directInferImplicit(genericType, typeConstructor).map(_.tree) + + if (currentStack.frames.isEmpty) recursionStack = ListMap() + + val dereferencedResult = result.map { tree => + if (currentStack.frames.isEmpty) c.untypecheck(removeDeferred.transform(tree)) else tree + } + + dereferencedResult.getOrElse { + c.abort(c.enclosingPosition, s"magnolia: could not infer typeclass for type $genericType") + } + } + + /** constructs a new [[Subtype]] instance + * + * This method is intended to be called only from code generated by the Magnolia macro, and + * should not be called directly from users' code. */ + def subtype[Tc[_], T, S <: T](name: String, tc: => Tc[S], isType: T => Boolean, asType: T => S) = + new Subtype[Tc, T] { + type SType = S + def label: String = name + def typeclass: Tc[SType] = tc + def cast: PartialFunction[T, SType] = new PartialFunction[T, S] { + def isDefinedAt(t: T) = isType(t) + def apply(t: T): SType = asType(t) + } + } + + /** constructs a new [[Param]] instance + * + * This method is intended to be called only from code generated by the Magnolia macro, and + * should not be called directly from users' code. */ + def param[Tc[_], T, P](name: String, + typeclassParam: Tc[P], + defaultVal: => Option[P], + deref: T => P) = new Param[Tc, T] { + type PType = P + def label: String = name + def default: Option[PType] = defaultVal + def typeclass: Tc[PType] = typeclassParam + def dereference(t: T): PType = deref(t) + } + + /** constructs a new [[CaseClass]] instance + * + * This method is intended to be called only from code generated by the Magnolia macro, and + * should not be called directly from users' code. */ + def caseClass[Tc[_], T](name: String, + obj: Boolean, + valClass: Boolean, + params: Array[Param[Tc, T]], + constructor: (Param[Tc, T] => Any) => T) = + new CaseClass[Tc, T](name, obj, valClass, params) { + def construct[R](param: Param[Tc, T] => R): T = constructor(param) + } +} + +private[magnolia] case class DirectlyReentrantException() + extends Exception("attempt to recurse directly") + +private[magnolia] object Deferred { def apply[T](method: String): T = ??? } + +private[magnolia] object CompileTimeState { + + sealed class TypePath(path: String) { override def toString = path } + case class CoproductType(typeName: String) extends TypePath(s"coproduct type $typeName") + + case class ProductType(paramName: String, typeName: String) + extends TypePath(s"parameter '$paramName' of product type $typeName") + + case class ChainedImplicit(typeName: String) + extends TypePath(s"chained implicit of type $typeName") + + case class ImplicitNotFound(genericType: String, path: List[TypePath]) + + case class Stack(cache: Map[whitebox.Context#Type, Option[whitebox.Context#Tree]], + frames: List[Frame], + errors: List[ImplicitNotFound]) { + + def lookup(c: whitebox.Context)(t: c.Type)(orElse: => Option[c.Tree]): (Option[c.Tree], Stack) = + if (cache.contains(t)) { + (cache(t).asInstanceOf[Option[c.Tree]], this) + } else { + val value = orElse + (value, copy(cache.updated(t, value))) + } + + def push(path: TypePath, key: whitebox.Context#Type, value: whitebox.Context#TermName): Stack = + Stack(cache, Frame(path, key, value) :: frames, errors) + + def pop(): Stack = Stack(cache, 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] + } + + var recursionStack: ListMap[api.Position, Stack] = ListMap() + var emittedErrors: Set[ImplicitNotFound] = Set() +} diff --git a/core/src/main/scala/interface.scala b/core/src/main/scala/interface.scala deleted file mode 100644 index 54f8ce3..0000000 --- a/core/src/main/scala/interface.scala +++ /dev/null @@ -1,157 +0,0 @@ -package magnolia - -import language.higherKinds - -/** represents a subtype of a sealed trait - * - * @tparam Typeclass type constructor for the typeclass being derived - * @tparam Type generic type of this parameter */ -trait Subtype[Typeclass[_], Type] { - - /** the type of subtype */ - type SType <: Type - - /** the name of the subtype - * - * This is the fully-qualified name of the type of subclass. */ - def label: String - - /** the typeclass instance associated with this subtype - * - * This is the instance of the type `Typeclass[SType]` which will have been discovered by - * implicit search, or derived by Magnolia. */ - def typeclass: Typeclass[SType] - - /** partial function defined the subset of values of `Type` which have the type of this subtype */ - def cast: PartialFunction[Type, SType] -} - -/** represents a parameter of a case class - * - * @tparam Typeclass type constructor for the typeclass being derived - * @tparam Type generic type of this parameter */ -trait Param[Typeclass[_], Type] { - - /** the type of the parameter being represented - * - * For exmaple, for a case class, - *
-    *  case class Person(name: String, age: Int)
-    *  
- * the [[Param]] instance corresponding to the `age` parameter would have a [[PType]] equal to - * the type [[scala.Int]]. However, in practice, this type will never be universally quantified. - */ - type PType - - /** the name of the parameter */ - def label: String - - /** the typeclass instance associated with this parameter - * - * This is the instance of the type `Typeclass[PType]` which will have been discovered by - * implicit search, or derived by Magnolia. - * - * Its type is existentially quantified on this [[Param]] instance, and depending on the - * nature of the particular typeclass, it may either accept or produce types which are also - * existentially quantified on this same [[Param]] instance. */ - def typeclass: Typeclass[PType] - - /** provides the default value for this parameter, as defined in the case class constructor */ - def default: Option[PType] - - /** dereferences a value of the case class type, `Type`, to access the value of the parameter - * being represented - * - * When programming generically, against an unknown case class, with unknown parameter names - * and types, it is not possible to directly access the parameter values without reflection, - * which is undesirable. This method, whose implementation is provided by the Magnolia macro, - * will dereference a case class instance to access the parameter corresponding to this - * [[Param]]. - * - * Whilst the type of the resultant parameter value cannot be universally known at the use, its - * type will be existentially quantified on this [[Param]] instance, and the return type of the - * corresponding `typeclass` method will be existentially quantified on the same value. This is - * sufficient for the compiler to determine that the two values are compatible, and the value may - * be applied to the typeclass (in whatever way that particular typeclass provides). - * - * @param param the instance of the case class to be dereferenced - * @return the parameter value */ - def dereference(param: Type): PType -} - -/** represents a case class or case object and the context required to construct a new typeclass - * instance corresponding to it - * - * Instances of [[CaseClass]] provide access to all of the parameters of the case class, the full - * name of the case class type, and a boolean to determine whether the type is a case class or case - * object. - * - * @param typeName the name of the case class - * @param isObject true only if this represents a case object rather than a case class - * @param parametersArray an array of [[Param]] values for this case class - * @tparam Typeclass type constructor for the typeclass being derived - * @tparam Type generic type of this parameter */ -abstract class CaseClass[Typeclass[_], Type] private[magnolia] ( - val typeName: String, - val isObject: Boolean, - val isValueClass: Boolean, - parametersArray: Array[Param[Typeclass, Type]] -) { - - /** constructs a new instance of the case class type - * - * This method will be implemented by the Magnolia macro to make it possible to construct - * instances of case classes generically in user code, that is, without knowing their type - * concretely. - * - * To construct a new case class instance, the method takes a lambda which defines how each - * parameter in the new case class should be constructed. See the [[Param]] class for more - * information on constructing parameter values from a [[Param]] instance. - * - * @param makeParam lambda for converting a generic [[Param]] into the value to be used for - * this parameter in the construction of a new instance of the case class - * @return a new instance of the case class */ - def construct[Return](makeParam: Param[Typeclass, Type] => Return): Type - - /** a sequence of [[Param]] objects representing all of the parameters in the case class - * - * For efficiency, this sequence is implemented by an `Array`, but upcast to a - * [[scala.collection.Seq]] to hide the mutable collection API. */ - def parameters: Seq[Param[Typeclass, Type]] = parametersArray -} - -/** represents a sealed trait and the context required to construct a new typeclass instance - * corresponding to it - * - * Instances of `SealedTrait` provide access to all of the component subtypes of the sealed trait - * which form a coproduct, and to the fully-qualified name of the sealed trait. - * - * @param typeName the name of the sealed trait - * @param subtypesArray an array of [[Subtype]] instances for each subtype in the sealed trait - * @tparam Typeclass type constructor for the typeclass being derived - * @tparam Type generic type of this parameter */ -final class SealedTrait[Typeclass[_], Type](val typeName: String, - subtypesArray: Array[Subtype[Typeclass, Type]]) { - - /** a sequence of all the subtypes of this sealed trait */ - def subtypes: Seq[Subtype[Typeclass, Type]] = subtypesArray - - /** convenience method for delegating typeclass application to the typeclass corresponding to the - * subtype of the sealed trait which matches the type of the `value` - * - * @tparam Return the return type of the lambda, which should be inferred - * @param value the instance of the generic type whose value should be used to match on a - * particular subtype of the sealed trait - * @param handle lambda for applying the value to the typeclass for the particular subtype which - * matches - * @return the result of applying the `handle` lambda to subtype of the sealed trait which - * matches the parameter `value` */ - def dispatch[Return](value: Type)(handle: Subtype[Typeclass, Type] => Return): Return = - subtypes - .map { sub => - sub.cast.andThen { v => - handle(sub) - } - } - .reduce(_ orElse _)(value) -} diff --git a/core/src/main/scala/magnolia.scala b/core/src/main/scala/magnolia.scala deleted file mode 100644 index 51f594d..0000000 --- a/core/src/main/scala/magnolia.scala +++ /dev/null @@ -1,522 +0,0 @@ -package magnolia - -import scala.reflect._, macros._ -import scala.collection.immutable.ListMap -import language.existentials -import language.higherKinds - -/** the object which defines the Magnolia macro */ -object Magnolia { - import CompileTimeState._ - - /** derives a generic typeclass instance for the type `T` - * - * This is a macro definition method which should be bound to a method defined inside a Magnolia - * generic derivation object, that is, one which defines the methods `combine`, `dispatch` and - * the type constructor, `Typeclass[_]`. This will typically look like, - *
-    *  object Derivation {
-    *    // other definitions
-    *    implicit def gen[T]: Typeclass[T] = Magnolia.gen[T]
-    *  }
-    *  
- * which would support automatic derivation of typeclass instances by calling - * `Derivation.gen[T]` or with `implicitly[Typeclass[T]]`, if the implicit method is imported - * into the current scope. - * - * The definition expects a type constructor called `Typeclass`, taking one *-kinded type - * parameter to be defined on the same object as a means of determining how the typeclass should - * be genericized. While this may be obvious for typeclasses like `Show[T]` which take only a - * single type parameter, Magnolia can also derive typeclass instances for types such as - * `Decoder[Format, Type]` which would typically fix the `Format` parameter while varying the - * `Type` parameter. - * - * While there is no "interface" for a derivation, in the object-oriented sense, the Magnolia - * macro expects to be able to call certain methods on the object within which it is bound to a - * method. - * - * Specifically, for deriving case classes (product types), the macro will attempt to call the - * `combine` method with an instance of [[CaseClass]], like so, - *
-    *    <derivation>.combine(<caseClass>): Typeclass[T]
-    *  
- * That is to say, the macro expects there to exist a method called `combine` on the derivation - * object, which may be called with the code above, and for it to return a type which conforms - * to the type `Typeclass[T]`. The implementation of `combine` will therefore typically look - * like this, - *
-    *    def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = ...
-    *  
- * however, there is the flexibility to provide additional type parameters or additional - * implicit parameters to the definition, provided these do not affect its ability to be invoked - * as described above. - * - * Likewise, for deriving sealed traits (coproduct or sum types), the macro will attempt to call - * the `dispatch` method with an instance of [[SealedTrait]], like so, - *
-    *    <derivation>.dispatch(<sealedTrait>): Typeclass[T]
-    *  
- * so a definition such as, - *
-    *    def dispatch[T](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ...
-    *  
- * will suffice, however the qualifications regarding additional type parameters and implicit - * parameters apply equally to `dispatch` as to `combine`. - * */ - def gen[T: c.WeakTypeTag](c: whitebox.Context): c.Tree = { - import c.universe._ - import scala.util.{Try, Success, Failure} - - val magnoliaPkg = q"_root_.magnolia" - val magnoliaObj = q"$magnoliaPkg.Magnolia" - val arrayCls = tq"_root_.scala.Array" - - val prefixType = c.prefix.tree.tpe - - def companionRef(tpe: Type): Tree = { - val global = c.universe match { case global: scala.tools.nsc.Global => global } - val globalTpe = tpe.asInstanceOf[global.Type] - val companion = globalTpe.typeSymbol.companionSymbol - if (companion != NoSymbol) - global.gen.mkAttributedRef(globalTpe.prefix, companion).asInstanceOf[Tree] - else q"${tpe.typeSymbol.name.toTermName}" - } - - val typeDefs = prefixType.baseClasses.flatMap { cls => - cls.asType.toType.decls.filter(_.isType).find(_.name.toString == "Typeclass").map { tpe => - tpe.asType.toType.asSeenFrom(prefixType, cls) - } - } - - val typeConstructorOpt = - typeDefs.headOption.map(_.typeConstructor) - - val typeConstructor = typeConstructorOpt.getOrElse { - c.abort(c.enclosingPosition, - "magnolia: the derivation object does not define the Typeclass type constructor") - } - - def checkMethod(termName: String, category: String, expected: String) = { - val term = TermName(termName) - val combineClass = c.prefix.tree.tpe.baseClasses - .find { cls => - cls.asType.toType.decl(term) != NoSymbol - } - .getOrElse { - c.abort( - c.enclosingPosition, - s"magnolia: the method `$termName` must be defined on the derivation object to derive typeclasses for $category" - ) - } - val firstParamBlock = combineClass.asType.toType.decl(term).asTerm.asMethod.paramLists.head - if (firstParamBlock.length != 1) - c.abort(c.enclosingPosition, - s"magnolia: the method `combine` should take a single parameter of type $expected") - } - - // FIXME: Only run these methods if they're used, particularly `dispatch` - checkMethod("combine", "case classes", "CaseClass[Typeclass, _]") - checkMethod("dispatch", "sealed traits", "SealedTrait[Typeclass, _]") - - def findType(key: Type): Option[TermName] = - recursionStack(c.enclosingPosition).frames.find(_.genericType == key).map(_.termName(c)) - - case class Typeclass(typ: c.Type, tree: c.Tree) - - def recurse[T](path: TypePath, key: Type, value: TermName)(fn: => T): Option[T] = { - val oldRecursionStack = recursionStack.get(c.enclosingPosition) - recursionStack = recursionStack.updated( - c.enclosingPosition, - oldRecursionStack.map(_.push(path, key, value)).getOrElse { - Stack(Map(), 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()) - } - } - - val removeDeferred: Transformer = new Transformer { - override def transform(tree: Tree): Tree = tree match { - case q"$magnoliaPkg.Deferred.apply[$returnType](${Literal(Constant(method: String))})" => - q"${TermName(method)}" - case _ => - super.transform(tree) - } - } - - def typeclassTree(paramName: Option[String], - genericType: Type, - typeConstructor: Type, - assignedName: TermName): Tree = { - - val searchType = appliedType(typeConstructor, genericType) - - val deferredRef = findType(genericType).map { methodName => - val methodAsString = methodName.decodedName.toString - q"$magnoliaPkg.Deferred.apply[$searchType]($methodAsString)" - } - - val foundImplicit = deferredRef.orElse { - val (inferredImplicit, newStack) = - recursionStack(c.enclosingPosition).lookup(c)(searchType) { - val implicitSearchTry = scala.util.Try { - val genericTypeName: String = - genericType.typeSymbol.name.decodedName.toString.toLowerCase - - val assignedName: TermName = TermName(c.freshName(s"${genericTypeName}Typeclass")) - - recurse(ChainedImplicit(genericType.toString), genericType, assignedName) { - c.inferImplicitValue(searchType, false, false) - }.get - } - - implicitSearchTry.toOption.orElse( - directInferImplicit(genericType, typeConstructor).map(_.tree) - ) - } - recursionStack = recursionStack.updated(c.enclosingPosition, newStack) - inferredImplicit - } - - foundImplicit.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) - - val stackPaths = recursionStack(c.enclosingPosition).frames.map(_.path) - val stack = stackPaths.mkString(" in ", "\n in ", "\n") - - c.abort(c.enclosingPosition, - s"magnolia: could not find typeclass for type $genericType\n$stack") - } - } - - def directInferImplicit(genericType: c.Type, typeConstructor: Type): Option[Typeclass] = { - - val genericTypeName: String = genericType.typeSymbol.name.decodedName.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 isCaseObject = classType.map(_.isModuleClass).getOrElse(false) - val isSealedTrait = classType.map(_.isSealed).getOrElse(false) - - val primitives = Set(typeOf[Double], - typeOf[Float], - typeOf[Short], - typeOf[Byte], - typeOf[Int], - typeOf[Long], - typeOf[Char], - typeOf[Boolean]) - - val isValueClass = genericType <:< typeOf[AnyVal] && !primitives.exists(_ =:= genericType) - - val resultType = appliedType(typeConstructor, genericType) - - val result = if (isCaseObject) { - // FIXME: look for an alternative which isn't deprecated on Scala 2.12+ - val obj = companionRef(genericType) - val className = genericType.typeSymbol.name.decodedName.toString - - val impl = q""" - ${c.prefix}.combine($magnoliaObj.caseClass[$typeConstructor, $genericType]( - $className, true, false, new $arrayCls(0), _ => $obj) - ) - """ - Some(Typeclass(genericType, impl)) - } else if (isCaseClass || isValueClass) { - val caseClassParameters = genericType.decls.collect { - case m: MethodSymbol if m.isCaseAccessor || (isValueClass && m.isParamAccessor) => - m.asMethod - } - val className = genericType.typeSymbol.name.decodedName.toString - - case class CaseParam(sym: c.universe.MethodSymbol, - typeclass: c.Tree, - paramType: c.Type, - ref: c.TermName) - - val caseParamsReversed: List[CaseParam] = caseClassParameters.foldLeft(List[CaseParam]()) { - case (acc, param) => - val paramName = param.name.decodedName.toString - val paramType = param.returnType.substituteTypes(genericType.etaExpand.typeParams, - genericType.typeArgs) - - val predefinedRef = acc.find(_.paramType == paramType) - - val caseParamOpt = predefinedRef.map { backRef => - CaseParam(param, q"()", paramType, backRef.ref) :: acc - } - - caseParamOpt.getOrElse { - val derivedImplicit = - recurse(ProductType(paramName, genericType.toString), genericType, assignedName) { - typeclassTree(Some(paramName), paramType, typeConstructor, assignedName) - }.getOrElse( - c.abort(c.enclosingPosition, s"failed to get implicit for type $genericType") - ) - - val ref = TermName(c.freshName("paramTypeclass")) - val assigned = q"""val $ref = $derivedImplicit""" - CaseParam(param, assigned, paramType, ref) :: acc - } - } - - val caseParams = caseParamsReversed.reverse - - val paramsVal: TermName = TermName(c.freshName("parameters")) - val fnVal: TermName = TermName(c.freshName("fn")) - - val preAssignments = caseParams.map(_.typeclass) - - val defaults = if (!isValueClass) { - val caseClassCompanion = genericType.companion - val constructorMethod = caseClassCompanion.decl(TermName("apply")).asMethod - val indexedConstructorParams = - constructorMethod.paramLists.head.map(_.asTerm).zipWithIndex - - indexedConstructorParams.map { - case (p, idx) => - if (p.isParamWithDefault) { - val method = TermName("apply$default$" + (idx + 1)) - q"_root_.scala.Some(${genericType.typeSymbol.companion.asTerm}.$method)" - } else q"_root_.scala.None" - } - } else List(q"_root_.scala.None") - - val assignments = caseParams.zip(defaults).zipWithIndex.map { - case ((CaseParam(param, typeclass, paramType, ref), defaultVal), idx) => - q"""$paramsVal($idx) = $magnoliaObj.param[$typeConstructor, $genericType, - $paramType]( - ${param.name.decodedName.toString}, $ref, $defaultVal, _.${param.name} - )""" - } - - Some( - Typeclass( - genericType, - q"""{ - ..$preAssignments - val $paramsVal: $arrayCls[Param[$typeConstructor, $genericType]] = - new $arrayCls(${assignments.length}) - ..$assignments - - ${c.prefix}.combine($magnoliaObj.caseClass[$typeConstructor, $genericType]( - $className, - false, - $isValueClass, - $paramsVal, - ($fnVal: Param[$typeConstructor, $genericType] => Any) => - new $genericType(..${caseParams.zipWithIndex.map { - case (typeclass, idx) => - q"$fnVal($paramsVal($idx)).asInstanceOf[${typeclass.paramType}]" - }}) - )) - }""" - ) - ) - } else if (isSealedTrait) { - val genericSubtypes = classType.get.knownDirectSubclasses.to[List] - val subtypes = genericSubtypes.map { sub => - val typeArgs = sub.asType.typeSignature.baseType(genericType.typeSymbol).typeArgs - val mapping = typeArgs.zip(genericType.typeArgs).toMap - val newTypeParams = sub.asType.toType.typeArgs.map(mapping(_)) - appliedType(sub.asType.toType.typeConstructor, newTypeParams) - } - - if (subtypes.isEmpty) { - c.info(c.enclosingPosition, - s"magnolia: could not find any direct subtypes of $typeSymbol", - true) - - c.abort(c.enclosingPosition, "") - } - - val subtypesVal: TermName = TermName(c.freshName("subtypes")) - - val typeclasses = subtypes.map { searchType => - recurse(CoproductType(genericType.toString), genericType, assignedName) { - (searchType, typeclassTree(None, searchType, typeConstructor, assignedName)) - }.getOrElse { - c.abort(c.enclosingPosition, s"failed to get implicit for type $searchType") - } - } - - val assignments = typeclasses.zipWithIndex.map { - case ((typ, typeclass), idx) => - q"""$subtypesVal($idx) = $magnoliaObj.subtype[$typeConstructor, $genericType, $typ]( - ${typ.typeSymbol.fullName.toString}, - $typeclass, - (t: $genericType) => t.isInstanceOf[$typ], - (t: $genericType) => t.asInstanceOf[$typ] - )""" - } - - Some { - Typeclass( - genericType, - q"""{ - val $subtypesVal: $arrayCls[_root_.magnolia.Subtype[$typeConstructor, $genericType]] = - new $arrayCls(${assignments.size}) - - ..$assignments - - ${c.prefix}.dispatch(new _root_.magnolia.SealedTrait( - $genericTypeName, - $subtypesVal: $arrayCls[_root_.magnolia.Subtype[$typeConstructor, $genericType]]) - ): $resultType - }""" - ) - } - } else None - - result.map { - case Typeclass(t, r) => - Typeclass(t, q"""{ - def $assignedName: $resultType = $r - $assignedName - }""") - } - } - - val genericType: Type = weakTypeOf[T] - - val currentStack: Stack = - recursionStack.get(c.enclosingPosition).getOrElse(Stack(Map(), List(), List())) - - val directlyReentrant = Some(genericType) == currentStack.frames.headOption.map(_.genericType) - - 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"magnolia: could not derive ${typeConstructor} instance for type " + - s"${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).map(_.tree) - case Some(enclosingRef) => - val methodAsString = enclosingRef.toString - val searchType = appliedType(typeConstructor, genericType) - Some(q"_root_.magnolia.Deferred[$searchType]($methodAsString)") - } - } else directInferImplicit(genericType, typeConstructor).map(_.tree) - - if (currentStack.frames.isEmpty) recursionStack = ListMap() - - val dereferencedResult = result.map { tree => - if (currentStack.frames.isEmpty) c.untypecheck(removeDeferred.transform(tree)) else tree - } - - dereferencedResult.getOrElse { - c.abort(c.enclosingPosition, s"magnolia: could not infer typeclass for type $genericType") - } - } - - /** constructs a new [[Subtype]] instance - * - * This method is intended to be called only from code generated by the Magnolia macro, and - * should not be called directly from users' code. */ - def subtype[Tc[_], T, S <: T](name: String, tc: => Tc[S], isType: T => Boolean, asType: T => S) = - new Subtype[Tc, T] { - type SType = S - def label: String = name - def typeclass: Tc[SType] = tc - def cast: PartialFunction[T, SType] = new PartialFunction[T, S] { - def isDefinedAt(t: T) = isType(t) - def apply(t: T): SType = asType(t) - } - } - - /** constructs a new [[Param]] instance - * - * This method is intended to be called only from code generated by the Magnolia macro, and - * should not be called directly from users' code. */ - def param[Tc[_], T, P](name: String, - typeclassParam: Tc[P], - defaultVal: => Option[P], - deref: T => P) = new Param[Tc, T] { - type PType = P - def label: String = name - def default: Option[PType] = defaultVal - def typeclass: Tc[PType] = typeclassParam - def dereference(t: T): PType = deref(t) - } - - /** constructs a new [[CaseClass]] instance - * - * This method is intended to be called only from code generated by the Magnolia macro, and - * should not be called directly from users' code. */ - def caseClass[Tc[_], T](name: String, - obj: Boolean, - valClass: Boolean, - params: Array[Param[Tc, T]], - constructor: (Param[Tc, T] => Any) => T) = - new CaseClass[Tc, T](name, obj, valClass, params) { - def construct[R](param: Param[Tc, T] => R): T = constructor(param) - } -} - -private[magnolia] case class DirectlyReentrantException() - extends Exception("attempt to recurse directly") - -private[magnolia] object Deferred { def apply[T](method: String): T = ??? } - -private[magnolia] object CompileTimeState { - - sealed class TypePath(path: String) { override def toString = path } - case class CoproductType(typeName: String) extends TypePath(s"coproduct type $typeName") - - case class ProductType(paramName: String, typeName: String) - extends TypePath(s"parameter '$paramName' of product type $typeName") - - case class ChainedImplicit(typeName: String) - extends TypePath(s"chained implicit of type $typeName") - - case class ImplicitNotFound(genericType: String, path: List[TypePath]) - - case class Stack(cache: Map[whitebox.Context#Type, Option[whitebox.Context#Tree]], - frames: List[Frame], - errors: List[ImplicitNotFound]) { - - def lookup(c: whitebox.Context)(t: c.Type)(orElse: => Option[c.Tree]): (Option[c.Tree], Stack) = - if (cache.contains(t)) { - (cache(t).asInstanceOf[Option[c.Tree]], this) - } else { - val value = orElse - (value, copy(cache.updated(t, value))) - } - - def push(path: TypePath, key: whitebox.Context#Type, value: whitebox.Context#TermName): Stack = - Stack(cache, Frame(path, key, value) :: frames, errors) - - def pop(): Stack = Stack(cache, 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] - } - - var recursionStack: ListMap[api.Position, Stack] = ListMap() - var emittedErrors: Set[ImplicitNotFound] = Set() -} diff --git a/examples/shared/src/main/scala/decode.scala b/examples/shared/src/main/scala/decode.scala new file mode 100644 index 0000000..5b083bd --- /dev/null +++ b/examples/shared/src/main/scala/decode.scala @@ -0,0 +1,79 @@ +package magnolia.examples + +import magnolia._ +import scala.language.experimental.macros + +/** very basic decoder for converting strings to other types */ +trait Decoder[T] { def decode(str: String): T } + +/** derivation object (and companion object) for [[Decoder]] instances */ +object Decoder { + + /** decodes strings */ + implicit val string: Decoder[String] = new Decoder[String] { + def decode(str: String): String = str + } + + /** decodes ints */ + implicit val int: Decoder[Int] = new Decoder[Int] { def decode(str: String): Int = str.toInt } + + /** binds the Magnolia macro to this derivation object */ + implicit def gen[T]: Decoder[T] = macro Magnolia.gen[T] + + /** type constructor for new instances of the typeclass */ + type Typeclass[T] = Decoder[T] + + /** defines how new [[Decoder]]s for case classes should be constructed */ + def combine[T](ctx: CaseClass[Decoder, T]): Decoder[T] = new Decoder[T] { + def decode(value: String) = { + val (name, values) = parse(value) + ctx.construct { param => + param.typeclass.decode(values(param.label)) + } + } + } + + /** defines how to choose which subtype of the sealed trait to use for decoding */ + def dispatch[T](ctx: SealedTrait[Decoder, T]): Decoder[T] = new Decoder[T] { + def decode(param: String) = { + val (name, values) = parse(param) + val subtype = ctx.subtypes.find(_.label == name).get + subtype.typeclass.decode(param) + } + } + + /** very simple extractor for grabbing an entire parameter value, assuming matching parentheses */ + private def parse(value: String): (String, Map[String, String]) = { + val end = value.indexOf('(') + val name = value.substring(0, end) + + def parts(value: String, + idx: Int = 0, + depth: Int = 0, + collected: List[String] = List("")): List[String] = { + def plus(char: Char): List[String] = collected.head + char :: collected.tail + + if (idx == value.length) collected + else + value(idx) match { + case '(' => + parts(value, idx + 1, depth + 1, plus('(')) + case ')' => + if (depth == 1) plus(')') + else parts(value, idx + 1, depth - 1, plus(')')) + case ',' => + if (depth == 0) parts(value, idx + 1, depth, "" :: collected) + else parts(value, idx + 1, depth, plus(',')) + case char => + parts(value, idx + 1, depth, plus(char)) + } + } + + def keyValue(str: String): (String, String) = { + val List(label, value) = str.split("=", 2).to[List] + (label, value) + } + + (name, parts(value.substring(end + 1, value.length - 1)).map(keyValue).toMap) + } +} diff --git a/examples/shared/src/main/scala/default.scala b/examples/shared/src/main/scala/default.scala new file mode 100644 index 0000000..4c1b634 --- /dev/null +++ b/examples/shared/src/main/scala/default.scala @@ -0,0 +1,35 @@ +package magnolia.examples + +import magnolia._ +import scala.language.experimental.macros + +/** typeclass for providing a default value for a particular type */ +trait Default[T] { def default: T } + +/** companion object and derivation object for [[Default]] */ +object Default { + + type Typeclass[T] = Default[T] + + /** constructs a default for each parameter, using the constructor default (if provided), + * otherwise using a typeclass-provided default */ + def combine[T](ctx: CaseClass[Default, T]): Default[T] = new Default[T] { + def default = ctx.construct { param => + param.default.getOrElse(param.typeclass.default) + } + } + + /** chooses which subtype to delegate to */ + def dispatch[T](ctx: SealedTrait[Default, T])(): Default[T] = new Default[T] { + def default: T = ctx.subtypes.head.typeclass.default + } + + /** default value for a string; the empty string */ + implicit val string: Default[String] = new Default[String] { def default = "" } + + /** default value for ints; 0 */ + implicit val int: Default[Int] = new Default[Int] { def default = 0 } + + /** generates default instances of [[Default]] for case classes and sealed traits */ + implicit def gen[T]: Default[T] = macro Magnolia.gen[T] +} diff --git a/examples/shared/src/main/scala/eq.scala b/examples/shared/src/main/scala/eq.scala new file mode 100644 index 0000000..8ee42a4 --- /dev/null +++ b/examples/shared/src/main/scala/eq.scala @@ -0,0 +1,41 @@ +package magnolia.examples + +import magnolia._ +import scala.language.experimental.macros + +/** typeclass for testing the equality of two values of the same type */ +trait Eq[T] { def equal(value: T, value2: T): Boolean } + +/** companion object to [[Eq]] */ +object Eq { + + /** type constructor for the equality typeclass */ + type Typeclass[T] = Eq[T] + + /** defines equality for this case class in terms of equality for all its parameters */ + def combine[T](ctx: CaseClass[Eq, T]): Eq[T] = new Eq[T] { + def equal(value1: T, value2: T) = ctx.parameters.forall { param => + param.typeclass.equal(param.dereference(value1), param.dereference(value2)) + } + } + + /** choose which equality subtype to defer to + * + * Note that in addition to dispatching based on the type of the first parameter to the `equal` + * method, we check that the second parameter is the same type. */ + def dispatch[T](ctx: SealedTrait[Eq, T]): Eq[T] = new Eq[T] { + def equal(value1: T, value2: T): Boolean = ctx.dispatch(value1) { + case sub => + sub.cast.isDefinedAt(value2) && sub.typeclass.equal(sub.cast(value1), sub.cast(value2)) + } + } + + /** equality typeclass instance for strings */ + implicit val string: Eq[String] = new Eq[String] { def equal(v1: String, v2: String) = v1 == v2 } + + /** equality typeclass instance for integers */ + implicit val int: Eq[Int] = new Eq[Int] { def equal(v1: Int, v2: Int) = v1 == v2 } + + /** binds the Magnolia macro to the `gen` method */ + implicit def gen[T]: Eq[T] = macro Magnolia.gen[T] +} diff --git a/examples/shared/src/main/scala/show.scala b/examples/shared/src/main/scala/show.scala new file mode 100644 index 0000000..50b34ee --- /dev/null +++ b/examples/shared/src/main/scala/show.scala @@ -0,0 +1,63 @@ +package magnolia.examples + +import magnolia._ +import scala.language.experimental.macros + +/** shows one type as another, often as a string + * + * Note that this is a more general form of `Show` than is usual, as it permits the return type to + * be something other than a string. */ +trait Show[Out, T] { def show(value: T): Out } + +trait GenericShow[Out] { + + /** the type constructor for new [[Show]] instances + * + * The first parameter is fixed as `String`, and the second parameter varies generically. */ + type Typeclass[T] = Show[Out, T] + + def join(typeName: String, strings: Seq[String]): Out + + /** creates a new [[Show]] instance by labelling and joining (with `mkString`) the result of + * showing each parameter, and prefixing it with the class name */ + def combine[T](ctx: CaseClass[Typeclass, T]): Show[Out, T] = new Show[Out, T] { + def show(value: T) = + if (ctx.isValueClass) { + val param = ctx.parameters.head + param.typeclass.show(param.dereference(value)) + } else { + val paramStrings = ctx.parameters.map { param => + s"${param.label}=${param.typeclass.show(param.dereference(value))}" + } + + join(ctx.typeName.split("\\.").last, paramStrings) + } + } + + /** choose which typeclass to use based on the subtype of the sealed trait */ + def dispatch[T](ctx: SealedTrait[Typeclass, T]): Show[Out, T] = new Show[Out, T] { + def show(value: T): Out = ctx.dispatch(value) { sub => + sub.typeclass.show(sub.cast(value)) + } + } + + /** bind the Magnolia macro to this derivation object */ + implicit def gen[T]: Show[Out, T] = macro Magnolia.gen[T] +} + +/** companion object to [[Show]] */ +object Show extends GenericShow[String] { + + /** show typeclass for strings */ + implicit val string: Show[String, String] = new Show[String, String] { + def show(s: String): String = s + } + + def join(typeName: String, params: Seq[String]): String = + params.mkString(s"$typeName(", ",", ")") + + /** show typeclass for integers */ + implicit val int: Show[String, Int] = new Show[String, Int] { + def show(s: Int): String = s.toString + } +} diff --git a/examples/src/main/scala/decode.scala b/examples/src/main/scala/decode.scala deleted file mode 100644 index 5b083bd..0000000 --- a/examples/src/main/scala/decode.scala +++ /dev/null @@ -1,79 +0,0 @@ -package magnolia.examples - -import magnolia._ -import scala.language.experimental.macros - -/** very basic decoder for converting strings to other types */ -trait Decoder[T] { def decode(str: String): T } - -/** derivation object (and companion object) for [[Decoder]] instances */ -object Decoder { - - /** decodes strings */ - implicit val string: Decoder[String] = new Decoder[String] { - def decode(str: String): String = str - } - - /** decodes ints */ - implicit val int: Decoder[Int] = new Decoder[Int] { def decode(str: String): Int = str.toInt } - - /** binds the Magnolia macro to this derivation object */ - implicit def gen[T]: Decoder[T] = macro Magnolia.gen[T] - - /** type constructor for new instances of the typeclass */ - type Typeclass[T] = Decoder[T] - - /** defines how new [[Decoder]]s for case classes should be constructed */ - def combine[T](ctx: CaseClass[Decoder, T]): Decoder[T] = new Decoder[T] { - def decode(value: String) = { - val (name, values) = parse(value) - ctx.construct { param => - param.typeclass.decode(values(param.label)) - } - } - } - - /** defines how to choose which subtype of the sealed trait to use for decoding */ - def dispatch[T](ctx: SealedTrait[Decoder, T]): Decoder[T] = new Decoder[T] { - def decode(param: String) = { - val (name, values) = parse(param) - val subtype = ctx.subtypes.find(_.label == name).get - subtype.typeclass.decode(param) - } - } - - /** very simple extractor for grabbing an entire parameter value, assuming matching parentheses */ - private def parse(value: String): (String, Map[String, String]) = { - val end = value.indexOf('(') - val name = value.substring(0, end) - - def parts(value: String, - idx: Int = 0, - depth: Int = 0, - collected: List[String] = List("")): List[String] = { - def plus(char: Char): List[String] = collected.head + char :: collected.tail - - if (idx == value.length) collected - else - value(idx) match { - case '(' => - parts(value, idx + 1, depth + 1, plus('(')) - case ')' => - if (depth == 1) plus(')') - else parts(value, idx + 1, depth - 1, plus(')')) - case ',' => - if (depth == 0) parts(value, idx + 1, depth, "" :: collected) - else parts(value, idx + 1, depth, plus(',')) - case char => - parts(value, idx + 1, depth, plus(char)) - } - } - - def keyValue(str: String): (String, String) = { - val List(label, value) = str.split("=", 2).to[List] - (label, value) - } - - (name, parts(value.substring(end + 1, value.length - 1)).map(keyValue).toMap) - } -} diff --git a/examples/src/main/scala/default.scala b/examples/src/main/scala/default.scala deleted file mode 100644 index 4c1b634..0000000 --- a/examples/src/main/scala/default.scala +++ /dev/null @@ -1,35 +0,0 @@ -package magnolia.examples - -import magnolia._ -import scala.language.experimental.macros - -/** typeclass for providing a default value for a particular type */ -trait Default[T] { def default: T } - -/** companion object and derivation object for [[Default]] */ -object Default { - - type Typeclass[T] = Default[T] - - /** constructs a default for each parameter, using the constructor default (if provided), - * otherwise using a typeclass-provided default */ - def combine[T](ctx: CaseClass[Default, T]): Default[T] = new Default[T] { - def default = ctx.construct { param => - param.default.getOrElse(param.typeclass.default) - } - } - - /** chooses which subtype to delegate to */ - def dispatch[T](ctx: SealedTrait[Default, T])(): Default[T] = new Default[T] { - def default: T = ctx.subtypes.head.typeclass.default - } - - /** default value for a string; the empty string */ - implicit val string: Default[String] = new Default[String] { def default = "" } - - /** default value for ints; 0 */ - implicit val int: Default[Int] = new Default[Int] { def default = 0 } - - /** generates default instances of [[Default]] for case classes and sealed traits */ - implicit def gen[T]: Default[T] = macro Magnolia.gen[T] -} diff --git a/examples/src/main/scala/eq.scala b/examples/src/main/scala/eq.scala deleted file mode 100644 index 8ee42a4..0000000 --- a/examples/src/main/scala/eq.scala +++ /dev/null @@ -1,41 +0,0 @@ -package magnolia.examples - -import magnolia._ -import scala.language.experimental.macros - -/** typeclass for testing the equality of two values of the same type */ -trait Eq[T] { def equal(value: T, value2: T): Boolean } - -/** companion object to [[Eq]] */ -object Eq { - - /** type constructor for the equality typeclass */ - type Typeclass[T] = Eq[T] - - /** defines equality for this case class in terms of equality for all its parameters */ - def combine[T](ctx: CaseClass[Eq, T]): Eq[T] = new Eq[T] { - def equal(value1: T, value2: T) = ctx.parameters.forall { param => - param.typeclass.equal(param.dereference(value1), param.dereference(value2)) - } - } - - /** choose which equality subtype to defer to - * - * Note that in addition to dispatching based on the type of the first parameter to the `equal` - * method, we check that the second parameter is the same type. */ - def dispatch[T](ctx: SealedTrait[Eq, T]): Eq[T] = new Eq[T] { - def equal(value1: T, value2: T): Boolean = ctx.dispatch(value1) { - case sub => - sub.cast.isDefinedAt(value2) && sub.typeclass.equal(sub.cast(value1), sub.cast(value2)) - } - } - - /** equality typeclass instance for strings */ - implicit val string: Eq[String] = new Eq[String] { def equal(v1: String, v2: String) = v1 == v2 } - - /** equality typeclass instance for integers */ - implicit val int: Eq[Int] = new Eq[Int] { def equal(v1: Int, v2: Int) = v1 == v2 } - - /** binds the Magnolia macro to the `gen` method */ - implicit def gen[T]: Eq[T] = macro Magnolia.gen[T] -} diff --git a/examples/src/main/scala/show.scala b/examples/src/main/scala/show.scala deleted file mode 100644 index 50b34ee..0000000 --- a/examples/src/main/scala/show.scala +++ /dev/null @@ -1,63 +0,0 @@ -package magnolia.examples - -import magnolia._ -import scala.language.experimental.macros - -/** shows one type as another, often as a string - * - * Note that this is a more general form of `Show` than is usual, as it permits the return type to - * be something other than a string. */ -trait Show[Out, T] { def show(value: T): Out } - -trait GenericShow[Out] { - - /** the type constructor for new [[Show]] instances - * - * The first parameter is fixed as `String`, and the second parameter varies generically. */ - type Typeclass[T] = Show[Out, T] - - def join(typeName: String, strings: Seq[String]): Out - - /** creates a new [[Show]] instance by labelling and joining (with `mkString`) the result of - * showing each parameter, and prefixing it with the class name */ - def combine[T](ctx: CaseClass[Typeclass, T]): Show[Out, T] = new Show[Out, T] { - def show(value: T) = - if (ctx.isValueClass) { - val param = ctx.parameters.head - param.typeclass.show(param.dereference(value)) - } else { - val paramStrings = ctx.parameters.map { param => - s"${param.label}=${param.typeclass.show(param.dereference(value))}" - } - - join(ctx.typeName.split("\\.").last, paramStrings) - } - } - - /** choose which typeclass to use based on the subtype of the sealed trait */ - def dispatch[T](ctx: SealedTrait[Typeclass, T]): Show[Out, T] = new Show[Out, T] { - def show(value: T): Out = ctx.dispatch(value) { sub => - sub.typeclass.show(sub.cast(value)) - } - } - - /** bind the Magnolia macro to this derivation object */ - implicit def gen[T]: Show[Out, T] = macro Magnolia.gen[T] -} - -/** companion object to [[Show]] */ -object Show extends GenericShow[String] { - - /** show typeclass for strings */ - implicit val string: Show[String, String] = new Show[String, String] { - def show(s: String): String = s - } - - def join(typeName: String, params: Seq[String]): String = - params.mkString(s"$typeName(", ",", ")") - - /** show typeclass for integers */ - implicit val int: Show[String, Int] = new Show[String, Int] { - def show(s: Int): String = s.toString - } -} -- cgit v1.2.3