Skip to content

Commit 5a061fa

Browse files
committed
Derivation of more efficient constructors for named tuples
1 parent e95951d commit 5a061fa

File tree

1 file changed

+16
-5
lines changed
  • jsoniter-scala-macros/shared/src/main/scala-3/com/github/plokhotnyuk/jsoniter_scala/macros

1 file changed

+16
-5
lines changed

jsoniter-scala-macros/shared/src/main/scala-3/com/github/plokhotnyuk/jsoniter_scala/macros/JsonCodecMaker.scala

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -975,11 +975,23 @@ object JsonCodecMaker {
975975
def genNew(argss: List[List[Term]]): Term
976976
}
977977

978-
case class NamedTupleInfo(tpe: TypeRepr, tupleType: Type[?], isGeneric: Boolean,
978+
case class NamedTupleInfo(tpe: TypeRepr, typeArgs: List[TypeRepr],
979979
override val paramLists: List[List[FieldInfo]]) extends TypeInfo(tpe, paramLists) {
980-
def genNew(argss: List[List[Term]]): Term =
980+
val tupleType: Type[?] = tpe.asType
981+
val isGeneric: Boolean = isGenericTuple(tpe)
982+
983+
def genNew(argss: List[List[Term]]): Term = {
984+
val args = argss.flatten
985+
val constructor =
986+
if (isGeneric) {
987+
if (args.isEmpty) Expr(EmptyTuple)
988+
else Expr.ofTupleFromSeq(args.map(_.asExpr))
989+
} else {
990+
Apply(TypeApply(Select.unique(New(Inferred(tpe)), "<init>"), typeArgs.map(x => Inferred(x))), args).asExpr
991+
}
981992
// Borrowed from an amazing work of Aleksander Rainko: https://github.com/arainko/ducktape/blob/8d779f0303c23fd45815d3574467ffc321a8db2b/ducktape/src/main/scala/io/github/arainko/ducktape/internal/ProductConstructor.scala#L22
982-
Typed(Expr.ofTupleFromSeq(argss.flatten.map(_.asExpr)).asTerm, TypeTree.of(using tupleType))
993+
Typed(constructor.asTerm, TypeTree.of(using tupleType))
994+
}
983995
}
984996

985997
val namedTupleInfos = new mutable.LinkedHashMap[TypeRepr, NamedTupleInfo]
@@ -997,10 +1009,9 @@ object JsonCodecMaker {
9971009
val tupleCons = TypeRepr.of[*:]
9981010
(curr, acc) => tupleCons.appliedTo(curr :: acc :: Nil)
9991011
}
1000-
val isGeneric = isGenericTuple(tupleTpe)
10011012
val noSymbol = Symbol.noSymbol
10021013
var i = - 1
1003-
NamedTupleInfo(tpe, tupleTpe.asType, isGeneric, List(names.zip(typeArgs).map { case (name, fTpe) =>
1014+
NamedTupleInfo(tupleTpe, typeArgs, List(names.zip(typeArgs).map { case (name, fTpe) =>
10041015
i += 1
10051016
val mappedName = cfg.fieldNameMapper(name).getOrElse(name)
10061017
FieldInfo(noSymbol, mappedName, noSymbol, None, fTpe, false, false, i)

0 commit comments

Comments
 (0)