diff options
author | Jon Pretty <jon.pretty@propensive.com> | 2018-01-27 18:00:29 +0000 |
---|---|---|
committer | Jon Pretty <jon.pretty@propensive.com> | 2018-01-27 18:00:29 +0000 |
commit | 097f5aeebdcc350f91e37a05ca36ae9c6f27f04e (patch) | |
tree | ec4dd86f4e74f098baabe593763acb40774f58b5 /core/shared/src | |
parent | 4fe64bd5ba7bdc1ea0e29923b27463c62a3c4052 (diff) | |
download | magnolia-097f5aeebdcc350f91e37a05ca36ae9c6f27f04e.tar.gz magnolia-097f5aeebdcc350f91e37a05ca36ae9c6f27f04e.tar.bz2 magnolia-097f5aeebdcc350f91e37a05ca36ae9c6f27f04e.zip |
Cleaned up
Diffstat (limited to 'core/shared/src')
-rw-r--r-- | core/shared/src/main/scala/globalutil.scala | 62 | ||||
-rw-r--r-- | core/shared/src/main/scala/interface.scala | 204 | ||||
-rw-r--r-- | core/shared/src/main/scala/magnolia.scala | 509 |
3 files changed, 0 insertions, 775 deletions
diff --git a/core/shared/src/main/scala/globalutil.scala b/core/shared/src/main/scala/globalutil.scala deleted file mode 100644 index 5c11f79..0000000 --- a/core/shared/src/main/scala/globalutil.scala +++ /dev/null @@ -1,62 +0,0 @@ -package magnolia - -import scala.reflect.macros.{runtime, whitebox} -import scala.tools.nsc.Global - -/** Workarounds that needs to use `nsc.Global`. */ -private[magnolia] object GlobalUtil { - - // From Shapeless: https://github.com/milessabin/shapeless/blob/master/core/src/main/scala/shapeless/generic.scala#L698 - // Cut-n-pasted (with most original comments) and slightly adapted from - // https://github.com/scalamacros/paradise/blob/c14c634923313dd03f4f483be3d7782a9b56de0e/plugin/src/main/scala/org/scalamacros/paradise/typechecker/Namers.scala#L568-L613 - def patchedCompanionRef(c: whitebox.Context)(tpe: c.Type): c.Tree = { - // see https://github.com/scalamacros/paradise/issues/7 - // also see https://github.com/scalamacros/paradise/issues/64 - - val global = c.universe.asInstanceOf[Global] - val typer = c.asInstanceOf[runtime.Context].callsiteTyper.asInstanceOf[global.analyzer.Typer] - val ctx = typer.context - val globalType = tpe.asInstanceOf[global.Type] - val original = globalType.typeSymbol - val owner = original.owner - val companion = original.companion.orElse { - import global.{abort => aabort, _} - implicit class PatchedContext(ctx: global.analyzer.Context) { - trait PatchedLookupResult { def suchThat(criterion: Symbol => Boolean): Symbol } - def patchedLookup(name: Name, expectedOwner: Symbol) = new PatchedLookupResult { - override def suchThat(criterion: Symbol => Boolean): Symbol = { - var res: Symbol = NoSymbol - var ctx = PatchedContext.this.ctx - while (res == NoSymbol && ctx.outer != ctx) { - // NOTE: original implementation says `val s = ctx.scope lookup name` - // but we can't use it, because Scope.lookup returns wrong results when the lookup is ambiguous - // and that triggers https://github.com/scalamacros/paradise/issues/64 - val s = { - val lookupResult = ctx.scope.lookupAll(name).filter(criterion).toList - lookupResult match { - case Nil => NoSymbol - case List(unique) => unique - case _ => - aabort( - s"unexpected multiple results for a companion symbol lookup for $original#{$original.id}" - ) - } - } - if (s != NoSymbol && s.owner == expectedOwner) - res = s - else - ctx = ctx.outer - } - res - } - } - } - - ctx.patchedLookup(original.name.companionName, owner) suchThat { sym => - (original.isTerm || sym.hasModuleFlag) && (sym isCoDefinedWith original) - } - } - - global.gen.mkAttributedRef(globalType.prefix, companion).asInstanceOf[c.Tree] - } -} diff --git a/core/shared/src/main/scala/interface.scala b/core/shared/src/main/scala/interface.scala deleted file mode 100644 index 846eee9..0000000 --- a/core/shared/src/main/scala/interface.scala +++ /dev/null @@ -1,204 +0,0 @@ -package magnolia - -import language.higherKinds -import scala.annotation.tailrec - -/** 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 [[TypeName]] of the subtype - * - * This is the full name information for the type of subclass. */ - def typeName: TypeName - - /** 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 example, for a case class, - * <pre> - * case class Person(name: String, age: Int) - * </pre> - * 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 - - /** flag indicating a repeated (aka. vararg) parameter - * - * For example, for a case class, - * <pre> - * case class Account(id: String, emails: String*) - * </pre> - * the [[Param]] instance corresponding to the `emails` parameter would be `repeated` and have a - * [[PType]] equal to the type `Seq[String]`. Note that only the last parameter of a case class - * can be repeated. */ - def repeated: Boolean - - /** 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: TypeName, - 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 */ - final def construct[Return](makeParam: Param[Typeclass, Type] => Return): Type = - rawConstruct(parameters map makeParam) - - /** constructs a new instance of the case class type - * - * Like [[construct]] this method is implemented by Magnolia and let's you construct case class - * instances generically in user code, without knowing their type concretely. - * - * `rawConstruct`, however, is more low-level in that it expects you to provide a [[Seq]] - * containing all the field values for the case class type, in order and with the correct types. - * - * @param fieldValues contains the field values for the case class instance to be constructed, - * in order and with the correct types. - * @return a new instance of the case class - * @throws IllegalArgumentException if the size of `paramValues` differs from the size of [[parameters]] */ - def rawConstruct(fieldValues: Seq[Any]): 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. */ - final 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: TypeName, - 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 = { - @tailrec def rec(ix: Int): Return = - if (ix < subtypesArray.length) { - val sub = subtypesArray(ix) - if (sub.cast.isDefinedAt(value)) handle(sub) else rec(ix + 1) - } else - throw new IllegalArgumentException( - s"The given value `$value` is not a sub type of `$typeName`" - ) - rec(0) - } -} - -/** - * Provides the different parts of a type's class name. - */ -final case class TypeName(owner: String, short: String) { - def full: String = s"$owner.$short" -} - -/** - * This annotation can be attached to the implicit `gen` method of a type class companion, - * which is implemented by the `Magnolia.gen` macro. - * It causes magnolia to dump the macro-generated code to the console during compilation. - * - * @param typeNamePart If non-empty restricts the output generation to types - * whose full name contains the given [[String]] - */ -final class debug(typeNamePart: String = "") extends scala.annotation.StaticAnnotation diff --git a/core/shared/src/main/scala/magnolia.scala b/core/shared/src/main/scala/magnolia.scala deleted file mode 100644 index 5318aa2..0000000 --- a/core/shared/src/main/scala/magnolia.scala +++ /dev/null @@ -1,509 +0,0 @@ -package magnolia - -import scala.collection.mutable -import scala.language.existentials -import scala.language.higherKinds -import scala.reflect.macros._ - -/** 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, - * <pre> - * object Derivation { - * // other definitions - * implicit def gen[T]: Typeclass[T] = Magnolia.gen[T] - * } - * </pre> - * 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, - * <pre> - * <derivation>.combine(<caseClass>): Typeclass[T] - * </pre> - * 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, - * <pre> - * def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = ... - * </pre> - * 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, - * <pre> - * <derivation>.dispatch(<sealedTrait>): Typeclass[T] - * </pre> - * so a definition such as, - * <pre> - * def dispatch[T](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ... - * </pre> - * 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 = Stack.withContext(c) { stack => - import c.universe._ - import internal._ - - val debug = c.macroApplication.symbol.annotations - .find(_.tree.tpe <:< typeOf[debug]) - .flatMap(_.tree.children.tail.collectFirst { case Literal(Constant(s: String)) => s }) - - val magnoliaPkg = c.mirror.staticPackage("magnolia") - val scalaPkg = c.mirror.staticPackage("scala") - - val repeatedParamClass = definitions.RepeatedParamClass - val scalaSeqType = typeOf[Seq[_]].typeConstructor - - val prefixType = c.prefix.tree.tpe - val prefixObject = prefixType.typeSymbol - val prefixName = prefixObject.name.decodedName - - 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 typeConstructor = typeDefs.headOption.fold { - c.abort( - c.enclosingPosition, - s"magnolia: the derivation $prefixObject does not define the Typeclass type constructor" - ) - }(_.typeConstructor) - - def checkMethod(termName: String, category: String, expected: String): Unit = { - 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 $prefixObject to derive typeclasses for $category" - ) - } - val firstParamBlock = combineClass.asType.toType.decl(term).asTerm.asMethod.paramLists.head - if (firstParamBlock.lengthCompare(1) != 0) - 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, _]") - - val removeDeferred = new Transformer { - override def transform(tree: Tree) = tree match { - case q"$magnolia.Deferred.apply[$_](${Literal(Constant(method: String))})" - if magnolia.symbol == magnoliaPkg => - q"${TermName(method)}" - case _ => - super.transform(tree) - } - } - - def typeclassTree(genericType: Type, typeConstructor: Type): Tree = { - val searchType = appliedType(typeConstructor, genericType) - val deferredRef = for (methodName <- stack find searchType) yield { - val methodAsString = methodName.decodedName.toString - q"$magnoliaPkg.Deferred.apply[$searchType]($methodAsString)" - } - - deferredRef.getOrElse { - val path = ChainedImplicit(s"$prefixName.Typeclass", genericType.toString) - val frame = stack.Frame(path, searchType, termNames.EMPTY) - stack.recurse(frame, searchType) { - Option(c.inferImplicitValue(searchType)) - .filterNot(_.isEmpty) - .orElse(directInferImplicit(genericType, typeConstructor)) - .getOrElse { - val missingType = stack.top.fold(searchType)(_.searchType.asInstanceOf[Type]) - val typeClassName = s"${missingType.typeSymbol.name.decodedName}.Typeclass" - val genericType = missingType.typeArgs.head - val trace = stack.trace.mkString(" in ", "\n in ", "\n") - c.abort(c.enclosingPosition, - s"magnolia: could not find $typeClassName for type $genericType\n$trace") - } - } - } - } - - def directInferImplicit(genericType: Type, typeConstructor: Type): Option[Tree] = { - val genericTypeName = genericType.typeSymbol.name.decodedName.toString.toLowerCase - val assignedName = TermName(c.freshName(s"${genericTypeName}Typeclass")) - val typeSymbol = genericType.typeSymbol - val classType = if (typeSymbol.isClass) Some(typeSymbol.asClass) else None - val isCaseClass = classType.exists(_.isCaseClass) - val isCaseObject = classType.exists(_.isModuleClass) - val isSealedTrait = classType.exists(_.isSealed) - - val primitives = Set(typeOf[Double], - typeOf[Float], - typeOf[Short], - typeOf[Byte], - typeOf[Int], - typeOf[Long], - typeOf[Char], - typeOf[Boolean], - typeOf[Unit]) - - val isValueClass = genericType <:< typeOf[AnyVal] && !primitives.exists(_ =:= genericType) - - val resultType = appliedType(typeConstructor, genericType) - - val typeName = TermName(c.freshName("typeName")) - val typeNameDef = { - val ts = genericType.typeSymbol - q"val $typeName = $magnoliaPkg.TypeName(${ts.owner.fullName}, ${ts.name.decodedName.toString})" - } - - val result = if (isCaseObject) { - val impl = q""" - $typeNameDef - ${c.prefix}.combine($magnoliaPkg.Magnolia.caseClass[$typeConstructor, $genericType]( - $typeName, true, false, new $scalaPkg.Array(0), _ => ${genericType.typeSymbol.asClass.module}) - ) - """ - Some(impl) - } else if (isCaseClass || isValueClass) { - val caseClassParameters = genericType.decls.collect { - case m: MethodSymbol if m.isCaseAccessor || (isValueClass && m.isParamAccessor) => - m.asMethod - } - - case class CaseParam(sym: MethodSymbol, - repeated: Boolean, - typeclass: Tree, - paramType: Type, - ref: TermName) - - val caseParamsReversed = caseClassParameters.foldLeft[List[CaseParam]](Nil) { - (acc, param) => - val paramName = param.name.decodedName.toString - val paramTypeSubstituted = param.typeSignatureIn(genericType).resultType - - val (repeated, paramType) = paramTypeSubstituted match { - case TypeRef(_, `repeatedParamClass`, typeArgs) => - true -> appliedType(scalaSeqType, typeArgs) - case tpe => - false -> tpe - } - - acc - .find(_.paramType =:= paramType) - .fold { - val path = ProductType(paramName, genericType.toString) - val frame = stack.Frame(path, resultType, assignedName) - val derivedImplicit = - stack.recurse(frame, appliedType(typeConstructor, paramType)) { - typeclassTree(paramType, typeConstructor) - } - - val ref = TermName(c.freshName("paramTypeclass")) - val assigned = q"""lazy val $ref = $derivedImplicit""" - CaseParam(param, repeated, assigned, paramType, ref) :: acc - } { backRef => - CaseParam(param, repeated, q"()", paramType, backRef.ref) :: acc - } - } - - val caseParams = caseParamsReversed.reverse - - val paramsVal: TermName = TermName(c.freshName("parameters")) - val fieldValues: TermName = TermName(c.freshName("fieldValues")) - - val preAssignments = caseParams.map(_.typeclass) - - val defaults = if (!isValueClass) { - val companionRef = GlobalUtil.patchedCompanionRef(c)(genericType.dealias) - val companionSym = companionRef.symbol.asModule.info - - // If a companion object is defined with alternative apply methods - // it is needed get all the alternatives - val constructorMethods = - companionSym.decl(TermName("apply")).alternatives.map(_.asMethod) - - // The last apply method in the alternatives is the one that belongs - // to the case class, not the user defined companion object - val indexedConstructorParams = - constructorMethods.last.paramLists.head.map(_.asTerm).zipWithIndex - - indexedConstructorParams.map { - case (p, idx) => - if (p.isParamWithDefault) { - val method = TermName("apply$default$" + (idx + 1)) - q"$scalaPkg.Some($companionRef.$method)" - } else q"$scalaPkg.None" - } - } else List(q"$scalaPkg.None") - - val assignments = caseParams.zip(defaults).zipWithIndex.map { - case ((CaseParam(param, repeated, typeclass, paramType, ref), defaultVal), idx) => - q"""$paramsVal($idx) = $magnoliaPkg.Magnolia.param[$typeConstructor, $genericType, - $paramType]( - ${param.name.decodedName.toString}, $repeated, $ref, $defaultVal, _.${param.name} - )""" - } - - Some(q"""{ - ..$preAssignments - val $paramsVal: $scalaPkg.Array[$magnoliaPkg.Param[$typeConstructor, $genericType]] = - new $scalaPkg.Array(${assignments.length}) - ..$assignments - - $typeNameDef - - ${c.prefix}.combine($magnoliaPkg.Magnolia.caseClass[$typeConstructor, $genericType]( - $typeName, - false, - $isValueClass, - $paramsVal, - ($fieldValues: $scalaPkg.Seq[Any]) => { - if ($fieldValues.lengthCompare($paramsVal.length) != 0) { - val msg = "`" + $typeName.full + "` has " + $paramsVal.length + " fields, not " + $fieldValues.size - throw new java.lang.IllegalArgumentException(msg) - } - new $genericType(..${caseParams.zipWithIndex.map { - case (typeclass, idx) => - val arg = q"$fieldValues($idx).asInstanceOf[${typeclass.paramType}]" - if (typeclass.repeated) q"$arg: _*" else arg - }})})) - }""") - } else if (isSealedTrait) { - val genericSubtypes = classType.get.knownDirectSubclasses.to[List] - val subtypes = genericSubtypes.map { sub => - val subType = sub.asType.toType // FIXME: Broken for path dependent types - val typeParams = sub.asType.typeParams - val typeArgs = thisType(sub).baseType(genericType.typeSymbol).typeArgs - val mapping = (typeArgs.map(_.typeSymbol), genericType.typeArgs).zipped.toMap - val newTypeArgs = typeParams.map(mapping.withDefault(_.asType.toType)) - val applied = appliedType(subType.typeConstructor, newTypeArgs) - existentialAbstraction(typeParams, applied) - } - - if (subtypes.isEmpty) { - c.info(c.enclosingPosition, - s"magnolia: could not find any direct subtypes of $typeSymbol", - force = true) - - c.abort(c.enclosingPosition, "") - } - - val subtypesVal: TermName = TermName(c.freshName("subtypes")) - - val typeclasses = for (subType <- subtypes) yield { - val path = CoproductType(genericType.toString) - val frame = stack.Frame(path, resultType, assignedName) - subType -> stack.recurse(frame, appliedType(typeConstructor, subType)) { - typeclassTree(subType, typeConstructor) - } - } - - val assignments = typeclasses.zipWithIndex.map { - case ((typ, typeclass), idx) => - q"""$subtypesVal($idx) = $magnoliaPkg.Magnolia.subtype[$typeConstructor, $genericType, $typ]( - $magnoliaPkg.TypeName(${typ.typeSymbol.owner.fullName}, ${typ.typeSymbol.name.decodedName.toString}), - $typeclass, - (t: $genericType) => t.isInstanceOf[$typ], - (t: $genericType) => t.asInstanceOf[$typ] - )""" - } - - Some(q"""{ - val $subtypesVal: $scalaPkg.Array[$magnoliaPkg.Subtype[$typeConstructor, $genericType]] = - new $scalaPkg.Array(${assignments.size}) - - ..$assignments - - $typeNameDef - - ${c.prefix}.dispatch(new $magnoliaPkg.SealedTrait( - $typeName, - $subtypesVal: $scalaPkg.Array[$magnoliaPkg.Subtype[$typeConstructor, $genericType]]) - ): $resultType - }""") - } else None - - for (term <- result) yield q"""{ - lazy val $assignedName: $resultType = $term - $assignedName - }""" - } - - val genericType: Type = weakTypeOf[T] - val searchType = appliedType(typeConstructor, genericType) - val directlyReentrant = stack.top.exists(_.searchType =:= searchType) - if (directlyReentrant) throw DirectlyReentrantException() - - val result = stack - .find(searchType) - .map { enclosingRef => - q"$magnoliaPkg.Deferred[$searchType](${enclosingRef.toString})" - } - .orElse { - directInferImplicit(genericType, typeConstructor) - } - - for (tree <- result) if (debug.isDefined && genericType.toString.contains(debug.get)) { - c.echo(c.enclosingPosition, s"Magnolia macro expansion for $genericType") - c.echo(NoPosition, s"... = ${showCode(tree)}\n\n") - } - - val dereferencedResult = - if (stack.nonEmpty) result - else for (tree <- result) yield c.untypecheck(removeDeferred.transform(tree)) - - dereferencedResult.getOrElse { - c.abort(c.enclosingPosition, - s"magnolia: could not infer $prefixName.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: TypeName, - tc: => Tc[S], - isType: T => Boolean, - asType: T => S): Subtype[Tc, T] = - new Subtype[Tc, T] with PartialFunction[T, S] { - type SType = S - def typeName: TypeName = name - def typeclass: Tc[SType] = tc - def cast: PartialFunction[T, SType] = this - 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, - isRepeated: Boolean, - typeclassParam: => Tc[P], - defaultVal: => Option[P], - deref: T => P): Param[Tc, T] = new Param[Tc, T] { - type PType = P - def label: String = name - def repeated: Boolean = isRepeated - 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: TypeName, - obj: Boolean, - valClass: Boolean, - params: Array[Param[Tc, T]], - constructor: Seq[Any] => T): CaseClass[Tc, T] = - new CaseClass[Tc, T](name, obj, valClass, params) { - def rawConstruct(fieldValues: Seq[Any]): T = constructor(fieldValues) - } -} - -private[magnolia] final case class DirectlyReentrantException() - extends Exception("attempt to recurse directly") - -private[magnolia] object Deferred { def apply[T](method: String): T = ??? } - -private[magnolia] object CompileTimeState { - - sealed abstract class TypePath(path: String) { override def toString = path } - final case class CoproductType(typeName: String) extends TypePath(s"coproduct type $typeName") - - final case class ProductType(paramName: String, typeName: String) - extends TypePath(s"parameter '$paramName' of product type $typeName") - - final case class ChainedImplicit(typeClassName: String, typeName: String) - extends TypePath(s"chained implicit $typeClassName for type $typeName") - - final class Stack[C <: whitebox.Context] { - private var frames = List.empty[Frame] - private val cache = mutable.Map.empty[C#Type, C#Tree] - - def isEmpty: Boolean = frames.isEmpty - def nonEmpty: Boolean = frames.nonEmpty - def top: Option[Frame] = frames.headOption - def pop(): Unit = frames = frames drop 1 - def push(frame: Frame): Unit = frames ::= frame - - def clear(): Unit = { - frames = Nil - cache.clear() - } - - def find(searchType: C#Type): Option[C#TermName] = frames.collectFirst { - case Frame(_, tpe, term) if tpe =:= searchType => term - } - - def recurse[T <: C#Tree](frame: Frame, searchType: C#Type)(fn: => T): T = { - push(frame) - val result = cache.getOrElseUpdate(searchType, fn) - pop() - result.asInstanceOf[T] - } - - def trace: List[TypePath] = - frames - .drop(1) - .foldLeft[(C#Type, List[TypePath])]((null, Nil)) { - case ((_, Nil), frame) => - (frame.searchType, frame.path :: Nil) - case (continue @ (tpe, acc), frame) => - if (tpe =:= frame.searchType) continue - else (frame.searchType, frame.path :: acc) - } - ._2 - .reverse - - override def toString: String = - frames.mkString("magnolia stack:\n", "\n", "\n") - - final case class Frame(path: TypePath, searchType: C#Type, term: C#TermName) - } - - object Stack { - private val global = new Stack[whitebox.Context] - private val workSet = mutable.Set.empty[whitebox.Context#Symbol] - - def withContext(c: whitebox.Context)(fn: Stack[c.type] => c.Tree): c.Tree = { - workSet += c.macroApplication.symbol - val depth = c.enclosingMacros.count(m => workSet(m.macroApplication.symbol)) - try fn(global.asInstanceOf[Stack[c.type]]) - finally if (depth <= 1) { - global.clear() - workSet.clear() - } - } - } -} |