Skip to content
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

WIP: add FieldTypeResolver and tests #1244

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ lazy val `jsoniter-scala-benchmark` = crossProject(JVMPlatform, JSPlatform)
"com.disneystreaming.smithy4s" %%% "smithy4s-json" % "0.18.29",
"com.evolutiongaming" %%% "play-json-jsoniter" % "0.10.3" intransitive(),
"org.playframework" %%% "play-json" % "3.0.4",
"dev.zio" %%% "zio-json" % "0.7.9",
"dev.zio" %%% "zio-json" % "0.7.10",
"dev.zio" %%% "zio-schema-json" % "1.6.1",
"io.circe" %%% "circe-generic" % "0.14.10",
"io.circe" %%% "circe-jawn" % "0.14.10",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,82 +586,98 @@ object JsonCodecMaker {
*/
inline def make[A](inline config: CodecMakerConfig): JsonValueCodec[A] = ${Impl.makeWithSpecifiedConfig('config)}

private[macros] object Impl {
def makeWithDefaultConfig[A: Type](using Quotes): Expr[JsonValueCodec[A]] = make(CodecMakerConfig)

def makeWithoutDiscriminator[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withDiscriminatorFieldName(None))

def makeWithRequiredCollectionFields[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withRequireCollectionFields(true))

def makeWithRequiredDefaultFields[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientDefault(false).withRequireDefaultFields(true))

def makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withRequireCollectionFields(true)
.withDiscriminatorFieldName(Some("name")))

def makeCirceLike[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withTransientDefault(false).withTransientNone(false)
.withDiscriminatorFieldName(None).withCirceLikeObjectEncoding(true))

def makeCirceLikeSnakeCased[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig(
fieldNameMapper = enforce_snake_case,
javaEnumValueNameMapper = enforce_snake_case,
adtLeafClassNameMapper = (x: String) => enforce_snake_case(simpleClassName(x)),
discriminatorFieldName = None,
isStringified = false,
mapAsArray = false,
skipUnexpectedFields = true,
transientDefault = false,
transientEmpty = false,
transientNone = false,
requireCollectionFields = false,
bigDecimalPrecision = 34,
bigDecimalScaleLimit = 6178,
bigDecimalDigitsLimit = 308,
bigIntDigitsLimit = 308,
bitSetValueLimit = 1024,
mapMaxInsertNumber = 1024,
setMaxInsertNumber = 1024,
allowRecursiveTypes = false,
requireDiscriminatorFirst = true,
useScalaEnumValueId = false,
skipNestedOptionValues = false,
circeLikeObjectEncoding = true,
decodingOnly = false,
encodingOnly = false,
requireDefaultFields = false,
checkFieldDuplication = true,
scalaTransientSupport = false,
inlineOneValueClasses = false,
alwaysEmitDiscriminator = false))

def makeWithSpecifiedConfig[A: Type](config: Expr[CodecMakerConfig])(using Quotes): Expr[JsonValueCodec[A]] = {
import quotes.reflect._
object Impl {
type FieldTypeResolver = (q: Quotes) ?=> (q.reflect.TypeRepr, q.reflect.Symbol) => q.reflect.TypeRepr

object FieldTypeResolver {
val original: FieldTypeResolver = (tpe, symbol) => {
tpe.memberType(symbol).dealias
}
}

try make[A](summon[FromExpr[CodecMakerConfig]].unapply(config)
.fold(report.errorAndAbort(s"Cannot evaluate a parameter of the 'make' macro call for type '${Type.show[A]}'. ")) {
cfg =>
if (cfg.requireCollectionFields && cfg.transientEmpty)
report.errorAndAbort("'requireCollectionFields' and 'transientEmpty' cannot be 'true' simultaneously")
if (cfg.requireDefaultFields && cfg.transientDefault)
report.errorAndAbort("'requireDefaultFields' and 'transientDefault' cannot be 'true' simultaneously")
if (cfg.circeLikeObjectEncoding && cfg.discriminatorFieldName.nonEmpty)
report.errorAndAbort("'discriminatorFieldName' should be 'None' when 'circeLikeObjectEncoding' is 'true'")
if (cfg.alwaysEmitDiscriminator && cfg.discriminatorFieldName.isEmpty)
report.errorAndAbort("'discriminatorFieldName' should not be 'None' when 'alwaysEmitDiscriminator' is 'true'")
if (cfg.decodingOnly && cfg.encodingOnly)
report.errorAndAbort("'decodingOnly' and 'encodingOnly' cannot be 'true' simultaneously")
cfg
}) catch {
case ex: CompileTimeEvalException => report.errorAndAbort(s"Can't evaluate compile-time expression: ${ex.message}", ex.expr)
// @plokhotnyuk: this is mainly used for backwards compatibility and being able to swap out
// implementations in tests without having to do a major refactor.
trait MacroAPI(val ftr: FieldTypeResolver) {
def makeWithDefaultConfig[A: Type](using Quotes): Expr[JsonValueCodec[A]] = make(CodecMakerConfig, ftr)

def makeWithoutDiscriminator[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withDiscriminatorFieldName(None), ftr)

def makeWithRequiredCollectionFields[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withRequireCollectionFields(true), ftr)

def makeWithRequiredDefaultFields[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientDefault(false).withRequireDefaultFields(true), ftr)

def makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withRequireCollectionFields(true)
.withDiscriminatorFieldName(Some("name")), ftr)

def makeCirceLike[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig.withTransientEmpty(false).withTransientDefault(false).withTransientNone(false)
.withDiscriminatorFieldName(None).withCirceLikeObjectEncoding(true), ftr)

def makeCirceLikeSnakeCased[A: Type](using Quotes): Expr[JsonValueCodec[A]] =
make(CodecMakerConfig(
fieldNameMapper = enforce_snake_case,
javaEnumValueNameMapper = enforce_snake_case,
adtLeafClassNameMapper = (x: String) => enforce_snake_case(simpleClassName(x)),
discriminatorFieldName = None,
isStringified = false,
mapAsArray = false,
skipUnexpectedFields = true,
transientDefault = false,
transientEmpty = false,
transientNone = false,
requireCollectionFields = false,
bigDecimalPrecision = 34,
bigDecimalScaleLimit = 6178,
bigDecimalDigitsLimit = 308,
bigIntDigitsLimit = 308,
bitSetValueLimit = 1024,
mapMaxInsertNumber = 1024,
setMaxInsertNumber = 1024,
allowRecursiveTypes = false,
requireDiscriminatorFirst = true,
useScalaEnumValueId = false,
skipNestedOptionValues = false,
circeLikeObjectEncoding = true,
decodingOnly = false,
encodingOnly = false,
requireDefaultFields = false,
checkFieldDuplication = true,
scalaTransientSupport = false,
inlineOneValueClasses = false,
alwaysEmitDiscriminator = false), ftr)

def makeWithSpecifiedConfig[A: Type](config: Expr[CodecMakerConfig])(using Quotes): Expr[JsonValueCodec[A]] = {
import quotes.reflect._

try make[A](summon[FromExpr[CodecMakerConfig]].unapply(config)
.fold(report.errorAndAbort(s"Cannot evaluate a parameter of the 'make' macro call for type '${Type.show[A]}'. ")) {
cfg =>
if (cfg.requireCollectionFields && cfg.transientEmpty)
report.errorAndAbort("'requireCollectionFields' and 'transientEmpty' cannot be 'true' simultaneously")
if (cfg.requireDefaultFields && cfg.transientDefault)
report.errorAndAbort("'requireDefaultFields' and 'transientDefault' cannot be 'true' simultaneously")
if (cfg.circeLikeObjectEncoding && cfg.discriminatorFieldName.nonEmpty)
report.errorAndAbort("'discriminatorFieldName' should be 'None' when 'circeLikeObjectEncoding' is 'true'")
if (cfg.alwaysEmitDiscriminator && cfg.discriminatorFieldName.isEmpty)
report.errorAndAbort("'discriminatorFieldName' should not be 'None' when 'alwaysEmitDiscriminator' is 'true'")
if (cfg.decodingOnly && cfg.encodingOnly)
report.errorAndAbort("'decodingOnly' and 'encodingOnly' cannot be 'true' simultaneously")
cfg
}, ftr) catch {
case ex: CompileTimeEvalException => report.errorAndAbort(s"Can't evaluate compile-time expression: ${ex.message}", ex.expr)
}
}
}

private[this] def make[A: Type](cfg: CodecMakerConfig)(using Quotes): Expr[JsonValueCodec[A]] = {
object api extends MacroAPI(FieldTypeResolver.original)
export api.*

// @plokhotnyuk: this is the only actual change required for my macros to work.
def make[A: Type](cfg: CodecMakerConfig, ftr: FieldTypeResolver)(using Quotes): Expr[JsonValueCodec[A]] = {
import quotes.reflect._

def fail(msg: String): Nothing = report.errorAndAbort(msg, Position.ofMacroExpansion)
Expand Down Expand Up @@ -948,7 +964,8 @@ object JsonCodecMaker {
} else None
val isStringified = annotationOption.exists(_.stringified)
val isTransient = annotationOption.exists(_.transient)
val originFieldType = tpe.memberType(symbol).dealias
// val originFieldType = tpe.memberType(symbol).dealias
val originFieldType = ftr(tpe, symbol)
val fieldType = typeArgs(tpe) match
case Nil => originFieldType
case typeArgs => originFieldType.substituteTypes(typeParams, typeArgs)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
package com.github.plokhotnyuk.jsoniter_scala.macros

import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker
import scala.quoted.*


// @plokhotnyuk: this is used by `JsonCodecMakerCustomSpec` to swap out the different implementations
// without requiring a major refactor. This is in order to ensure compatibility with existing tests.
// The reason for including this file in `main` instead of `test` is because the incremental compiler
// will crash when `originalResolverImpl` and `customResolverImpl` are used while in the same compile-unit
// as the tests.
object makerImpl {
import JsonCodecMaker.Impl
import JsonCodecMaker.Impl.FieldTypeResolver

// @plokhotnyuk: the default implementation
object jsonCodecMakerImpl {
export JsonCodecMaker.{
make,
makeWithoutDiscriminator,
makeWithRequiredCollectionFields,
makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName,
makeWithRequiredDefaultFields,
makeCirceLike,
makeCirceLikeSnakeCased
}
}

object defaultAPI extends Impl.MacroAPI(Impl.FieldTypeResolver.original)

// @plokhotnyuk: stubbed-out equivalent of the default implementation
object originalResolverImpl {

inline def make[A]: JsonValueCodec[A] = ${defaultAPI.makeWithDefaultConfig}

inline def makeWithoutDiscriminator[A]: JsonValueCodec[A] = ${defaultAPI.makeWithoutDiscriminator}

inline def makeWithRequiredCollectionFields[A]: JsonValueCodec[A] = ${defaultAPI.makeWithRequiredCollectionFields}

inline def makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName[A]: JsonValueCodec[A] =
${defaultAPI.makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName}

inline def makeWithRequiredDefaultFields[A]: JsonValueCodec[A] = ${defaultAPI.makeWithRequiredDefaultFields}

inline def makeCirceLike[A]: JsonValueCodec[A] = ${defaultAPI.makeCirceLike}

inline def makeCirceLikeSnakeCased[A]: JsonValueCodec[A] = ${defaultAPI.makeCirceLikeSnakeCased}

inline def make[A](inline config: CodecMakerConfig): JsonValueCodec[A] = ${defaultAPI.makeWithSpecifiedConfig('config)}
}

// @plokhotnyuk: this is the actual fix
object customAPI extends Impl.MacroAPI(
(tpe, symbol) => {
import quotes.reflect.*
val tst = symbol.typeRef.translucentSuperType.typeSymbol
if (tst.flags.is(Flags.JavaDefined) || tst.flags.is(Flags.Scala2x)) {
FieldTypeResolver.original(tpe, symbol)
} else {
tpe match {
case TypeRef(q, n) if q.typeSymbol.flags.is(Flags.Module) => {
val trmRef = q.typeSymbol.termRef
def recurse(t: TypeRepr): TypeRepr = t match {
case TermRef(q, n) => TermRef(recurse(q), n)
case tr @ TypeRef(q, n) => recurse(q).select(tr.typeSymbol)
case tt @ ThisType(tref) => {
if (!tref.typeSymbol.flags.is(Flags.Module) && (trmRef.baseClasses.contains(tref.typeSymbol))) {
// replacing ThisType with its concrete enclosing module
trmRef
} else {
tt
}
}
case _ => t
}
recurse(symbol.typeRef.translucentSuperType).dealias
}
case _ => {
FieldTypeResolver.original(tpe, symbol)
}
}
}
})

// @plokhotnyuk: stubbed-out custom implementation
object customResolverImpl {

inline def make[A]: JsonValueCodec[A] = ${customAPI.makeWithDefaultConfig}

inline def makeWithoutDiscriminator[A]: JsonValueCodec[A] = ${customAPI.makeWithoutDiscriminator}

inline def makeWithRequiredCollectionFields[A]: JsonValueCodec[A] = ${customAPI.makeWithRequiredCollectionFields}

inline def makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName[A]: JsonValueCodec[A] =
${customAPI.makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName}

inline def makeWithRequiredDefaultFields[A]: JsonValueCodec[A] = ${customAPI.makeWithRequiredDefaultFields}

inline def makeCirceLike[A]: JsonValueCodec[A] = ${customAPI.makeCirceLike}

inline def makeCirceLikeSnakeCased[A]: JsonValueCodec[A] = ${customAPI.makeCirceLikeSnakeCased}

inline def make[A](inline config: CodecMakerConfig): JsonValueCodec[A] = ${customAPI.makeWithSpecifiedConfig('config)}
}
}
Loading
Loading