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

Modified project to cross-compile to scala 3 and 2 #97

Open
wants to merge 1 commit 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
24 changes: 17 additions & 7 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import sbtcrossproject.CrossPlugin.autoImport.{CrossType, crossProject}

ThisBuild / organization := "org.julienrf"

ThisBuild / scalaVersion := "2.13.3"
ThisBuild / scalaVersion := "3.3.3"

ThisBuild / crossScalaVersions := Seq(scalaVersion.value, "2.12.8")
ThisBuild / crossScalaVersions := Seq(scalaVersion.value, "2.13.15", "2.12.20")

ThisBuild / versionPolicyIntention := Compatibility.None

ThisBuild / version := "11.0.0-local"

ThisBuild / mimaBinaryIssueFilters ++= Seq(
// package private method
ProblemFilters.exclude[IncompatibleSignatureProblem]("julienrf.json.derived.DerivedOWritesUtil.makeCoProductOWrites")
Expand Down Expand Up @@ -38,12 +40,20 @@ val library =
.settings(
name := "play-json-derived-codecs",
libraryDependencies ++= Seq(
"com.chuusai" %%% "shapeless" % "2.3.3",
"org.scalatest" %%% "scalatest" % "3.2.3" % Test,
"org.scalacheck" %%% "scalacheck" % "1.15.2" % Test,
"org.scalatestplus" %%% "scalacheck-1-15" % "3.2.3.0" % Test,
"org.playframework" %%% "play-json" % "3.0.1"
"org.scalatest" %%% "scalatest" % "3.2.19" % Test,
"org.scalacheck" %%% "scalacheck" % "1.15.4" % Test,
"org.scalatestplus" %%% "scalacheck-1-15" % "3.2.11.0" % Test,
"org.playframework" %%% "play-json" % "3.0.4"
),
libraryDependencies ++= {
CrossVersion.partialVersion(scalaVersion.value) match {
case Some((2, _)) => Seq(
"com.chuusai" %%% "shapeless" % "2.3.3"
)
case _ =>
Seq.empty
}
},
scalacOptions ++= {
Seq(
"-deprecation",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
package julienrf.json.derived

/** Adapter function to transform case classes member names during the derivation process
*
* A NameAdapter can be used to customize the derivation process, allowing to apply a transformation function
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package julienrf.json.derived

import play.api.libs.json.*

import scala.compiletime.*
import scala.deriving.Mirror

/**
* Derives an `OWrites[A]`
*
* @tparam TT Type of TypeTag to use to discriminate alternatives of sealed traits
*/
trait DerivedOWrites[A, TT <: TypeTag[A]] {

/**
* @param tagOwrites The strategy to use to serialize sum types
* @param adapter The fields naming strategy
* @return The derived `OWrites[A]`
*/
def owrites(tagOwrites: TypeTagOWrites, adapter: NameAdapter): OWrites[A]
}

object DerivedOWrites extends DerivedOWritesInstances

trait DerivedOWritesInstances {
inline given derivedSumWrites[A, TT[S] <: TypeTag[S]](using m: Mirror.SumOf[A]): DerivedOWrites[A, TT[A]] = new DerivedOWrites[A, TT[A]] {
def owrites(tagOwrites: TypeTagOWrites, adapter: NameAdapter): OWrites[A] = sumWrites[A, TT](m, tagOwrites, adapter)
}

inline given derivedProductWrites[A, TT[P] <: TypeTag[P]](using m: Mirror.ProductOf[A], tt: TT[A]): DerivedOWrites[A, TT[A]] = new DerivedOWrites[A, TT[A]] {
def owrites(tagOwrites: TypeTagOWrites, adapter: NameAdapter): OWrites[A] = productWrites(m, tagOwrites, adapter)
}


private inline def sumWrites[A, TT[P] <: TypeTag[P]](s: Mirror.SumOf[A], tagOwrites: TypeTagOWrites, adapter: NameAdapter): OWrites[A] = new OWrites[A] {
def writes(a: A): JsObject = {
val ordinal = s.ordinal(a)
val elemWritesAndTypeTags = summonAllWritesAndTypeTags[s.MirroredElemTypes, TT](tagOwrites, adapter)
val (write, fieldName) = elemWritesAndTypeTags(ordinal)
tagOwrites.owrites(fieldName, write.asInstanceOf[Writes[A]]).writes(a)
}
}

private inline def productWrites[A](m: Mirror.Of[A], tagOwrites: TypeTagOWrites, adapter: NameAdapter): OWrites[A] = new OWrites[A] {
private val elemLabels = summonAllLabels[m.MirroredElemLabels].map(adapter)
private val elemWrites = summonAllWrites[m.MirroredElemTypes]

def writes(a: A): JsObject = {
val elems = a.asInstanceOf[Product].productIterator.toList
val fields = elemLabels.zip(elems).zip(elemWrites).map {
case ((label, value), writes) =>
label -> writes.asInstanceOf[Writes[Any]].writes(value)
}
JsObject(fields)
}
}

private inline def summonWrites[T]: Writes[T] = summonInline[Writes[T]]


private inline def summonAllWritesAndTypeTags[T <: Tuple, TT[P] <: TypeTag[P]](tagOWrites: TypeTagOWrites, adapter: NameAdapter): List[(Writes[_], String)] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (hh *: ts) =>
val (headWrite, headTagType) = summonWritesOrFallback[hh, TT] {
val derivedOWrites = summonInline[DerivedOWrites[hh, TT[hh]]]
val fieldName = summonInline[TT[hh]].value
val writes = derivedOWrites.owrites(tagOWrites, adapter)
(writes, fieldName)
}
(headWrite, headTagType) :: summonAllWritesAndTypeTags[ts, TT](tagOWrites, adapter)


private inline def summonAllWrites[T <: Tuple]: List[Writes[_]] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (hh *: ts) => summonWrites[hh] :: summonAllWrites[ts]

private inline def summonAllLabels[T <: Tuple]: List[String] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (hx *: tx) => constValue[hx].asInstanceOf[String] :: summonAllLabels[tx]

private inline def summonWritesOrFallback[T, TT[P] <: TypeTag[P]](fallback: => (Writes[T], String)): (Writes[T], String) =
summonFrom[Writes[T]] {
case r: Writes[T] => r -> summonInline[TT[T]].value
case _ => fallback
}
}
96 changes: 96 additions & 0 deletions library/src/main/scala-3/julienrf/json/derived/DerivedReads.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package julienrf.json.derived

import play.api.libs.json.*

import scala.compiletime.*
import scala.deriving.Mirror
import scala.reflect.ClassTag
import scala.util.{Failure, Success, Try}


trait DerivedReads[A, TT <: TypeTag[A]] {
def reads(tagReads: TypeTagReads, adapter: NameAdapter): Reads[A]
}

object DerivedReads {
inline given derivedSumReads[A, TT[S] <: TypeTag[S]](using m: Mirror.SumOf[A]): DerivedReads[A, TT[A]] = new DerivedReads[A, TT[A]] {
def reads(tagReads: TypeTagReads, adapter: NameAdapter): Reads[A] = sumReads[A, TT](m, tagReads, adapter)
}

inline given derivedProductReads[A, TT <: TypeTag[A]](using m: Mirror.ProductOf[A], tt: TT): DerivedReads[A, TT] = new DerivedReads[A, TT] {
def reads(tagReads: TypeTagReads, adapter: NameAdapter): Reads[A] = productReads(m, adapter)
}

private inline def summonReads[T]: Reads[T] = summonInline[Reads[T]]

private inline def summonAllReads[T <: Tuple]: List[(Reads[_], Boolean)] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (Option[s] *: ts) =>
(summonReads[s], true) :: summonAllReads[ts]
case _: (s *: ts) =>
(summonReads[s], false) :: summonAllReads[ts]

private inline def summonAllTypes[T <: Tuple]: List[_] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (s *: ts) => erasedValue[s] :: summonAllTypes[ts]

private inline def summonLabels[T <: Tuple]: List[String] =
inline erasedValue[T] match
case _: EmptyTuple => Nil
case _: (head *: tail) => constValue[head].asInstanceOf[String] :: summonLabels[tail]

private inline def summonReadsOrFallback[T, TT[P] <: TypeTag[P]](fallback: => (Reads[T], String)): (Reads[T], String) =
summonFrom[Reads[T]] {
case r: Reads[T] => r -> summonInline[TT[T]].value
case _ => fallback
}

private inline def productReads[A, TT <: TypeTag[A]](m: Mirror.ProductOf[A], adapter: NameAdapter)(using typeTag: TT): Reads[A] =
val elemReads = summonAllReads[m.MirroredElemTypes]
val elemLabels = summonLabels[m.MirroredElemLabels].map(adapter)

Reads { json =>

val results = elemLabels.zip(elemReads).map {
case (label, (read, false)) =>
(json \ label).validate(read.asInstanceOf[Reads[Any]])
case (label, (read, true)) =>
(json \ label).validateOpt(read.asInstanceOf[Reads[Any]])
}

results.collect { case JsError(errors) => errors } match
case Nil =>
val args = results.map(_.get)
Try(m.fromProduct(Tuple.fromArray(args.toArray))) match
case Success(value: A) => JsSuccess(value)
case Failure(ex) => JsError(s"Error constructing instance: ${ex.getMessage}")
case errors =>
JsError(errors.flatten)
}


private inline def handleSumTypes[T <: Tuple, A, TT[P] <: TypeTag[P]](tagReads: TypeTagReads, json: JsValue, adapter: NameAdapter): JsResult[A] = inline erasedValue[T] match {
case _: (h *: ts) =>
val (reads, fieldName) = summonReadsOrFallback[h, TT] {
val derivedReads = summonInline[DerivedReads[h, TT[h]]]
val reads = derivedReads.reads(tagReads, adapter)
reads -> summonInline[TT[h]].value
}

tagReads.reads(fieldName, reads).reads(json) match {
case JsSuccess(value, _) =>
JsSuccess(value.asInstanceOf[A])
case JsError(_) => handleSumTypes[ts, A, TT](tagReads, json, adapter)
}
case _: EmptyTuple =>
JsError(s"Could not find a matching type for $json")
}


inline def sumReads[A, TT[P] <: TypeTag[P]](s: Mirror.SumOf[A], tagReads: TypeTagReads, adapter: NameAdapter): Reads[A] = new Reads[A] {
def reads(json: JsValue): JsResult[A] = handleSumTypes[s.MirroredElemTypes, A, TT](tagReads, json, adapter)
}

}
53 changes: 53 additions & 0 deletions library/src/main/scala-3/julienrf/json/derived/NameAdapter.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package julienrf.json.derived

/** Adapter function to transform case classes member names during the derivation process
*
* A NameAdapter can be used to customize the derivation process, allowing to apply a transformation function
* to case classes member names when deriving serializers/deserializers
*
* For instance, it can be used to derive serializers/deserializers that use a different casing for the json keys.
*
* For example, to derive a Format[A] that uses snake_case for the json keys (using the predefined [[NameAdapter.snakeCase]])
* {{{
* import julienrf.json.derived
* import julienrf.json.derived.NameAdapter
* import play.api.libs.json.{Format, Json}
*
* case class Bar(camelCase: String)
* object Bar {
* implicit val format: Format[Bar] = derived.oformat[Bar](NameAdapter.snakeCase)
* }
* }}}
*
* {{{
* scala> Json.toJson(Bar("a json value"))
* res0: play.api.libs.json.JsValue = {"camel_case":"a json value"}
*
* scala> Json.fromJson[Bar](Json.parse("""{"camel_case":"a json value"}"""))
* res1: play.api.libs.json.JsResult[Bar] = JsSuccess(Bar(a json value),)
* }}}
*/
trait NameAdapter extends (String => String)

object NameAdapter {

/** Converts case classes member names from camelCase to snake_case */
val snakeCase = NameAdapter {
(s: String) => {
val builder = new StringBuilder
s foreach {
case c if Character.isUpperCase(c) && builder.nonEmpty =>
builder append "_" append (Character toLowerCase c)
case c => builder append c
}
builder.toString
}
}

/** Does not apply any transformation to case classes member names */
val identity = NameAdapter(s => s)

def apply(f: (String => String)): NameAdapter = new NameAdapter {
override def apply(v1: String): String = f(v1)
}
}
50 changes: 50 additions & 0 deletions library/src/main/scala-3/julienrf/json/derived/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package julienrf.json

import play.api.libs.json.{OFormat, OWrites, Reads}

import scala.compiletime.summonFrom

package object derived {

inline def reads[A](adapter: NameAdapter = NameAdapter.identity)(using derivedReads: DerivedReads[A, TypeTag.ShortClassName[A]]): Reads[A] =
derivedReads.reads(TypeTagReads.nested, adapter)

inline def owrites[A](adapter: NameAdapter = NameAdapter.identity)(using derivedOWrites: DerivedOWrites[A, TypeTag.ShortClassName[A]]): OWrites[A] =
derivedOWrites.owrites(TypeTagOWrites.nested, adapter)

inline def oformat[A](adapter: NameAdapter = NameAdapter.identity)(using derivedReads: DerivedReads[A, TypeTag.ShortClassName[A]], derivedOWrites: DerivedOWrites[A, TypeTag.ShortClassName[A]]): OFormat[A] =
OFormat(derivedReads.reads(TypeTagReads.nested, adapter), derivedOWrites.owrites(TypeTagOWrites.nested, adapter))

object flat {

inline def reads[A](typeName: Reads[String], adapter: NameAdapter = NameAdapter.identity)(using derivedReads: DerivedReads[A, TypeTag.ShortClassName[A]]): Reads[A] =
derivedReads.reads(TypeTagReads.flat(typeName), adapter)

inline def owrites[A](typeName: OWrites[String], adapter: NameAdapter = NameAdapter.identity)(using derivedOWrites: DerivedOWrites[A, TypeTag.ShortClassName[A]]): OWrites[A] =
derivedOWrites.owrites(TypeTagOWrites.flat(typeName), adapter)

inline def oformat[A](typeName: OFormat[String], adapter: NameAdapter = NameAdapter.identity)(using derivedReads: DerivedReads[A, TypeTag.ShortClassName[A]], derivedOWrites: DerivedOWrites[A, TypeTag.ShortClassName[A]]): OFormat[A] =
OFormat(derivedReads.reads(TypeTagReads.flat(typeName), adapter), derivedOWrites.owrites(TypeTagOWrites.flat(typeName), adapter))

}

object withTypeTag {

inline def reads[A](typeTagSetting: TypeTagSetting, adapter: NameAdapter = NameAdapter.identity, typeTagReads: TypeTagReads = TypeTagReads.nested)(using derivedReads: DerivedReads[A, typeTagSetting.Value[A]]): Reads[A] =
derivedReads.reads(typeTagReads, adapter)

inline def owrites[A](typeTagSetting: TypeTagSetting, adapter: NameAdapter = NameAdapter.identity, typeTagOWrites: TypeTagOWrites = TypeTagOWrites.nested)(using derivedOWrites: DerivedOWrites[A, typeTagSetting.Value[A]]): OWrites[A] =
derivedOWrites.owrites(typeTagOWrites, adapter)

inline def oformat[A](typeTagSetting: TypeTagSetting, adapter: NameAdapter = NameAdapter.identity, typeTagOFormat: TypeTagOFormat = TypeTagOFormat.nested)(using derivedReads: DerivedReads[A, typeTagSetting.Value[A]], derivedOWrites: DerivedOWrites[A, typeTagSetting.Value[A]]): OFormat[A] =
OFormat(derivedReads.reads(typeTagOFormat, adapter), derivedOWrites.owrites(typeTagOFormat, adapter))

}

private[derived] inline def summonTypeTagOrFallback[A, TT[P] <: TypeTag[P]](fallback: => TypeTag[A]): TypeTag[A] =
summonFrom[TT[A]] {
case r: TT[A] => r
case _ => fallback
}

}
Loading
Loading