diff --git a/core/src/main/scala-3.0.0-RC3/cats/derived/all.scala b/core/src/main/scala-3.0.0-RC3/cats/derived/all.scala index 9434e033..2d7d353e 100644 --- a/core/src/main/scala-3.0.0-RC3/cats/derived/all.scala +++ b/core/src/main/scala-3.0.0-RC3/cats/derived/all.scala @@ -12,4 +12,5 @@ object all extends OrderDerivation, PartialOrderDerivation, SemigroupDerivation, + ShowDerivation, TraverseDerivation diff --git a/core/src/main/scala-3.0.0-RC3/cats/derived/show.scala b/core/src/main/scala-3.0.0-RC3/cats/derived/show.scala new file mode 100644 index 00000000..3dc77013 --- /dev/null +++ b/core/src/main/scala-3.0.0-RC3/cats/derived/show.scala @@ -0,0 +1,32 @@ +package cats.derived + +import cats.Show +import shapeless3.deriving.{Continue, K0, Labelling} + +object show extends ShowDerivation + +trait ShowDerivation: + + extension (F: Show.type) + inline def derived[A](using gen: K0.Generic[A]): Show[A] = gen.derive(productShow, coproductShow) + + given productShow[A](using inst : => K0.ProductInstances[Show, A], l: Labelling[A]): Show[A] = + (a: A) => { + var idx = 0 + val x = inst.foldLeft[StringBuilder](a)(new StringBuilder(s"${l.label}("))( + [t] => (acc: StringBuilder, sh: Show[t], t0: t) => { + //elemLabels is backed by an array so this should be fast + val res = Continue(acc.append(s"${l.elemLabels(idx)}=${sh.show(t0)}, ")) + idx = idx + 1 + res + } + ) + if(idx > 0) {x.delete(x.length - 2, x.length)} + x.append(")") + x.toString() + } + + given coproductShow[A](using inst: => K0.CoproductInstances[Show, A]): Show[A] = + (a: A) => inst.fold[String](a)( + [t] => (sh: Show[t], t0: t) => sh.show(t0) + ) diff --git a/core/src/test/scala-3.0.0-RC3/cats/derived/ShowTests.scala b/core/src/test/scala-3.0.0-RC3/cats/derived/ShowTests.scala new file mode 100644 index 00000000..5e1066d3 --- /dev/null +++ b/core/src/test/scala-3.0.0-RC3/cats/derived/ShowTests.scala @@ -0,0 +1,9 @@ +package cats.derived + +import alleycats._ +import cats._ +import cats.derived.all._ + +class ShowTests { // + case class Foo(i: Int, b: Option[String]) derives Show +}