-
-
Notifications
You must be signed in to change notification settings - Fork 134
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Reimplement Macros with Scala 3 metaprogramming #689
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
8c661e4
Update Macro facade
cchantep 0c34c45
Value class macros
cchantep 5e61ce4
Singleton reads macro
cchantep 7c3de57
WIP
cchantep b2c8b56
productReads
cchantep 59e9f60
productWrites
cchantep 8b45dc1
Revert scalafmt changes
cchantep 7700028
Add unit test about quotes utilities
cchantep 8abe480
Add specs for simple/non-case class support by macros
cchantep 3a7ff17
Add specs for objects support in macros
cchantep 63909d5
Update tests for non-case class macro support
cchantep 001b00c
Update documentation & add Scala 3 specific tests for custom class
cchantep bd7cec4
Revert
cchantep 61a100e
Review
cchantep File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
263 changes: 263 additions & 0 deletions
263
play-json/shared/src/main/scala-3/play/api/libs/json/ImplicitResolver.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,263 @@ | ||
/* | ||
* Copyright (C) 2009-2021 Lightbend Inc. <https://www.lightbend.com> | ||
cchantep marked this conversation as resolved.
Show resolved
Hide resolved
|
||
*/ | ||
|
||
package play.api.libs.json | ||
|
||
import scala.quoted.{ Expr, Quotes, Type } | ||
|
||
private[json] trait ImplicitResolver[A] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
type Q <: Quotes | ||
|
||
protected implicit val quotes: Q | ||
|
||
import quotes.reflect.* | ||
|
||
protected implicit val aTpe: Type[A] | ||
|
||
protected final lazy val aTpeRepr: TypeRepr = TypeRepr.of(using aTpe) | ||
|
||
import Json.Placeholder | ||
|
||
// The placeholder type | ||
protected final lazy val PlaceholderType: TypeRepr = | ||
TypeRepr.of[Placeholder] | ||
|
||
/** | ||
* Refactor the input types, by replacing any type matching the `filter`, | ||
* by the given `replacement`. | ||
*/ | ||
@annotation.tailrec | ||
private def refactor( | ||
in: List[TypeRepr], | ||
base: (TypeRepr, /*Type*/ Symbol), | ||
out: List[TypeRepr], | ||
tail: List[ | ||
(List[TypeRepr], (TypeRepr, /*Type*/ Symbol), List[TypeRepr]) | ||
], | ||
filter: TypeRepr => Boolean, | ||
replacement: TypeRepr, | ||
altered: Boolean | ||
): (TypeRepr, Boolean) = in match { | ||
case tpe :: ts => | ||
tpe match { | ||
case t if filter(t) => | ||
refactor( | ||
ts, | ||
base, | ||
(replacement :: out), | ||
tail, | ||
filter, | ||
replacement, | ||
true | ||
) | ||
|
||
case AppliedType(t, as) if as.nonEmpty => | ||
refactor( | ||
as, | ||
t -> t.typeSymbol, | ||
List.empty, | ||
(ts, base, out) :: tail, | ||
filter, | ||
replacement, | ||
altered | ||
) | ||
|
||
case t => | ||
refactor( | ||
ts, | ||
base, | ||
(t :: out), | ||
tail, | ||
filter, | ||
replacement, | ||
altered | ||
) | ||
} | ||
|
||
case _ => { | ||
val tpe = base._1.appliedTo(out.reverse) | ||
|
||
tail match { | ||
case (x, y, more) :: ts => | ||
refactor( | ||
x, | ||
y, | ||
(tpe :: more), | ||
ts, | ||
filter, | ||
replacement, | ||
altered | ||
) | ||
|
||
case _ => tpe -> altered | ||
} | ||
} | ||
} | ||
|
||
/** | ||
* Replaces any reference to the type itself by the Placeholder type. | ||
* @return the normalized type + whether any self reference has been found | ||
*/ | ||
private def normalized(tpe: TypeRepr): (TypeRepr, Boolean) = | ||
tpe match { | ||
case t if t =:= aTpeRepr => PlaceholderType -> true | ||
|
||
case AppliedType(t, args) if args.nonEmpty => | ||
refactor( | ||
args, | ||
t -> t.typeSymbol, | ||
List.empty, | ||
List.empty, | ||
_ =:= aTpeRepr, | ||
PlaceholderType, | ||
false | ||
) | ||
|
||
case t => t -> false | ||
} | ||
|
||
/* Restores reference to the type itself when Placeholder is found. */ | ||
private def denormalized(ptype: TypeRepr): TypeRepr = ptype match { | ||
case t if t =:= PlaceholderType => | ||
aTpeRepr | ||
|
||
case AppliedType(base, args) if args.nonEmpty => | ||
refactor( | ||
args, | ||
base -> base.typeSymbol, | ||
List.empty, | ||
List.empty, | ||
_ == PlaceholderType, | ||
aTpeRepr, | ||
false | ||
)._1 | ||
|
||
case _ => | ||
ptype | ||
} | ||
|
||
private val PlaceholderHandlerName = | ||
"play.api.libs.json.Json.Placeholder.Format" | ||
|
||
/** | ||
* @param tc the type representation of the typeclass | ||
* @param forwardExpr the `Expr` that forward to the materialized instance itself | ||
*/ | ||
private class ImplicitTransformer[T](forwardExpr: Expr[T]) extends TreeMap { | ||
private val denorm = denormalized _ | ||
|
||
@SuppressWarnings(Array("AsInstanceOf")) | ||
override def transformTree(tree: Tree)(owner: Symbol): Tree = tree match { | ||
case TypeApply(tpt, args) => | ||
TypeApply( | ||
transformTree(tpt)(owner).asInstanceOf[Term], | ||
args.map(transformTree(_)(owner).asInstanceOf[TypeTree]) | ||
) | ||
|
||
case t @ (Select(_, _) | Ident(_)) if t.show == PlaceholderHandlerName => | ||
forwardExpr.asTerm | ||
|
||
case tt: TypeTree => | ||
super.transformTree( | ||
TypeTree.of(using denorm(tt.tpe).asType) | ||
)(owner) | ||
|
||
case Apply(fun, args) => | ||
Apply(transformTree(fun)(owner).asInstanceOf[Term], args.map(transformTree(_)(owner).asInstanceOf[Term])) | ||
|
||
case _ => | ||
super.transformTree(tree)(owner) | ||
} | ||
} | ||
|
||
private def createImplicit[M[_]]( | ||
debug: String => Unit | ||
)(tc: Type[M], ptype: TypeRepr, tx: TreeMap): Option[Implicit] = { | ||
val pt = ptype.asType | ||
val (ntpe, selfRef) = normalized(ptype) | ||
val ptpe = ntpe | ||
|
||
// infers given | ||
val neededGivenType = TypeRepr | ||
.of[M](using tc) | ||
.appliedTo(ptpe) | ||
|
||
val neededGiven: Option[Term] = Implicits.search(neededGivenType) match { | ||
case suc: ImplicitSearchSuccess => { | ||
if (!selfRef) { | ||
Some(suc.tree) | ||
} else { | ||
tx.transformTree(suc.tree)(suc.tree.symbol) match { | ||
case t: Term => Some(t) | ||
case _ => Option.empty[Term] | ||
} | ||
} | ||
} | ||
|
||
case _ => | ||
Option.empty[Term] | ||
} | ||
|
||
debug { | ||
val show: Option[String] = | ||
try { | ||
neededGiven.map(_.show) | ||
} catch { | ||
case e: MatchError /* Dotty bug */ => | ||
neededGiven.map(_.symbol.fullName) | ||
} | ||
|
||
s"// Resolve given ${prettyType( | ||
TypeRepr.of(using tc) | ||
)} for ${prettyType(ntpe)} as ${prettyType( | ||
neededGivenType | ||
)} (self? ${selfRef}) = ${show.mkString}" | ||
} | ||
|
||
neededGiven.map(_ -> selfRef) | ||
} | ||
|
||
protected def resolver[M[_], T]( | ||
forwardExpr: Expr[M[T]], | ||
debug: String => Unit | ||
)(tc: Type[M]): TypeRepr => Option[Implicit] = { | ||
val tx = | ||
new ImplicitTransformer[M[T]](forwardExpr) | ||
|
||
createImplicit(debug)(tc, _: TypeRepr, tx) | ||
} | ||
|
||
/** | ||
* @param sym a type symbol | ||
*/ | ||
protected def typeName(sym: Symbol): String = | ||
sym.fullName.replaceAll("(\\.package\\$|\\$|java\\.lang\\.|scala\\.Predef\\$\\.)", "") | ||
|
||
// To print the implicit types in the compiler messages | ||
private[json] final def prettyType(t: TypeRepr): String = t match { | ||
case _ if t <:< TypeRepr.of[EmptyTuple] => | ||
"EmptyTuple" | ||
|
||
case AppliedType(ty, a :: b :: Nil) if ty <:< TypeRepr.of[*:] => | ||
s"${prettyType(a)} *: ${prettyType(b)}" | ||
|
||
case AppliedType(_, args) => | ||
typeName(t.typeSymbol) + args.map(prettyType).mkString("[", ", ", "]") | ||
|
||
case OrType(a, b) => | ||
s"${prettyType(a)} | ${prettyType(b)}" | ||
|
||
case _ => { | ||
val sym = t.typeSymbol | ||
|
||
if (sym.isTypeParam) { | ||
sym.name | ||
} else { | ||
typeName(sym) | ||
} | ||
} | ||
} | ||
|
||
type Implicit = (Term, Boolean) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Required for the Scala3 equivalent, not a compatibility issue for me, as compile-time