scala.annotation.implicitNotFound Scala Examples

The following examples show how to use scala.annotation.implicitNotFound. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: ExerciseOn.scala    From daml   with Apache License 2.0 5 votes vote down vote up
// Copyright (c) 2020 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package com.daml.ledger.client.binding
package encoding

import Primitive.ContractId
import Template.CreateForExercise

import scala.annotation.implicitNotFound

@implicitNotFound(
  """Cannot decide how to exercise a choice on ${Self}; only well-typed contract IDs and Templates (.createAnd) are candidates for choice exercise""")
sealed abstract class ExerciseOn[-Self, Tpl]

object ExerciseOn {
  implicit def OnId[T]: ExerciseOn[ContractId[T], T] = new OnId
  implicit def CreateAndOnTemplate[T]: ExerciseOn[CreateForExercise[T], T] =
    new CreateAndOnTemplate

  private[binding] final class OnId[T] extends ExerciseOn[ContractId[T], T]
  private[binding] final class CreateAndOnTemplate[T] extends ExerciseOn[CreateForExercise[T], T]
} 
Example 2
Source File: CommutativeSemigroupDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.kernel.CommutativeSemigroup
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object CommutativeSemigroupDerivation {
  type Typeclass[T] = CommutativeSemigroup[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = SemigroupMethods.combineN(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)

    new CommutativeSemigroup[T] {
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
    }
  }

  @implicitNotFound("Cannot derive CommutativeSemigroup for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
} 
Example 3
Source File: CommutativeGroupDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.kernel.CommutativeGroup
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object CommutativeGroupDerivation {
  type Typeclass[T] = CommutativeGroup[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val emptyImpl = MonoidMethods.empty(caseClass)
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = GroupMethods.combineN(caseClass)
    val combineAllImpl = MonoidMethods.combineAll(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)
    val inverseImpl = GroupMethods.inverse(caseClass)
    val removeImpl = GroupMethods.remove(caseClass)

    new CommutativeGroup[T] {
      override def empty: T = emptyImpl()
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAll(as: IterableOnce[T]): T = combineAllImpl(as)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
      override def inverse(a: T): T = inverseImpl(a)
      override def remove(a: T, b: T): T = removeImpl(a, b)
    }
  }

  @implicitNotFound("Cannot derive CommutativeGroup for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
} 
Example 4
Source File: SemigroupDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.Semigroup
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object SemigroupDerivation {
  type Typeclass[T] = Semigroup[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = SemigroupMethods.combineN(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)

    new Semigroup[T] {
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
    }
  }

  @implicitNotFound("Cannot derive Semigroup for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
}

private object SemigroupMethods {
  def combine[T, Typeclass[T] <: Semigroup[T]](caseClass: CaseClass[Typeclass, T]): (T, T) => T =
    (x, y) => caseClass.construct(p => p.typeclass.combine(p.dereference(x), p.dereference(y)))

  def combineNBase[T, Typeclass[T] <: Semigroup[T]](
    caseClass: CaseClass[Typeclass, T]
  ): (T, Int) => T =
    (a: T, n: Int) => caseClass.construct(p => p.typeclass.combineN(p.dereference(a), n))

  def combineN[T, Typeclass[T] <: Semigroup[T]](
    caseClass: CaseClass[Typeclass, T]
  ): (T, Int) => T = {
    val f = combineNBase(caseClass)
    (a: T, n: Int) =>
      if (n <= 0) {
        throw new IllegalArgumentException("Repeated combining for semigroups must have n > 0")
      } else {
        f(a, n)
      }
  }

  def combineAllOption[T, Typeclass[T] <: Semigroup[T]](
    caseClass: CaseClass[Typeclass, T]
  ): IterableOnce[T] => Option[T] = {
    val combineImpl = combine(caseClass)
    as: IterableOnce[T] =>
      as match {
        case it: Iterable[T] if it.nonEmpty =>
          // input is re-iterable and non-empty, combineAllOption on each field
          val result = Array.fill[Any](caseClass.parameters.length)(null)
          var i = 0
          while (i < caseClass.parameters.length) {
            val p = caseClass.parameters(i)
            result(i) = p.typeclass.combineAllOption(it.iterator.map(p.dereference)).get
            i += 1
          }
          Some(caseClass.rawConstruct(result))
        case xs =>
          xs.reduceOption(combineImpl)
      }
  }
} 
Example 5
Source File: BandDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.kernel.Band
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object BandDerivation {
  type Typeclass[T] = Band[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = SemigroupMethods.combineN(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)

    new Band[T] {
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
    }
  }

  @implicitNotFound("Cannot derive Band for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
} 
Example 6
Source File: GroupDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.Group
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object GroupDerivation {
  type Typeclass[T] = Group[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val emptyImpl = MonoidMethods.empty(caseClass)
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = GroupMethods.combineN(caseClass)
    val combineAllImpl = MonoidMethods.combineAll(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)
    val inverseImpl = GroupMethods.inverse(caseClass)
    val removeImpl = GroupMethods.remove(caseClass)

    new Group[T] {
      override def empty: T = emptyImpl()
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAll(as: IterableOnce[T]): T = combineAllImpl(as)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
      override def inverse(a: T): T = inverseImpl(a)
      override def remove(a: T, b: T): T = removeImpl(a, b)
    }
  }

  @implicitNotFound("Cannot derive Group for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
}

private object GroupMethods {
  def combineN[T, Typeclass[T] <: Group[T]](caseClass: CaseClass[Typeclass, T]): (T, Int) => T = {
    val emptyImpl = MonoidMethods.empty(caseClass)
    val combineImpl = SemigroupMethods.combine(caseClass)
    val f = SemigroupMethods.combineNBase(caseClass)
    val inverseImpl = inverse(caseClass)
    val removeImpl = remove(caseClass)
    (a: T, n: Int) =>
      if (n > 0) {
        f(a, n)
      } else if (n == 0) {
        emptyImpl()
      } else if (n == Int.MinValue) {
        f(inverseImpl(combineImpl(a, a)), 1073741824)
      } else {
        f(inverseImpl(a), -n)
      }
  }

  def inverse[T, Typeclass[T] <: Group[T]](caseClass: CaseClass[Typeclass, T]): T => T =
    a => caseClass.construct(p => p.typeclass.inverse(p.dereference(a)))

  def remove[T, Typeclass[T] <: Group[T]](caseClass: CaseClass[Typeclass, T]): (T, T) => T =
    (a, b) => caseClass.construct(p => p.typeclass.remove(p.dereference(a), p.dereference(b)))
} 
Example 7
Source File: MonoidDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.Monoid
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object MonoidDerivation {
  type Typeclass[T] = Monoid[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val emptyImpl = MonoidMethods.empty(caseClass)
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = MonoidMethods.combineN(caseClass)
    val combineAllImpl = MonoidMethods.combineAll(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)

    new Monoid[T] {
      override def empty: T = emptyImpl()
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAll(as: IterableOnce[T]): T = combineAllImpl(as)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
    }
  }

  @implicitNotFound("Cannot derive Monoid for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
}

private object MonoidMethods {
  def empty[T, Typeclass[T] <: Monoid[T]](caseClass: CaseClass[Typeclass, T]): () => T =
    new Function0[T] with Serializable {
      @transient private lazy val value = caseClass.construct(_.typeclass.empty)
      override def apply(): T = value
    }

  def combineN[T, Typeclass[T] <: Monoid[T]](caseClass: CaseClass[Typeclass, T]): (T, Int) => T = {
    val emptyImpl = empty(caseClass)
    val f = SemigroupMethods.combineNBase(caseClass)
    (a: T, n: Int) =>
      if (n < 0) {
        throw new IllegalArgumentException("Repeated combining for monoids must have n >= 0")
      } else if (n == 0) {
        emptyImpl()
      } else {
        f(a, n)
      }
  }

  def combineAll[T, Typeclass[T] <: Monoid[T]](
    caseClass: CaseClass[Typeclass, T]
  ): IterableOnce[T] => T = {
    val combineImpl = SemigroupMethods.combine(caseClass)
    val emptyImpl = MonoidMethods.empty(caseClass)
    as: IterableOnce[T] =>
      as match {
        case it: Iterable[T] if it.nonEmpty =>
          // input is re-iterable and non-empty, combineAll on each field
          val result = Array.fill[Any](caseClass.parameters.length)(null)
          var i = 0
          while (i < caseClass.parameters.length) {
            val p = caseClass.parameters(i)
            result(i) = p.typeclass.combineAll(it.iterator.map(p.dereference))
            i += 1
          }
          caseClass.rawConstruct(result)
        case xs => xs.foldLeft(emptyImpl())(combineImpl)
      }
  }
} 
Example 8
Source File: CommutativeMonoidDerivation.scala    From magnolify   with Apache License 2.0 5 votes vote down vote up
package magnolify.cats.semiauto

import cats.kernel.CommutativeMonoid
import magnolia._

import scala.annotation.implicitNotFound
import scala.language.experimental.macros

object CommutativeMonoidDerivation {
  type Typeclass[T] = CommutativeMonoid[T]

  def combine[T](caseClass: CaseClass[Typeclass, T]): Typeclass[T] = {
    val emptyImpl = MonoidMethods.empty(caseClass)
    val combineImpl = SemigroupMethods.combine(caseClass)
    val combineNImpl = MonoidMethods.combineN(caseClass)
    val combineAllImpl = MonoidMethods.combineAll(caseClass)
    val combineAllOptionImpl = SemigroupMethods.combineAllOption(caseClass)

    new CommutativeMonoid[T] {
      override def empty: T = emptyImpl()
      override def combine(x: T, y: T): T = combineImpl(x, y)
      override def combineN(a: T, n: Int): T = combineNImpl(a, n)
      override def combineAll(as: IterableOnce[T]): T = combineAllImpl(as)
      override def combineAllOption(as: IterableOnce[T]): Option[T] = combineAllOptionImpl(as)
    }
  }

  @implicitNotFound("Cannot derive CommutativeMonoid for sealed trait")
  private sealed trait Dispatchable[T]
  def dispatch[T: Dispatchable](sealedTrait: SealedTrait[Typeclass, T]): Typeclass[T] = ???

  implicit def apply[T]: Typeclass[T] = macro Magnolia.gen[T]
} 
Example 9
Source File: Casting.scala    From spatial   with MIT License 5 votes vote down vote up
package argon.static

import forge.tags.rig

import scala.annotation.implicitNotFound

trait Casting {
  @implicitNotFound(msg = "Casting from ${A} to ${B} is undefined.")
  type Cast[A,B] = Either[Cast2Way[B,A],CastFunc[A,B]]
  type Lifting[A,B] = Right[Nothing,Lifter[A,B]]

  object Lifting {
    def apply[A,B:Type]: Lifting[A,B] = Right(new Lifter[A,B])
  }

  implicit class CastOps[A,B](c: Cast[A,B]) {
    @rig def apply(a: A): B = c match {
      case Left(cast)  => cast.applyLeft(a)
      case Right(cast) => cast(a)
    }
    @rig def applyLeft(b: B): Option[A] = c match {
      case Left(cast)  => cast.get(b)
      case Right(cast) => cast.getLeft(b)
    }
    @rig def saturating(a: A): B = c match {
      case Left(cast)  => cast.saturatingLeft(a)
      case Right(cast) => cast.saturating(a)
    }
    @rig def unbiased(a: A): B = c match {
      case Left(cast)  => cast.unbiasedLeft(a)
      case Right(cast) => cast.unbiased(a)
    }
    @rig def unbsat(a: A): B = c match {
      case Left(cast)  => cast.unbsatLeft(a)
      case Right(cast) => cast.unbsat(a)
    }
    @rig def saturatingLeft(b: B): Option[A] = c match {
      case Left(cast)  => cast.get(b)
      case Right(cast) => cast.saturatingGetLeft(b)
    }
    @rig def unbiasedLeft(b: B): Option[A] = c match {
      case Left(cast)  => cast.get(b)
      case Right(cast) => cast.unbiasedGetLeft(b)
    }
    @rig def unbsatLeft(b: B): Option[A] = c match {
      case Left(cast)  => cast.get(b)
      case Right(cast) => cast.unbsatGetLeft(b)
    }
    @rig def unchecked(a: A): B = c match {
      case Left(cast)  => cast.uncheckedLeft(a)
      case Right(cast) => cast.unchecked(a)
    }
    @rig def uncheckedLeft(b: B): Option[A] = c match {
      case Left(cast)  => cast.get(b)
      case Right(cast) => cast.uncheckedGetLeft(b)
    }

    def rightType: Type[B] = c match {
      case Left(cast)  => cast.tA
      case Right(cast) => cast.tB
    }
    def leftType: Option[Type[A]] = c match {
      case Left(cast)  => Some(cast.tB)
      case Right(cast) => None
    }
  }

  @rig def cast[A,B](a: A)(implicit cast: Cast[A,B]): B = cast.apply(a)

  implicit class SelfType[A<:Ref[_,_]](x: A) {
    def selfType: A = x.tp.asInstanceOf[A]
  }
} 
Example 10
Source File: AppError.scala    From octopus   with Apache License 2.0 5 votes vote down vote up
package octopus

import scala.concurrent.{ExecutionContext, Future}
import language.higherKinds
import scala.annotation.implicitNotFound

@implicitNotFound("Implicit instance for octopus.AppError[${M}] not found in scope!")
trait AppError[M[_]] extends Serializable {
  def pure[A](a: A): M[A]
  def failed[A](why: Throwable): M[A]
  def map[A, B](ma: M[A])(f: A => B): M[B]
  def map2[A, B, C](ma: M[A], mb: M[B])(f: (A, B) => C): M[C]
  def recover[A, B <: A](ma: M[A], f: PartialFunction[Throwable, B]): M[A]
}

object AppError extends Serializable {
  def apply[M[_]](implicit a: AppError[M]): AppError[M] = a

  implicit def futureAppError(implicit ec: ExecutionContext): AppError[Future] = new AppError[Future] {
    def pure[A](a: A): Future[A] =
      Future.successful(a)

    def failed[A](why: Throwable): Future[A] =
      Future.failed[A](why)

    def map[A, B](fa: Future[A])(f: A => B): Future[B] =
      fa.map(f)

    def map2[A, B, C](fa: Future[A], fb: Future[B])(f: (A, B) => C): Future[C] =
      fa.zip(fb).map { case (a, b) => f(a, b) }

    def recover[A, B <: A](fa: Future[A], f: PartialFunction[Throwable, B]): Future[A] =
      fa.recover(f)
  }
} 
Example 11
Source File: package.scala    From featherbed   with Apache License 2.0 5 votes vote down vote up
package featherbed

import scala.annotation.implicitNotFound
import scala.language.higherKinds

import cats.data.Validated.Valid
import com.twitter.finagle.http.Response
import shapeless._

package object support {

  @implicitNotFound("""In order to decode a request to ${A}, it must be known that a decoder exists to ${A} from
all the content types that you Accept, which is currently ${ContentTypes}.
You may have forgotten to specify Accept types with the `accept(..)` method,
or you may be missing Decoder instances for some content types.
""")
  sealed trait DecodeAll[A, ContentTypes <: Coproduct] {
    val instances: List[content.Decoder.Aux[_, A]]
    def findInstance(ct: String): Option[content.Decoder.Aux[_, A]] =
      instances.find(_.contentType == ct) orElse instances.find(_.contentType == "**"
        def apply(response: Response) = Valid(response)
      } :: Nil
    }
  }
} 
Example 12
Source File: Body.scala    From play-ws   with Apache License 2.0 5 votes vote down vote up
package play.api.libs.ws

import akka.stream.scaladsl.Source
import akka.util.ByteString

import scala.annotation.implicitNotFound


@implicitNotFound(
  "Cannot find an instance of ${A} to WSBody. Define a BodyWritable[${A}] or extend play.api.libs.ws.ahc.DefaultBodyWritables"
)
class BodyWritable[-A](val transform: A => WSBody, val contentType: String) {
  def map[B](f: B => A): BodyWritable[B] = new BodyWritable(b => transform(f(b)), contentType)
}

object BodyWritable {
  def apply[A](transform: (A => WSBody), contentType: String): BodyWritable[A] =
    new BodyWritable(transform, contentType)
} 
Example 13
Source File: QueryParams.scala    From finagle-postgres   with Apache License 2.0 5 votes vote down vote up
package com.twitter.finagle.postgres.generic

import scala.annotation.implicitNotFound
import scala.collection.GenTraversable

import com.twitter.finagle.postgres.Param
import com.twitter.finagle.postgres.values.ValueEncoder
import shapeless.ops.hlist.{Length, LiftAll, Mapper, ToList, ToTraversable, Tupler, Unifier, Zip}
import shapeless.ops.nat.ToInt
import shapeless.ops.record.Keys
import shapeless.{Generic, HList, HNil, LUBConstraint, LabelledGeneric, Nat, Poly1}


@implicitNotFound(
"""Could not represent the given value(s) of type ${T} as query parameters. The value must either be a scalar with a ValueEncoder instance, a Seq whose type parameter has a ValueEncoder instance, or a homogeneous tuple whose type has a ValueEncoder instance."""
)
trait QueryParams[T] {
  def apply(t: T): Seq[Param[_]]
  def placeholders(t: T, start: Int): Seq[String]
}

object QueryParams extends QueryParams0 {
  implicit def seq[F[A] <: Seq[A], T](implicit encoder: ValueEncoder[T]): QueryParams[F[T]] = new QueryParams[F[T]] {
    @inline final def apply(ts: F[T]): Seq[Param[_]] = ts.map(t => Param(t))
    @inline final def placeholders(ts: F[T], start: Int) = (start until (start + ts.length)).map(i => s"$$$i")
  }
}

trait QueryParams0 extends QueryParams1 { self: QueryParams.type =>

  implicit def tuple[A <: Product, L <: HList, P <: HList, N <: Nat](implicit
    gen: Generic.Aux[A, L],
    length: Length.Aux[L, N],
    tupler: Tupler.Aux[L, A],
    toInt: ToInt[N],
    mapper: Mapper.Aux[toParam.type, L, P],
    toTraversable: ToTraversable.Aux[P, Seq, Param[_]]
  ): QueryParams[A] = new QueryParams[A] {
    @inline final def apply(a: A): Seq[Param[_]] = toTraversable(mapper(gen.to(a)))
    @inline final def placeholders(a: A, start: Int) = (start until (start + toInt())).map(i => s"$$$i")
  }

}

trait QueryParams1 { self: QueryParams.type =>

  implicit def single[T](implicit encoder: ValueEncoder[T]): QueryParams[T] = new QueryParams[T] {
    def apply(t: T): Seq[Param[T]] = Seq(Param(t))
    def placeholders(t: T, start: Int) = Seq(s"$$$start")
  }

} 
Example 14
Source File: AmqpCheckSupport.scala    From gatling-amqp-plugin   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.gatling.amqp.checks

import java.nio.charset.Charset
import java.util.{Map => JMap}

import io.gatling.commons.validation._
import io.gatling.core.Predef.Session
import io.gatling.core.check._
import io.gatling.core.check.bytes.BodyBytesCheckType
import io.gatling.core.check.string.BodyStringCheckType
import io.gatling.core.check.xpath.XmlParsers
import io.gatling.core.json.JsonParsers
import io.gatling.core.session.Expression
import ru.tinkoff.gatling.amqp.AmqpCheck
import ru.tinkoff.gatling.amqp.checks.AmqpResponseCodeCheckBuilder.{AmqpMessageCheckType, ExtendedDefaultFindCheckBuilder, _}
import ru.tinkoff.gatling.amqp.request.AmqpProtocolMessage

import scala.annotation.implicitNotFound
import scala.util.Try

trait AmqpCheckSupport {
  def messageCheck: AmqpMessageCheck.type                                                              = AmqpMessageCheck
  val responseCode: ExtendedDefaultFindCheckBuilder[AmqpMessageCheckType, AmqpProtocolMessage, String] = ResponseCode

  @implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
  implicit def checkBuilder2AmqpCheck[A, P, X](checkBuilder: CheckBuilder[A, P, X])(
      implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
    checkBuilder.build(materializer)

  @implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
  implicit def validatorCheckBuilder2AmqpCheck[A, P, X](validatorCheckBuilder: ValidatorCheckBuilder[A, P, X])(
      implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
    validatorCheckBuilder.exists

  @implicitNotFound("Could not find a CheckMaterializer. This check might not be valid for AMQP.")
  implicit def findCheckBuilder2AmqpCheck[A, P, X](findCheckBuilder: FindCheckBuilder[A, P, X])(
      implicit materializer: CheckMaterializer[A, AmqpCheck, AmqpProtocolMessage, P]): AmqpCheck =
    findCheckBuilder.find.exists

  implicit def amqpXPathMaterializer(implicit xmlParsers: XmlParsers): AmqpXPathCheckMaterializer =
    new AmqpXPathCheckMaterializer(xmlParsers)

  implicit def amqpJsonPathMaterializer(implicit jsonParsers: JsonParsers): AmqpJsonPathCheckMaterializer =
    new AmqpJsonPathCheckMaterializer(jsonParsers)

  implicit def amqpBodyStringMaterializer: AmqpCheckMaterializer[BodyStringCheckType, String] =
    new CheckMaterializer[BodyStringCheckType, AmqpCheck, AmqpProtocolMessage, String](identity) {
      override protected def preparer: Preparer[AmqpProtocolMessage, String] = replyMessage => {
        val bodyCharset = Try(Charset.forName(replyMessage.amqpProperties.getContentEncoding))
          .getOrElse(Charset.defaultCharset())
        if (replyMessage.payload.length > 0) {
          new String(replyMessage.payload, bodyCharset).success
        } else "".success
      }
    }

  implicit def amqpBodyByteMaterializer: AmqpCheckMaterializer[BodyBytesCheckType, Array[Byte]] =
    new CheckMaterializer[BodyBytesCheckType, AmqpCheck, AmqpProtocolMessage, Array[Byte]](identity) {
      override protected def preparer: Preparer[AmqpProtocolMessage, Array[Byte]] = replyMessage => {
        if (replyMessage.payload.length > 0) {
          replyMessage.payload.success
        } else Array.emptyByteArray.success
      }
    }

  implicit val amqpStatusCheckMaterializer: AmqpCheckMaterializer[AmqpMessageCheckType, AmqpProtocolMessage] =
    new AmqpCheckMaterializer[AmqpMessageCheckType, AmqpProtocolMessage](identity) {
      override val preparer: Preparer[AmqpProtocolMessage, AmqpProtocolMessage] = _.success
    }

  implicit val amqpUntypedConditionalCheckWrapper: UntypedConditionalCheckWrapper[AmqpCheck] =
    (condition: Expression[Boolean], thenCheck: AmqpCheck) =>
      new Check[AmqpProtocolMessage] {
        private val typedCondition = (_: AmqpProtocolMessage, ses: Session) => condition(ses)

        override def check(response: AmqpProtocolMessage,
                           session: Session,
                           preparedCache: JMap[Any, Any]): Validation[CheckResult] =
          ConditionalCheck(typedCondition, thenCheck).check(response, session, preparedCache)
    }

  implicit val amqpTypedConditionalCheckWrapper: TypedConditionalCheckWrapper[AmqpProtocolMessage, AmqpCheck] =
    (condition: (AmqpProtocolMessage, Session) => Validation[Boolean], thenCheck: AmqpCheck) =>
      (response: AmqpProtocolMessage, session: Session, preparedCache: JMap[Any, Any]) =>
        ConditionalCheck(condition, thenCheck).check(response, session, preparedCache)
} 
Example 15
Source File: DefaultUdashSerialization.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.rpc.serialization

import com.avsystem.commons.meta.Fallback
import com.avsystem.commons.misc.ImplicitNotFound
import com.avsystem.commons.rpc.{AsRaw, AsReal}
import com.avsystem.commons.serialization.GenCodec
import com.avsystem.commons.serialization.json.{JsonStringInput, JsonStringOutput}
import io.udash.rpc.JsonStr

import scala.annotation.implicitNotFound

trait DefaultUdashSerialization {
  implicit def genCodecBasedAsReal[T: GenCodec]: Fallback[AsReal[JsonStr, T]] =
    Fallback(jsonStr => JsonStringInput.read[T](jsonStr.json))

  implicit def genCodecBasedAsRaw[T: GenCodec]: Fallback[AsRaw[JsonStr, T]] =
    Fallback(value => JsonStr(JsonStringOutput.write[T](value)))

  @implicitNotFound("#{forGenCodec}")
  implicit def asRealNotFound[T](
    implicit forGenCodec: ImplicitNotFound[GenCodec[T]]
  ): ImplicitNotFound[AsReal[JsonStr, T]] = ImplicitNotFound()

  @implicitNotFound("#{forGenCodec}")
  implicit def asRawNotFound[T](
    implicit forGenCodec: ImplicitNotFound[GenCodec[T]]
  ): ImplicitNotFound[AsRaw[JsonStr, T]] = ImplicitNotFound()
}
object DefaultUdashSerialization extends DefaultUdashSerialization 
Example 16
Source File: RestResponse.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest.raw

import com.avsystem.commons._
import com.avsystem.commons.misc.ImplicitNotFound
import com.avsystem.commons.rpc.{AsRaw, AsReal}

import scala.annotation.implicitNotFound
import scala.util.Failure

final case class RestResponse(code: Int, headers: IMapping[PlainValue], body: HttpBody) {
  def header(name: String, value: String): RestResponse =
    copy(headers = headers.append(name, PlainValue(value)))

  def isSuccess: Boolean =
    code >= 200 && code < 300
  def toHttpError: HttpErrorException =
    HttpErrorException(code, body.textualContentOpt.toOptArg)
  def ensureNonError: RestResponse =
    if (isSuccess) this else throw toHttpError
}

object RestResponse extends RestResponseLowPrio {
  def plain(status: Int, message: OptArg[String] = OptArg.Empty): RestResponse =
    RestResponse(status, IMapping.empty, HttpBody.plain(message))

  class LazyOps(private val resp: () => RestResponse) extends AnyVal {
    def recoverHttpError: RestResponse = try resp() catch {
      case e: HttpErrorException => e.toResponse
    }
  }
  implicit def lazyOps(resp: => RestResponse): LazyOps = new LazyOps(() => resp)

  implicit class AsyncOps(private val asyncResp: RawRest.Async[RestResponse]) extends AnyVal {
    def recoverHttpError: RawRest.Async[RestResponse] =
      callback => asyncResp {
        case Failure(e: HttpErrorException) => callback(Success(e.toResponse))
        case tr => callback(tr)
      }
  }

  implicit def effectFromAsyncResp[F[_], T](
    implicit asyncEff: RawRest.AsyncEffect[F], asResponse: AsReal[RestResponse, T]
  ): AsReal[RawRest.Async[RestResponse], Try[F[T]]] =
    async => Success(asyncEff.fromAsync(RawRest.mapAsync(async)(resp => asResponse.asReal(resp))))

  implicit def effectToAsyncResp[F[_], T](
    implicit asyncEff: RawRest.AsyncEffect[F], asResponse: AsRaw[RestResponse, T]
  ): AsRaw[RawRest.Async[RestResponse], Try[F[T]]] =
    _.fold(RawRest.failingAsync, ft => RawRest.mapAsync(asyncEff.toAsync(ft))(asResponse.asRaw)).recoverHttpError

  // following two implicits provide nice error messages when serialization is lacking for HTTP method result
  // while the async wrapper is fine (e.g. Future)

  @implicitNotFound("${F}[${T}] is not a valid result type because:\n#{forResponseType}")
  implicit def effAsyncAsRealNotFound[F[_], T](implicit
    fromAsync: RawRest.AsyncEffect[F],
    forResponseType: ImplicitNotFound[AsReal[RestResponse, T]]
  ): ImplicitNotFound[AsReal[RawRest.Async[RestResponse], Try[F[T]]]] = ImplicitNotFound()

  @implicitNotFound("${F}[${T}] is not a valid result type because:\n#{forResponseType}")
  implicit def effAsyncAsRawNotFound[F[_], T](implicit
    toAsync: RawRest.AsyncEffect[F],
    forResponseType: ImplicitNotFound[AsRaw[RestResponse, T]]
  ): ImplicitNotFound[AsRaw[RawRest.Async[RestResponse], Try[F[T]]]] = ImplicitNotFound()

  // following two implicits provide nice error messages when result type of HTTP method is totally wrong

  @implicitNotFound("#{forResponseType}")
  implicit def asyncAsRealNotFound[T](
    implicit forResponseType: ImplicitNotFound[HttpResponseType[T]]
  ): ImplicitNotFound[AsReal[RawRest.Async[RestResponse], Try[T]]] = ImplicitNotFound()

  @implicitNotFound("#{forResponseType}")
  implicit def asyncAsRawNotFound[T](
    implicit forResponseType: ImplicitNotFound[HttpResponseType[T]]
  ): ImplicitNotFound[AsRaw[RawRest.Async[RestResponse], Try[T]]] = ImplicitNotFound()
}
trait RestResponseLowPrio { this: RestResponse.type =>
  implicit def bodyBasedFromResponse[T](implicit bodyAsReal: AsReal[HttpBody, T]): AsReal[RestResponse, T] =
    resp => bodyAsReal.asReal(resp.ensureNonError.body)

  implicit def bodyBasedToResponse[T](implicit bodyAsRaw: AsRaw[HttpBody, T]): AsRaw[RestResponse, T] =
    value => bodyAsRaw.asRaw(value).defaultResponse.recoverHttpError

  // following two implicits forward implicit-not-found error messages for HttpBody as error messages for RestResponse

  @implicitNotFound("Cannot deserialize ${T} from RestResponse, because:\n#{forBody}")
  implicit def asRealNotFound[T](
    implicit forBody: ImplicitNotFound[AsReal[HttpBody, T]]
  ): ImplicitNotFound[AsReal[RestResponse, T]] = ImplicitNotFound()

  @implicitNotFound("Cannot serialize ${T} into RestResponse, because:\n#{forBody}")
  implicit def asRawNotFound[T](
    implicit forBody: ImplicitNotFound[AsRaw[HttpBody, T]]
  ): ImplicitNotFound[AsRaw[RestResponse, T]] = ImplicitNotFound()
} 
Example 17
Source File: CirceRestApiTest.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest

import com.avsystem.commons.meta.MacroInstances
import com.avsystem.commons.meta.MacroInstances.materializeWith
import com.avsystem.commons.misc.ImplicitNotFound
import com.avsystem.commons.rpc.{AsRaw, AsReal}
import io.circe._
import io.circe.parser._
import io.circe.syntax._
import io.udash.rest.raw.{JsonValue, PlainValue}

import scala.annotation.implicitNotFound
import scala.concurrent.Future

trait CirceRestImplicits extends FloatingPointRestImplicits {
  implicit def encoderBasedAsJson[T: Encoder]: AsRaw[JsonValue, T] =
    v => JsonValue(v.asJson.noSpaces)

  implicit def decoderBasedFromJson[T: Decoder]: AsReal[JsonValue, T] =
    json => parse(json.value).fold(throw _, _.as[T].fold(throw _, identity))

  implicit def keyEncoderBasedAsPlain[T: KeyEncoder]: AsRaw[PlainValue, T] =
    v => PlainValue(KeyEncoder[T].apply(v))

  implicit def keyDecoderBasedFromPlain[T: KeyDecoder]: AsReal[PlainValue, T] =
    pv => KeyDecoder[T].apply(pv.value)
      .getOrElse(throw new IllegalArgumentException(s"Invalid key: ${pv.value}"))

  @implicitNotFound("#{forEncoder}")
  implicit def asJsonNotFound[T](
    implicit forEncoder: ImplicitNotFound[Encoder[T]]
  ): ImplicitNotFound[AsRaw[JsonValue, T]] = ImplicitNotFound()

  @implicitNotFound("#{forDecoder}")
  implicit def fromJsonNotFound[T](
    implicit forDecoder: ImplicitNotFound[Decoder[T]]
  ): ImplicitNotFound[AsReal[JsonValue, T]] = ImplicitNotFound()

  @implicitNotFound("#{forKeyEncoder}")
  implicit def asPlainNotFound[T: KeyEncoder](
    implicit forKeyEncoder: ImplicitNotFound[KeyEncoder[T]]
  ): ImplicitNotFound[AsRaw[PlainValue, T]] = ImplicitNotFound()

  @implicitNotFound("#{forKeyDecoder}")
  implicit def fromPlainNotFound[T: KeyDecoder](
    implicit forKeyDecoder: ImplicitNotFound[KeyDecoder[T]]
  ): ImplicitNotFound[AsReal[PlainValue, T]] = ImplicitNotFound()
}
object CirceRestImplicits extends CirceRestImplicits

trait CirceInstances[T] {
  @materializeWith(io.circe.derivation.`package`, "deriveEncoder")
  def encoder: Encoder.AsObject[T]
  @materializeWith(io.circe.derivation.`package`, "deriveDecoder")
  def decoder: Decoder[T]
}

abstract class HasCirceCodec[T](
  implicit instances: MacroInstances[Unit, CirceInstances[T]]
) {
  implicit final lazy val objectEncoder: Encoder.AsObject[T] = instances((), this).encoder
  implicit final lazy val decoder: Decoder[T] = instances((), this).decoder
}

trait CirceCustomizedInstances[T] {
  @materializeWith(io.circe.derivation.`package`, "deriveEncoder")
  def encoder(nameTransform: String => String, discriminator: Option[String]): Encoder.AsObject[T]
  @materializeWith(io.circe.derivation.`package`, "deriveDecoder")
  def decoder(nameTransform: String => String, useDefaults: Boolean, discriminator: Option[String]): Decoder[T]
}

abstract class HasCirceCustomizedCodec[T](
  nameTransform: String => String,
  useDefaults: Boolean = true,
  discriminator: Option[String] = None
)(implicit instances: MacroInstances[Unit, CirceCustomizedInstances[T]]) {
  implicit final lazy val objectEncoder: Encoder.AsObject[T] = instances((), this).encoder(nameTransform, discriminator)
  implicit final lazy val decoder: Decoder[T] = instances((), this).decoder(nameTransform, useDefaults, discriminator)
}

case class CirceAddress(city: String, zip: String)
object CirceAddress extends HasCirceCustomizedCodec[CirceAddress](_.toUpperCase)

case class CircePerson(id: Long, name: String, address: Option[CirceAddress] = None)
object CircePerson extends HasCirceCodec[CircePerson]

abstract class CirceRestApiCompanion[T](
  implicit instances: MacroInstances[(CirceRestImplicits, FutureRestImplicits), FullInstances[T]]
) extends RestApiCompanion[(CirceRestImplicits, FutureRestImplicits), T]((CirceRestImplicits, FutureRestImplicits))

trait CirceRestApi {
  def createPerson(person: CircePerson): Future[String]
}
object CirceRestApi extends CirceRestApiCompanion[CirceRestApi] 
Example 18
Source File: MonixRestImplicits.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash
package rest.monix

import com.avsystem.commons._
import com.avsystem.commons.meta.MacroInstances
import com.avsystem.commons.misc.ImplicitNotFound
import io.udash.rest.raw.HttpResponseType
import io.udash.rest.raw.RawRest.{Async, AsyncEffect}
import io.udash.rest.{GenCodecRestImplicits, OpenApiFullInstances, RestOpenApiCompanion}
import monix.eval.Task
import monix.execution.Scheduler

import scala.annotation.implicitNotFound

trait MonixRestImplicits extends GenCodecRestImplicits {
  implicit def scheduler: Scheduler = Scheduler.global

  implicit def taskToAsync: AsyncEffect[Task] =
    new AsyncEffect[Task] {
      def toAsync[A](task: Task[A]): Async[A] =
        callback => task.runAsync(res => callback(res.fold(Failure(_), Success(_))))
      def fromAsync[A](async: Async[A]): Task[A] =
        Task.async(callback => async(res => callback(res.fold(Left(_), Right(_)))))
    }

  @implicitNotFound("${T} is not a valid HTTP method result type - it must be wrapped into a Task")
  implicit def httpResponseTypeNotFound[T]: ImplicitNotFound[HttpResponseType[T]] =
    ImplicitNotFound()
}
object MonixRestImplicits extends MonixRestImplicits

abstract class MonixRestApiCompanion[Real](
  implicit macroInstances: MacroInstances[MonixRestImplicits, OpenApiFullInstances[Real]]
) extends RestOpenApiCompanion[MonixRestImplicits, Real](MonixRestImplicits) 
Example 19
Source File: Blank.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.properties

import com.avsystem.commons.Opt
import com.avsystem.commons.misc.AbstractCase

import scala.annotation.implicitNotFound
import scala.collection.compat.{Factory => CFactory, _}

@implicitNotFound(
  "Class ${A} does not have a blank value. Please, specify the value of this property or add `implicit val blank: Blank[${A}] = ???` in ${A}'s companion object."
)
trait Blank[A] {
  def value: A
}

object Blank {
  def apply[A](implicit ev: Blank[A]): Blank[A] = ev

  final case class Simple[A](value: A) extends AbstractCase with Blank[A]
  final case class Factory[A](factory: () => A) extends AbstractCase with Blank[A] {
    override def value: A = factory()
  }

  implicit val Double: Blank[Double] = Simple(0.0)
  implicit val Float: Blank[Float] = Simple(0.0f)
  implicit val Long: Blank[Long] = Simple(0L)
  implicit val Int: Blank[Int] = Simple(0)
  implicit val Short: Blank[Short] = Simple(0)
  implicit val Byte: Blank[Byte] = Simple(0)
  implicit val Boolean: Blank[Boolean] = Simple(false)
  implicit val Unit: Blank[Unit] = Simple(())
  implicit val String: Blank[String] = Simple("")

  implicit def option[A]: Blank[Option[A]] = Simple(None)
  implicit def opt[A]: Blank[Opt[A]] = Simple(Opt.Empty)
  implicit def map[K, V]: Blank[Map[K, V]] = Simple(Map.empty)
  implicit def traversable[T, A[_] <: Iterable[_]](implicit fac: CFactory[T, A[T]]): Blank[A[T]] = Simple(Seq.empty[T].to(fac))
} 
Example 20
Source File: PropertyCreator.scala    From udash-core   with Apache License 2.0 5 votes vote down vote up
package io.udash.properties

import com.avsystem.commons._
import io.udash.properties.seq.DirectSeqPropertyImpl
import io.udash.properties.single.{CastableProperty, DirectPropertyImpl, ReadableProperty}

import scala.annotation.implicitNotFound
import scala.collection.compat.Factory

trait PropertyCreator[T] {
  def newProperty(parent: ReadableProperty[_])(implicit blank: Blank[T]): CastableProperty[T] =
    newProperty(blank.value, parent)

  def newProperty(value: T, parent: ReadableProperty[_]): CastableProperty[T] = {
    val prop = create(parent)
    prop.setInitValue(value)
    prop
  }

  def newImmutableProperty(value: T): ImmutableProperty[T]

  protected def create(parent: ReadableProperty[_]): CastableProperty[T]
}

object PropertyCreator extends PropertyCreatorImplicits {
  
  trait MacroGeneratedPropertyCreator

  def apply[T](implicit ev: PropertyCreator[T]): PropertyCreator[T] = ev

  implicit final val Double: PropertyCreator[Double] = new SinglePropertyCreator
  implicit final val Float: PropertyCreator[Float] = new SinglePropertyCreator
  implicit final val Long: PropertyCreator[Long] = new SinglePropertyCreator
  implicit final val Int: PropertyCreator[Int] = new SinglePropertyCreator
  implicit final val Short: PropertyCreator[Short] = new SinglePropertyCreator
  implicit final val Byte: PropertyCreator[Byte] = new SinglePropertyCreator
  implicit final val Char: PropertyCreator[Char] = new SinglePropertyCreator
  implicit final val Boolean: PropertyCreator[Boolean] = new SinglePropertyCreator
  implicit final val String: PropertyCreator[String] = new SinglePropertyCreator

  implicit final def materializeBSeq[T: PropertyCreator]: SeqPropertyCreator[T, BSeq] = new SeqPropertyCreator
  implicit final def materializeISeq[T: PropertyCreator]: SeqPropertyCreator[T, ISeq] = new SeqPropertyCreator
  implicit final def materializeVector[T: PropertyCreator]: SeqPropertyCreator[T, Vector] = new SeqPropertyCreator
  implicit final def materializeList[T: PropertyCreator]: SeqPropertyCreator[T, List] = new SeqPropertyCreator
}

final class SinglePropertyCreator[T] extends PropertyCreator[T] {
  protected def create(prt: ReadableProperty[_]): CastableProperty[T] =
    new DirectPropertyImpl[T](prt)

  override def newImmutableProperty(value: T): ImmutableProperty[T] = new ImmutableProperty[T](value)
}

final class SeqPropertyCreator[A: PropertyCreator, SeqTpe[T] <: BSeq[T]](implicit fac: Factory[A, SeqTpe[A]])
  extends PropertyCreator[SeqTpe[A]] {
  protected def create(parent: ReadableProperty[_]): CastableProperty[SeqTpe[A]] =
    new DirectSeqPropertyImpl[A, SeqTpe](parent).asInstanceOf[CastableProperty[SeqTpe[A]]]

  override def newImmutableProperty(value: SeqTpe[A]): ImmutableProperty[SeqTpe[A]] =
    new ImmutableSeqProperty[A, SeqTpe](value).asInstanceOf[ImmutableProperty[SeqTpe[A]]]
}

@implicitNotFound("Class ${T} cannot be used as ModelProperty template. Add `extends HasModelPropertyCreator[${T}]` to companion object of ${T}.")
abstract class ModelPropertyCreator[T] extends PropertyCreator[T] {
  override final def newImmutableProperty(value: T): ImmutableModelProperty[T] = new ImmutableModelProperty[T](value)
}

object ModelPropertyCreator {
  def apply[T](implicit ev: ModelPropertyCreator[T]): ModelPropertyCreator[T] = ev

  def materialize[T: IsModelPropertyTemplate]: ModelPropertyCreator[T] =
    macro io.udash.macros.PropertyMacros.reifyModelPropertyCreator[T]
} 
Example 21
Source File: Eql.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio.test

import scala.annotation.implicitNotFound


@implicitNotFound(
  "This operation assumes that values of types ${A} and ${B} could " +
    "potentially be equal. However, ${A} and ${B} are unrelated types, so " +
    "they cannot be equal."
)
sealed trait Eql[A, B]

object Eql {
  implicit final def eqlReflexive[A]: Eql[A, A]        = new Eql[A, A] {}
  implicit final def eqlSubtype1[A <: B, B]: Eql[A, B] = new Eql[A, B] {}
  implicit final def eqlSubtype2[A, B <: A]: Eql[A, B] = new Eql[A, B] {}
} 
Example 22
Source File: CanFail.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio

import scala.annotation.implicitNotFound


@implicitNotFound(
  "This error handling operation assumes your effect can fail. However, " +
    "your effect has Nothing for the error type, which means it cannot " +
    "fail, so there is no need to handle the failure. To find out which " +
    "method you can use instead of this operation, please see the " +
    "reference chart at: https://zio.dev/docs/can_fail"
)
sealed trait CanFail[-E]

object CanFail extends CanFail[Any] {

  implicit def canFail[E]: CanFail[E] = CanFail

  // Provide multiple ambiguous values so an implicit CanFail[Nothing] cannot be found.
  implicit val canFailAmbiguous1: CanFail[Nothing] = CanFail
  implicit val canFailAmbiguous2: CanFail[Nothing] = CanFail
} 
Example 23
Source File: CanFail.scala    From zio   with Apache License 2.0 5 votes vote down vote up
package zio

import scala.annotation.implicitNotFound
import scala.implicits.Not


@implicitNotFound(
  "This error handling operation assumes your effect can fail. However, " +
    "your effect has Nothing for the error type, which means it cannot " +
    "fail, so there is no need to handle the failure. To find out which " +
    "method you can use instead of this operation, please see the " +
    "reference chart at: https://zio.dev/docs/can_fail"
)
sealed trait CanFail[-E]

object CanFail extends CanFail[Any] {
  implicit def canFail[E](implicit ev: Not[E =:= Nothing]): CanFail[E] = CanFail
} 
Example 24
package org.scalaml.unsupervised.dl.restrictedBoltzmann

import org.scalaml.Predef._
import org.scalaml.Predef.Context._
import org.apache.commons.math3.linear.Array2DRowRealMatrix
import org.apache.commons.math3.linear.RealMatrix
import RBM._

import scala.annotation.implicitNotFound




  def apply(weights: Weights, v0: Array[Array[T]]): RealMatrix = {
      // Type conversion
    val cV0 = v0.map(_.map(implicitly[ToDouble[T]].apply(_)))
    val probSampler = new SCondProb(weights, nSamples)

      // Sample h0 = p(v0|h)
    val h0 = cV0.map( probSampler.sample(_, true) )
      // positive energy
    val posEnergy = multiplyTranspose(h0, cV0)

      // Sample v1 = p(h0| v)
    val v1 = h0.map( probSampler.sample(_, false))
      // Sample h1 = p(v1| h)
    val h1 = v1.map( probSampler.sample(_, true))
      // Negative energy
    val negEnergy = multiplyTranspose(v1, h1)
      // Normalized difference in energy
    posEnergy.subtract(negEnergy).scalarMultiply(v0.head.length)
  }


  private def multiplyTranspose(input1: DblMatrix, input2: DblMatrix): RealMatrix = {
    val realMatrix1 = new Array2DRowRealMatrix(input1)
    val realMatrix2 = new Array2DRowRealMatrix(input2)
    realMatrix1.transpose.multiply(realMatrix2)
  }
}


// ------------------------  EOF ---------------------------------------------- 
Example 25
Source File: objectkeys.scala    From picopickle   with MIT License 5 votes vote down vote up
package io.github.netvl.picopickle

import scala.annotation.implicitNotFound
import scala.{collection => coll}
import scala.collection.{mutable => mut, immutable => imm}

trait ObjectKeyTypesComponent {
  @implicitNotFound("Don't know how to write ${T} as a map key; make sure that an implicit `ObjectKeyWriter[${T}]` is in scope")
  trait ObjectKeyWriter[T] {
    def write(value: T): String
  }

  object ObjectKeyWriter {
    def apply[T](conv: T => String): ObjectKeyWriter[T] = new ObjectKeyWriter[T] {
      override def write(value: T): String = conv(value)
    }
  }

  @implicitNotFound("Don't know how to read ${T} as a map key; make sure that an implicit `ObjectKeyReader[${T}]` is in scope")
  trait ObjectKeyReader[T] {
    def read(value: String): T
  }

  object ObjectKeyReader {
    def apply[T](conv: String => T): ObjectKeyReader[T] = new ObjectKeyReader[T] {
      override def read(value: String): T = conv(value)
    }
  }

  type ObjectKeyReadWriter[T] = ObjectKeyReader[T] with ObjectKeyWriter[T]

  object ObjectKeyReadWriter {
    def apply[T](from: String => T): ObjectKeyReadWriter[T] = apply((t: T) => t.toString, from)

    def apply[T](to: T => String, from: String => T): ObjectKeyReadWriter[T] = new ObjectKeyReader[T] with ObjectKeyWriter[T] {
      override def write(value: T): String = to(value)
      override def read(value: String): T = from(value)
    }

    def apply[T](implicit r: ObjectKeyReader[T], w: ObjectKeyWriter[T]) = new ObjectKeyReader[T] with ObjectKeyWriter[T] {
      override def write(value: T): String = w.write(value)
      override def read(value: String): T = r.read(value)
    }
  }

}

trait ObjectKeyWritersComponent {
  this: ObjectKeyTypesComponent =>

  implicit val stringObjectKeyWriter: ObjectKeyWriter[String] = ObjectKeyWriter(identity)
}

trait ObjectKeyReadersComponent {
  this: ObjectKeyTypesComponent =>

  implicit val stringObjectKeyReader: ObjectKeyReader[String] = ObjectKeyReader(identity)
}

trait ObjectKeyReaderWritersComponent extends ObjectKeyReadersComponent with ObjectKeyWritersComponent {
  this: ObjectKeyTypesComponent =>
} 
Example 26
Source File: maps.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package shapeless.ops

import scala.annotation.implicitNotFound

import shapeless._
import labelled._

object maps {
  
  object FromMap {
    def apply[R <: HList](implicit fm: FromMap[R]) = fm

    implicit def hnilFromMap[T]: FromMap[HNil] =
      new FromMap[HNil] {
        def apply[K, V](m: Map[K, V]): Option[HNil] = Some(HNil)
      }


    implicit def hlistFromMap[K0, V0, T <: HList]
      (implicit wk: Witness.Aux[K0], tv: Typeable[V0], fmt: FromMap[T]): FromMap[FieldType[K0, V0] :: T] =
        new FromMap[FieldType[K0, V0] :: T] {
          def apply[K, V](m: Map[K, V]): Option[FieldType[K0, V0] :: T] = {
            for {
              value <- m.get(wk.value.asInstanceOf[K])
              typed <- tv.cast(value)
              rest <- fmt(m)
            } yield field[K0](typed) :: rest
          }
        }
  }
} 
Example 27
Source File: Hashing.scala    From perf_tester   with Apache License 2.0 5 votes vote down vote up
package scala
package util.hashing

import scala.annotation.implicitNotFound


@implicitNotFound(msg = "No implicit Hashing defined for ${T}.")
trait Hashing[T] extends Serializable {
  def hash(x: T): Int
}

object Hashing {
  final class Default[T] extends Hashing[T] {
    def hash(x: T) = x.##
  }

  implicit def default[T] = new Default[T]

  def fromFunction[T](f: T => Int) = new Hashing[T] {
    def hash(x: T) = f(x)
  }
} 
Example 28
Source File: AddableValues.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.types

import nl.rabobank.oss.rules.finance.core.Quantity

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class AddableValue available in scope for combination ${A} + ${B} = ${C}")
trait AddableValues[A, B, C] {
  def plus(a: A, b: B): C

  def leftUnit: A
  def rightUnit: B
}

object AddableValues {
  implicit def bigDecimalAddedToBigDecimal: AddableValues[BigDecimal, BigDecimal, BigDecimal] = new AddableValues[BigDecimal, BigDecimal, BigDecimal] {
    override def plus(a: BigDecimal, b: BigDecimal): BigDecimal = a + b
    override def leftUnit: BigDecimal = 0
    override def rightUnit: BigDecimal = 0
  }
  implicit def intAddedToInt: AddableValues[Int, Int, Int] = new AddableValues[Int, Int, Int] {
    override def plus(a: Int, b: Int): Int = a + b
    override def leftUnit: Int = 0
    override def rightUnit: Int = 0
  }
  implicit def quantityAddedToQuantity[N : Quantity]: AddableValues[N, N, N] = new AddableValues[N, N, N] {
    private val ev = implicitly[Quantity[N]]
    override def plus(a: N, b: N): N = ev.plus(a, b)
    override def leftUnit: N = ev.zero
    override def rightUnit: N = ev.zero
  }
} 
Example 29
Source File: SubtractableValues.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.types

import nl.rabobank.oss.rules.finance.core.Quantity

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class SubtractableValues available in scope for combination ${A} - ${B} = ${C}")
trait SubtractableValues[A, B, C] {
  def minus(a: A, b: B): C

  def leftUnit: A
  def rightUnit: B
}

object SubtractableValues {
  implicit def bigDecimalSubtractedByBigDecimal: SubtractableValues[BigDecimal, BigDecimal, BigDecimal] = new SubtractableValues[BigDecimal, BigDecimal, BigDecimal] {
    override def minus(a: BigDecimal, b: BigDecimal): BigDecimal = a - b
    override def leftUnit: BigDecimal = 0
    override def rightUnit: BigDecimal = 0
  }
  implicit def quantitySubtractedByQuantity[N : Quantity]: SubtractableValues[N, N, N] = new SubtractableValues[N, N, N] {
    private val ev = implicitly[Quantity[N]]
    override def minus(a: N, b: N): N = ev.minus(a, b)
    override def leftUnit: N = ev.zero
    override def rightUnit: N = ev.zero
  }
} 
Example 30
Source File: MultipliableValues.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.types

import nl.rabobank.oss.rules.finance.core.Quantity
import nl.rabobank.oss.rules.finance.nl._

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class MultipliableValues available in scope for combination ${A} * ${B} = ${C}")
trait MultipliableValues[A, B, C] {
  def multiply(a: A, b: B): C

  def leftUnit: A
  def rightUnit: B
}

object MultipliableValues {
  implicit def bigDecimalTimesBigDecimal: MultipliableValues[BigDecimal, BigDecimal, BigDecimal] = new MultipliableValues[BigDecimal, BigDecimal, BigDecimal] {
    override def multiply(a: BigDecimal, b: BigDecimal): BigDecimal = a * b
    override def leftUnit: BigDecimal = 0
    override def rightUnit: BigDecimal = 0
  }
  implicit def somethingTimesBigDecimal[N : Quantity]: MultipliableValues[N, BigDecimal, N] = new MultipliableValues[N, BigDecimal, N] {
    private val ev = implicitly[Quantity[N]]
    override def multiply(a: N, b: BigDecimal): N = ev.multiply(a, b)
    override def leftUnit: N = ev.zero
    override def rightUnit: BigDecimal = 0
  }
  implicit def bigDecimalTimesSomething[N : Quantity]: MultipliableValues[BigDecimal, N, N] = new MultipliableValues[BigDecimal, N, N] {
    private val ev = implicitly[Quantity[N]]
    override def multiply(a: BigDecimal, b: N): N = ev.multiply(b, a)
    override def leftUnit: BigDecimal = 0
    override def rightUnit: N = ev.zero
  }
  implicit def quantityTimesPercentage[N : Quantity]: MultipliableValues[N, Percentage, N] = new MultipliableValues[N, Percentage, N] {
    private val ev = implicitly[Quantity[N]]
    override def multiply(a: N, b: Percentage): N = b * a
    override def leftUnit: N = ev.zero
    override def rightUnit: Percentage = 0.procent
  }
  implicit def percentageTimesQuantity[N : Quantity]: MultipliableValues[Percentage, N, N] = new MultipliableValues[Percentage, N, N] {
    private val ev = implicitly[Quantity[N]]
    override def multiply(a: Percentage, b: N): N = a * b
    override def leftUnit: Percentage = 0.procent
    override def rightUnit: N = ev.zero
  }
  implicit def bedragTimesPeriode: MultipliableValues[Bedrag, Periode, Bedrag] = new MultipliableValues[Bedrag, Periode, Bedrag] {
    override def multiply(a: Bedrag, b: Periode): Bedrag = a * b.inMaanden
    override def leftUnit: Bedrag = 0.euro
    override def rightUnit: Periode = 0.maanden
  }
} 
Example 31
Source File: DivisibleValues.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.types

import nl.rabobank.oss.rules.finance.core.Quantity
import nl.rabobank.oss.rules.finance.nl._

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class DivisibleValues available in scope for combination ${A} / ${B} = ${C}")
trait DivisibleValues[A, B, C] {
  def divide(a: A, b: B): C

  def leftUnit: A
  def rightUnit: B
}

object DivisibleValues {
  implicit def bigDecimalDividedByBigDecimal: DivisibleValues[BigDecimal, BigDecimal, BigDecimal] = new DivisibleValues[BigDecimal, BigDecimal, BigDecimal] {
    override def divide(a: BigDecimal, b: BigDecimal): BigDecimal = a / b
    override def leftUnit: BigDecimal = 0
    override def rightUnit: BigDecimal = 1
  }

  implicit def somethingDividedByBigDecimal[N : Quantity]: DivisibleValues[N, BigDecimal, N] = new DivisibleValues[N, BigDecimal, N] {
    private val ev = implicitly[Quantity[N]]
    override def divide(a: N, b: BigDecimal): N = ev.divide(a, b)
    override def leftUnit: N = ev.zero
    override def rightUnit: BigDecimal = 1
  }

  implicit def somethingDividedByPercentage[N : Quantity]: DivisibleValues[N, Percentage, N] = new DivisibleValues[N, Percentage, N] {
    private val ev = implicitly[Quantity[N]]
    override def divide(a: N, b: Percentage): N = ev.divide(a, b.alsFractie)
    override def leftUnit: N = ev.zero
    override def rightUnit: Percentage = 100.procent
  }

  implicit def somethingDividedByInt[N : Quantity]: DivisibleValues[N, Int, N] = new DivisibleValues[N, Int, N] {
    // Currently BigDecimal gets wrapped in a NumberLike, which is why this will also work for BigDecimal.
    private val ev = implicitly[Quantity[N]]
    override def divide(a: N, b: Int): N = ev.divide(a, b)
    override def leftUnit: N = ev.zero
    override def rightUnit: Int = 1
  }

  implicit def percentageDividedByBigDecimal: DivisibleValues[Percentage, BigDecimal, BigDecimal] = new DivisibleValues[Percentage, BigDecimal, BigDecimal] {
    override def divide(a: Percentage, b: BigDecimal): BigDecimal = a / b
    override def leftUnit: Percentage = 0.procent
    override def rightUnit: BigDecimal = 1
  }

  implicit def somethingDividedBySomethingAsPercentage: DivisibleValues[Bedrag, Bedrag, Percentage] = new DivisibleValues[Bedrag, Bedrag, Percentage] {
    // Note: this type class instance was initially as Quantity x Quantity => Percentage, but the QuantityBigDecimal throws a fit if we do that
    // and makes it ambiguous to choose when trying to divide two BigDecimals
    //    private val ev = implicitly[Quantity[Bedrag]]
    override def divide(a: Bedrag, b: Bedrag): Percentage = (a.waarde / b.waarde * 100).procent
    override def leftUnit: Bedrag = 0.euro
    override def rightUnit: Bedrag = 1.euro
  }

  // Note: there is no somethingDividedByBedrag, because the division is not a commutative operation
  // and dividing a BigDecimal by something like a Bedrag would yield a BigDecimal Per Bedrag type, which
  // I do not yet foresee any use for.
} 
Example 32
Source File: Subtractable.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.operators

import nl.rabobank.oss.rules.dsl.core.types.SubtractableValues

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class Subtractable available in scope for combination ${A} - ${B} = ${C}")
trait Subtractable[A, B, C] extends BinaryOperable[A, B, C] {
  def operation(a: A, b: B): C

  def identityLeft: A
  def identityRight: B

  def representation: String = "-"
}

object Subtractable {
  implicit def valueSubtractedByValue[A, B, C](implicit ev: SubtractableValues[A, B, C]): Subtractable[A, B, C] = new Subtractable[A, B, C] {
    override def operation(n: A, m: B): C = ev.minus(n, m)
    override def identityLeft = ev.leftUnit
    override def identityRight = ev.rightUnit
  }
  implicit def listSubtractedByList[A, B, C](implicit ev: SubtractableValues[A, B, C]): Subtractable[List[A], List[B], List[C]] = new Subtractable[List[A], List[B], List[C]] {
    override def operation(n: List[A], m: List[B]): List[C] = n.zipAll(m, ev.leftUnit, ev.rightUnit).map(t => ev.minus(t._1, t._2))
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = List(ev.rightUnit)
  }
  implicit def listSubtractedByValue[A, B, C](implicit ev: SubtractableValues[A, B, C]): Subtractable[List[A], B, List[C]] = new Subtractable[List[A], B, List[C]] {
    override def operation(n: List[A], m: B): List[C] = n.map( ev.minus(_, m) )
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = ev.rightUnit
  }
  implicit def valueSubtractedByList[A, B, C](implicit ev: SubtractableValues[A, B, C]): Subtractable[A, List[B], List[C]] = new Subtractable[A, List[B], List[C]] {
    override def operation(n: A, m: List[B]): List[C] = m.map( ev.minus(n, _) )
    override def identityLeft = ev.leftUnit
    override def identityRight = List(ev.rightUnit)
  }
} 
Example 33
Source File: Divisible.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.operators

import nl.rabobank.oss.rules.dsl.core.types.DivisibleValues

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class Divisible available in scope for combination ${A} / ${B} = ${C}")
sealed trait Divisible[A, B, C] extends BinaryOperable[A, B, C] {
  def operation(a: A, b: B): C

  def identityLeft: A
  def identityRight: B

  def representation: String = "/"
}

object Divisible {
  implicit def valueDividedByValue[A, B, C](implicit ev: DivisibleValues[A, B, C]): Divisible[A, B, C] = new Divisible[A, B, C] {
    override def operation(n: A, m: B): C = ev.divide(n, m)
    override def identityLeft = ev.leftUnit
    override def identityRight = ev.rightUnit
  }
  implicit def listDividedByList[A, B, C](implicit ev: DivisibleValues[A, B, C]): Divisible[List[A], List[B], List[C]] = new Divisible[List[A], List[B], List[C]] {
    override def operation(n: List[A], m: List[B]): List[C] = n.zip(m).map(t => ev.divide(t._1, t._2))
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = List(ev.rightUnit)
  }
  implicit def listDividedByValue[A, B, C](implicit ev: DivisibleValues[A, B, C]): Divisible[List[A], B, List[C]] = new Divisible[List[A], B, List[C]] {
    override def operation(n: List[A], m: B): List[C] = n.map( ev.divide(_, m) )
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = ev.rightUnit
  }
  implicit def valueDividedByList[A, B, C](implicit ev: DivisibleValues[A, B, C]): Divisible[A, List[B], List[C]] = new Divisible[A, List[B], List[C]] {
    override def operation(n: A, m: List[B]): List[C] = m.map( ev.divide(n, _) )
    override def identityLeft = ev.leftUnit
    override def identityRight = List(ev.rightUnit)
  }
} 
Example 34
Source File: Addable.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.operators

import nl.rabobank.oss.rules.dsl.core.types.AddableValues

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class Addable available in scope for combination ${A} + ${B} = ${C}")
sealed trait Addable[A, B, C] extends BinaryOperable[A, B, C] {
  def operation(a: A, b: B): C

  def identityLeft: A
  def identityRight: B

  def representation: String = "+"
}

object Addable {
  implicit def valueAddedToValue[A, B, C](implicit ev: AddableValues[A, B, C]): Addable[A, B, C] = new Addable[A, B, C] {
    override def operation(n: A, m: B): C = ev.plus(n, m)
    override def identityLeft = ev.leftUnit
    override def identityRight = ev.rightUnit
  }
  implicit def listAddedToList[A, B, C](implicit ev: AddableValues[A, B, C]): Addable[List[A], List[B], List[C]] = new Addable[List[A], List[B], List[C]] {
    override def operation(n: List[A], m: List[B]): List[C] = n.zipAll(m, ev.leftUnit, ev.rightUnit).map(t => ev.plus(t._1, t._2))
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = List(ev.rightUnit)
  }
  implicit def listAddedToValue[A, B, C](implicit ev: AddableValues[A, B, C]): Addable[List[A], B, List[C]] = new Addable[List[A], B, List[C]] {
    override def operation(n: List[A], m: B): List[C] = n.map( ev.plus(_, m) )
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = ev.rightUnit
  }
  implicit def valueAddedToList[A, B, C](implicit ev: AddableValues[A, B, C]): Addable[A, List[B], List[C]] = new Addable[A, List[B], List[C]] {
    override def operation(n: A, m: List[B]): List[C] = m.map( ev.plus(n, _) )
    override def identityLeft = ev.leftUnit
    override def identityRight = List(ev.rightUnit)
  }
} 
Example 35
Source File: Multipliable.scala    From rule-engine   with MIT License 5 votes vote down vote up
package nl.rabobank.oss.rules.dsl.core.operators

import nl.rabobank.oss.rules.dsl.core.types.MultipliableValues

import scala.annotation.implicitNotFound


@implicitNotFound("No member of type class Multipliabe available in scope for combination ${A} * ${B} = ${C}")
sealed trait Multipliable[A, B, C] extends BinaryOperable[A, B, C] {
  def operation(a: A, b: B): C

  def identityLeft: A
  def identityRight: B

  def representation: String = "*"
}

object Multipliable {
  implicit def valueMultipliedByValue[A, B, C](implicit ev: MultipliableValues[A, B, C]): Multipliable[A, B, C] = new Multipliable[A, B, C] {
    override def operation(n: A, m: B): C = ev.multiply(n, m)
    override def identityLeft = ev.leftUnit
    override def identityRight = ev.rightUnit
  }
  implicit def listMultipliedByList[A, B, C](implicit ev: MultipliableValues[A, B, C]): Multipliable[List[A], List[B], List[C]] = new Multipliable[List[A], List[B], List[C]] {
    override def operation(n: List[A], m: List[B]): List[C] = n.zip(m).map(t => ev.multiply(t._1, t._2))
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = List(ev.rightUnit)
  }
  implicit def listMultipliedByValue[A, B, C](implicit ev: MultipliableValues[A, B, C]): Multipliable[List[A], B, List[C]] = new Multipliable[List[A], B, List[C]] {
    override def operation(n: List[A], m: B): List[C] = n.map( ev.multiply(_, m) )
    override def identityLeft = List(ev.leftUnit)
    override def identityRight = ev.rightUnit
  }
  implicit def valueMultipliedByList[A, B, C](implicit ev: MultipliableValues[A, B, C]): Multipliable[A, List[B], List[C]] = new Multipliable[A, List[B], List[C]] {
    override def operation(n: A, m: List[B]): List[C] = m.map( ev.multiply(n, _) )
    override def identityLeft = ev.leftUnit
    override def identityRight = List(ev.rightUnit)
  }

} 
Example 36
Source File: GraphQLInputTypeLookup.scala    From sangria   with Apache License 2.0 5 votes vote down vote up
package sangria.macros.derive

import sangria.marshalling.FromInput.{InputObjectResult, CoercedScalaResult}
import sangria.util.tag.@@

import language.higherKinds

import sangria.schema._

import scala.annotation.implicitNotFound

@implicitNotFound(msg = "Can't find suitable GraphQL input type for ${T}. If you have defined it already, please consider making it implicit and ensure that it's available in the scope.")
trait GraphQLInputTypeLookup[T, G] {
  def graphqlType: InputType[G]
}

object GraphQLInputTypeLookup extends GraphQLInputTypeLookupLowPrio {
  implicit def inCoercedLookup[T](implicit in: InputType[T @@ CoercedScalaResult]): GraphQLInputTypeLookup[T, T @@ CoercedScalaResult] = new GraphQLInputTypeLookup[T, T @@ CoercedScalaResult] {
    override val graphqlType: InputType[T @@ CoercedScalaResult] = in
  }

  implicit def inObjectLookup[T](implicit in: InputType[T @@ InputObjectResult]): GraphQLInputTypeLookup[T, T @@ InputObjectResult] = new GraphQLInputTypeLookup[T, T @@ InputObjectResult] {
    override val graphqlType: InputType[T @@ InputObjectResult] = in
  }

  implicit def optionLookup[T, G](implicit ev: GraphQLInputTypeLookup[T, G]): GraphQLInputTypeLookup[Option[T], Option[G]] = new GraphQLInputTypeLookup[Option[T], Option[G]] {
    override val graphqlType: OptionInputType[G] = OptionInputType(ev.graphqlType)
  }

  def finder[T] = new Finder[T]

  class Finder[T] {
    def apply[G]()(implicit ev: GraphQLInputTypeLookup[T, G]): GraphQLInputTypeLookup[T, G] = ev
  }
}

trait GraphQLInputTypeLookupLowPrio {
  implicit def inLookup[T](implicit in: InputType[T]): GraphQLInputTypeLookup[T, T] = new GraphQLInputTypeLookup[T, T] {
    override val graphqlType: InputType[T] = in
  }

  implicit def seqLookup[T, Coll[_] <: Seq[_], G](implicit ev: GraphQLInputTypeLookup[T, G]): GraphQLInputTypeLookup[Coll[T], Coll[G]] = new GraphQLInputTypeLookup[Coll[T], Coll[G]] {
    override val graphqlType: InputType[Coll[G]] = ListInputType(ev.graphqlType).asInstanceOf[InputType[Coll[G]]]
  }
} 
Example 37
Source File: GraphQLOutputTypeLookup.scala    From sangria   with Apache License 2.0 5 votes vote down vote up
package sangria.macros.derive

import language.higherKinds

import sangria.schema._

import scala.annotation.implicitNotFound

@implicitNotFound(msg = "Can't find suitable GraphQL output type for ${T}. If you have defined it already, please consider making it implicit and ensure that it's available in the scope.")
trait GraphQLOutputTypeLookup[T] {
  def graphqlType: OutputType[T]
}

object GraphQLOutputTypeLookup extends GraphQLOutputTypeLookupLowPrio {
  implicit def outLookup[T](implicit out: OutputType[T]): GraphQLOutputTypeLookup[T] = new GraphQLOutputTypeLookup[T] {
    override val graphqlType: OutputType[T] = out
  }

  implicit def optionLookup[T : GraphQLOutputTypeLookup]: GraphQLOutputTypeLookup[Option[T]] = new GraphQLOutputTypeLookup[Option[T]] {
    override val graphqlType: OptionType[T] = OptionType(implicitly[GraphQLOutputTypeLookup[T]].graphqlType)
  }
}

trait GraphQLOutputTypeLookupLowPrio {
  implicit def seqLookup[T : GraphQLOutputTypeLookup, Coll[_] <: Seq[_]]: GraphQLOutputTypeLookup[Coll[T]] = new GraphQLOutputTypeLookup[Coll[T]] {
    override val graphqlType: OutputType[Coll[T]] =
      ListType(implicitly[GraphQLOutputTypeLookup[T]].graphqlType).asInstanceOf[OutputType[Coll[T]]]
  }
} 
Example 38
Source File: HasId.scala    From sangria   with Apache License 2.0 5 votes vote down vote up
package sangria.execution.deferred

import scala.annotation.implicitNotFound

@implicitNotFound(msg = "Can't find suitable `HasId` type-class instance for type `${T}`. If you have defined it already, please consider defining an implicit instance `HasId[${T}]`.")
trait HasId[T, Id] {
  def id(value: T): Id
}

object HasId {
  private class SimpleHasId[T, Id](fn: T => Id) extends HasId[T, Id] {
    def id(value: T) = fn(value)
  }

  def apply[T, Id](fn: T => Id): HasId[T, Id] = new SimpleHasId[T, Id](fn)
} 
Example 39
Source File: Lattice.scala    From reactive-async   with BSD 2-Clause "Simplified" License 5 votes vote down vote up
package com.phaller.rasync
package lattice

import scala.annotation.implicitNotFound

trait PartialOrderingWithBottom[V] extends PartialOrdering[V] {
  
  def join(v1: V, v2: V): V

  override def lteq(v1: V, v2: V): Boolean = {
    join(v1, v2) == v2
  }

  override def gteq(v1: V, v2: V): Boolean = {
    join(v1, v2) == v1
  }
}

object Lattice {
  implicit def pair[T](implicit lattice: Lattice[T]): Lattice[(T, T)] = {
    new Lattice[(T, T)] {
      def join(v1: (T, T), v2: (T, T)): (T, T) =
        (lattice.join(v1._1, v2._1), lattice.join(v1._2, v2._2))
      val bottom: (T, T) =
        (lattice.bottom, lattice.bottom)
      override def lteq(v1: (T, T), v2: (T, T)): Boolean =
        lattice.lteq(v1._1, v2._1) && lattice.lteq(v1._2, v2._2)
      override def gteq(v1: (T, T), v2: (T, T)): Boolean =
        lattice.gteq(v1._1, v2._1) && lattice.gteq(v1._2, v2._2)
    }
  }
} 
Example 40
Source File: arguments.scala    From fs2-rabbit   with Apache License 2.0 5 votes vote down vote up
package dev.profunktor.fs2rabbit

import scala.annotation.implicitNotFound
import dev.profunktor.fs2rabbit.javaConversion._

object arguments {

  
  type SafeArg   = Evidence[SafeArgument]
  type Arguments = Map[String, SafeArg]

  implicit def argumentConversion(arguments: Arguments): java.util.Map[String, Object] =
    arguments.map { case (k, v) => k -> v.ev.toObject(v.value) }.asJava

  sealed trait Evidence[F[_]] {
    type A
    val value: A
    val ev: F[A]
  }

  final case class MkEvidence[F[_], A1](value: A1)(implicit val ev: F[A1]) extends Evidence[F] { type A = A1 }

  implicit def anySafeArg[F[_], A: F](a: A): Evidence[F] = MkEvidence(a)

  @implicitNotFound("Only types supported by the AMQP protocol are allowed. Custom classes are not supported.")
  sealed trait SafeArgument[A] {
    type JavaType >: Null <: AnyRef
    private[fs2rabbit] def toJavaType(a: A): JavaType
    private[fs2rabbit] def toObject(a: A): Object = toJavaType(a)
  }

  object SafeArgument {
    private[fs2rabbit] def apply[A](implicit ev: SafeArgument[A]): SafeArgument[A] = ev
    private[fs2rabbit] def instance[A, J >: Null <: AnyRef](f: A => J): SafeArgument[A] =
      new SafeArgument[A] {
        type JavaType = J
        def toJavaType(a: A) = f(a)
      }

    implicit val stringInstance: SafeArgument[String]         = instance(identity)
    implicit val bigDecimalInstance: SafeArgument[BigDecimal] = instance(_.bigDecimal)
    implicit val intInstance: SafeArgument[Int]               = instance(Int.box)
    implicit val longInstance: SafeArgument[Long]             = instance(Long.box)
    implicit val doubleInstance: SafeArgument[Double]         = instance(Double.box)
    implicit val floatInstance: SafeArgument[Float]           = instance(Float.box)
    implicit val shortInstance: SafeArgument[Short]           = instance(Short.box)
    implicit val booleanInstance: SafeArgument[Boolean]       = instance(Boolean.box)
    implicit val byteInstance: SafeArgument[Byte]             = instance(Byte.box)
    implicit val dateInstance: SafeArgument[java.util.Date]   = instance(identity)

    implicit def listInstance[A: SafeArgument]: SafeArgument[List[A]]                   = instance(_.asJava)
    implicit def mapInstance[K: SafeArgument, V: SafeArgument]: SafeArgument[Map[K, V]] = instance(_.asJava)
  }

} 
Example 41
Source File: Filterable.scala    From franklin   with Apache License 2.0 5 votes vote down vote up
package com.azavea.franklin.database

import doobie.Fragment

import scala.annotation.implicitNotFound


@implicitNotFound(
  "No instance of Filterable.scala[${Model}, ${T}] in scope, check imports and make sure one is defined"
)
final case class Filterable[-Model, T](toFilters: T => List[Option[Fragment]])

object Filterable {
  // when I called this apply, I wound up with surprising errors elsewhere about argument types
  // needing to be fully known. It was confusing, so I explicitly named the summoner method `summon`
  // and have chosen to deal with a tiny bit less syntactic sugar
  def summon[Model, T](implicit ev: Filterable[Model, T]) = ev
} 
Example 42
Source File: GenObjectCodec.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package serialization

import com.avsystem.commons.derivation.DeferredInstance

import scala.annotation.implicitNotFound


@implicitNotFound("No GenObjectCodec found for ${T}")
trait GenObjectCodec[T] extends GenCodec[T] {
  def readObject(input: ObjectInput): T
  def writeObject(output: ObjectOutput, value: T): Unit

  override def read(input: Input): T = {
    val oi = input.readObject()
    val res = readObject(oi)
    oi.skipRemaining()
    res
  }

  override def write(output: Output, value: T): Unit = {
    val oo = output.writeObject()
    writeObject(oo, value)
    oo.finish()
  }
}
object GenObjectCodec {
  def apply[T](implicit codec: GenObjectCodec[T]): GenObjectCodec[T] = codec

  def writeObject[T: GenObjectCodec](output: ObjectOutput, value: T): Unit =
    apply[T].writeObject(output, value)
  def readObject[T: GenObjectCodec](input: ObjectInput): T =
    apply[T].readObject(input)

  def materialize[T]: GenObjectCodec[T] = macro macros.serialization.GenCodecMacros.materialize[T]

  def fromApplyUnapplyProvider[T](applyUnapplyProvider: Any): GenObjectCodec[T] =
  macro macros.serialization.GenCodecMacros.fromApplyUnapplyProvider[T]

  def create[T](readFun: ObjectInput => T, writeFun: (ObjectOutput, T) => Any): GenObjectCodec[T] =
    new GenObjectCodec[T] {
      def readObject(input: ObjectInput): T = readFun(input)
      def writeObject(output: ObjectOutput, value: T): Unit = writeFun(output, value)
    }

  def makeLazy[T](codec: => GenObjectCodec[T]): GenObjectCodec[T] = new GenObjectCodec[T] {
    private lazy val underlying = codec
    def readObject(input: ObjectInput): T = underlying.readObject(input)
    def writeObject(output: ObjectOutput, value: T): Unit = underlying.writeObject(output, value)
  }

  def transformed[T, R: GenObjectCodec](toRaw: T => R, fromRaw: R => T): GenObjectCodec[T] =
    new Transformed[T, R](GenObjectCodec[R], toRaw, fromRaw)

  final class Transformed[A, B](val wrapped: GenObjectCodec[B], onWrite: A => B, onRead: B => A)
    extends GenObjectCodec[A] {

    def readObject(input: ObjectInput): A = onRead(wrapped.readObject(input))
    def writeObject(output: ObjectOutput, value: A): Unit = wrapped.writeObject(output, onWrite(value))
  }

  final class Deferred[T] extends DeferredInstance[GenObjectCodec[T]] with GenObjectCodec[T] {
    def readObject(input: ObjectInput): T = underlying.readObject(input)
    def writeObject(output: ObjectOutput, value: T): Unit = underlying.writeObject(output, value)
  }
} 
Example 43
Source File: MetadataCompanion.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package meta

import com.avsystem.commons.macros.misc.MiscMacros
import com.avsystem.commons.misc.ImplicitNotFound

import scala.annotation.implicitNotFound

trait MetadataCompanion[M[_]] {
  final def apply[Real](implicit metadata: M[Real]): M[Real] = metadata

  implicit final def fromFallback[Real](implicit fallback: Fallback[M[Real]]): M[Real] = fallback.value

  final class Lazy[Real](metadata: => M[Real]) {
    lazy val value: M[Real] = metadata
  }
  object Lazy {
    def apply[Real](metadata: => M[Real]): Lazy[Real] = new Lazy(metadata)

    // macro effectively turns `metadata` param into by-name param (implicit params by themselves cannot be by-name)
    implicit def lazyMetadata[Real](implicit metadata: M[Real]): Lazy[Real] = macro MiscMacros.lazyMetadata

    @implicitNotFound("#{forNotLazy}")
    implicit def notFound[T](implicit forNotLazy: ImplicitNotFound[M[T]]): ImplicitNotFound[Lazy[T]] =
      ImplicitNotFound()
  }
} 
Example 44
Source File: ApplierUnapplier.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package misc

import scala.annotation.implicitNotFound


@implicitNotFound("cannot materialize Unapplier: ${T} is not a case class or case class like type")
trait Unapplier[T] {
  def unapply(value: T): Seq[Any]
}
object Unapplier {
  implicit def materialize[T]: Unapplier[T] = macro macros.misc.MiscMacros.unapplier[T]
}

class ProductUnapplier[T <: Product] extends Unapplier[T] {
  def unapply(value: T): Seq[Any] = IArraySeq.unsafeWrapArray(value.productIterator.toArray)
}
abstract class ProductApplierUnapplier[T <: Product] extends ProductUnapplier[T] with ApplierUnapplier[T]

@implicitNotFound("cannot materialize ApplierUnapplier: ${T} is not a case class or case class like type")
trait ApplierUnapplier[T] extends Applier[T] with Unapplier[T]
object ApplierUnapplier {
  implicit def materialize[T]: ApplierUnapplier[T] = macro macros.misc.MiscMacros.applierUnapplier[T]
} 
Example 45
Source File: RedisRecordCodec.scala    From scala-commons   with MIT License 5 votes vote down vote up
package com.avsystem.commons
package redis

import com.avsystem.commons.redis.protocol.BulkStringMsg
import com.avsystem.commons.redis.util.SizedArraySeqFactory
import com.avsystem.commons.serialization.GenObjectCodec

import scala.annotation.implicitNotFound
import scala.collection.compat._
import scala.collection.mutable

@implicitNotFound("${T} has no RedisRecordCodec. It can be derived from GenObjectCodec which can be provided " +
  "by making your case class companion extend HasGenObjectCodec")
case class RedisRecordCodec[T](read: IndexedSeq[BulkStringMsg] => T, write: T => IndexedSeq[BulkStringMsg])
object RedisRecordCodec extends LowPriorityRedisRecordCodecs {
  def apply[T](implicit codec: RedisRecordCodec[T]): RedisRecordCodec[T] = codec

  implicit def forDataMap[M[X, Y] <: BMap[X, Y], F: RedisDataCodec, V: RedisDataCodec](
    implicit fac: Factory[(F, V), M[F, V]]
  ): RedisRecordCodec[M[F, V] with BMap[F, V]] =
    RedisRecordCodec(elems => record[F, V, M[F, V]](elems), map => bulks(map.iterator, map.size))

  implicit def forDataSeq[M[X] <: BSeq[X], F: RedisDataCodec, V: RedisDataCodec](
    implicit fac: Factory[(F, V), M[(F, V)]]
  ): RedisRecordCodec[M[(F, V)] with BSeq[(F, V)]] =
    RedisRecordCodec(elems => record[F, V, M[(F, V)]](elems), seq => bulks(seq.iterator, seq.size))

  private def record[F: RedisDataCodec, V: RedisDataCodec, To](
    elems: IndexedSeq[BulkStringMsg])(implicit fac: Factory[(F, V), To]
  ): To = {
    val b = fac.newBuilder
    b.sizeHint(elems.size)
    elems.iterator.pairs.foreach {
      case (BulkStringMsg(f), BulkStringMsg(v)) =>
        b += RedisDataCodec[F].read(f) -> RedisDataCodec[V].read(v)
    }
    b.result()
  }

  private def bulks[F: RedisDataCodec, V: RedisDataCodec](it: Iterator[(F, V)], size: Int): IndexedSeq[BulkStringMsg] =
    it.flatMap { case (f, v) => List(RedisDataCodec.write(f), RedisDataCodec.write(v)) }
      .map(BulkStringMsg).to(new SizedArraySeqFactory[BulkStringMsg](size))
}
sealed trait LowPriorityRedisRecordCodecs { this: RedisRecordCodec.type =>
  implicit def fromApplyUnapplyCodec[T](implicit codec: GenObjectCodec[T]): RedisRecordCodec[T] =
    RedisRecordCodec(
      elems => codec.readObject(new RedisRecordInput(elems)),
      value => {
        val buf = mutable.ArrayBuilder.make[BulkStringMsg]
        codec.writeObject(new RedisRecordOutput(buf), value)
        IArraySeq.unsafeWrapArray(buf.result())
      }
    )
} 
Example 46
Source File: CronUnit.scala    From cron4s   with Apache License 2.0 5 votes vote down vote up
package cron4s

import cron4s.base.Enumerated

import scala.annotation.implicitNotFound

import cats.{Eq, Show}


  def range: IndexedSeq[Int]
}

object CronUnit extends CronUnitInstances {
  @inline def apply[F <: CronField](implicit unit: CronUnit[F]): CronUnit[F] =
    unit

  final val All: List[CronUnit[_ <: CronField]] =
    List(Seconds, Minutes, Hours, DaysOfMonth, Months, DaysOfWeek)
}

private[cron4s] trait CronUnits {
  import CronField._

  // $COVERAGE-OFF$
  implicit def cronUnitEq[F <: CronField]: Eq[CronUnit[F]] =
    Eq.fromUniversalEquals[CronUnit[F]]

  implicit def cronUnitShow[F <: CronField]: Show[CronUnit[F]] =
    Show.fromToString[CronUnit[F]]
  // $COVERAGE-ON$

  private[cron4s] abstract class AbstractCronUnit[F <: CronField](
      val field: F,
      val min: Int,
      val max: Int
  ) extends CronUnit[F] {
    val range: IndexedSeq[Int] = min to max
  }

  implicit case object Seconds     extends AbstractCronUnit[Second](Second, 0, 59)
  implicit case object Minutes     extends AbstractCronUnit[Minute](Minute, 0, 59)
  implicit case object Hours       extends AbstractCronUnit[Hour](Hour, 0, 23)
  implicit case object DaysOfMonth extends AbstractCronUnit[DayOfMonth](DayOfMonth, 1, 31)
  implicit case object Months extends AbstractCronUnit[Month](Month, 1, 12) {
    val textValues = IndexedSeq(
      "jan",
      "feb",
      "mar",
      "apr",
      "may",
      "jun",
      "jul",
      "ago",
      "sep",
      "oct",
      "nov",
      "dec"
    )
  }
  implicit case object DaysOfWeek extends AbstractCronUnit[DayOfWeek](DayOfWeek, 0, 6) {
    val textValues = IndexedSeq("mon", "tue", "wed", "thu", "fri", "sat", "sun")
  }
}

private[cron4s] trait CronUnitInstances extends CronUnits {
  private[this] def enumerated[F <: CronField](unit: CronUnit[F]): Enumerated[CronUnit[F]] =
    new Enumerated[CronUnit[F]] {
      override def range(fL: CronUnit[F]): IndexedSeq[Int] = unit.range
    }

  implicit val secondsInstance     = enumerated(Seconds)
  implicit val minutesInstance     = enumerated(Minutes)
  implicit val hoursInstance       = enumerated(Hours)
  implicit val daysOfMonthInstance = enumerated(DaysOfMonth)
  implicit val monthsInstance      = enumerated(Months)
  implicit val daysOfWeekInstance  = enumerated(DaysOfWeek)
} 
Example 47
Source File: ServerHeaderExtractor.scala    From typedapi   with MIT License 5 votes vote down vote up
package typedapi.server

import typedapi.shared._
import shapeless._

import scala.annotation.implicitNotFound

@implicitNotFound("""Whoops, you should not be here. This seems to be a bug.

elements: ${El}""")
sealed trait ServerHeaderExtractor[El <: HList] {

  def apply(agg: Map[String, String]): Map[String, String]
}

sealed trait ServerHeaderExtractorLowPrio {

  implicit val serverHeaderReturnCase = new ServerHeaderExtractor[HNil] {
    def apply(agg: Map[String, String]): Map[String, String] = agg
  }

  implicit def serverHeaderIgnoreCase[H, T <: HList](implicit next: ServerHeaderExtractor[T]) = new ServerHeaderExtractor[H :: T] {
    def apply(agg: Map[String, String]): Map[String, String] = next(agg)
  }
}

object ServerHeaderExtractor extends ServerHeaderExtractorLowPrio {

  implicit def serverHeaderExtractCase[K, V, T <: HList]
      (implicit kWit: Witness.Aux[K], kShow: WitnessToString[K], vWit: Witness.Aux[V], vShow: WitnessToString[V], next: ServerHeaderExtractor[T]) = 
    new ServerHeaderExtractor[ServerHeaderSend[K, V] :: T] {
      def apply(agg: Map[String, String]): Map[String, String] = {
        val key   = kShow.show(kWit.value)
        val value = vShow.show(vWit.value)

        next(agg + (key -> value))
      }
    }
} 
Example 48
Source File: SmartProject.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ops

import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.{Keys, SelectAll, Values}
import shapeless.{HList, LabelledGeneric}

import scala.annotation.implicitNotFound

@implicitNotFound(msg = "Cannot prove that ${T} can be projected to ${U}. Perhaps not all member names and types of ${U} are the same in ${T}?")
case class SmartProject[T: TypedEncoder, U: TypedEncoder](apply: TypedDataset[T] => TypedDataset[U])

object SmartProject {
  
  implicit def deriveProduct[T: TypedEncoder, U: TypedEncoder, TRec <: HList, TProj <: HList, URec <: HList, UVals <: HList, UKeys <: HList]
    (implicit
      i0: LabelledGeneric.Aux[T, TRec],
      i1: LabelledGeneric.Aux[U, URec],
      i2: Keys.Aux[URec, UKeys],
      i3: SelectAll.Aux[TRec, UKeys, TProj],
      i4: Values.Aux[URec, UVals],
      i5: UVals =:= TProj,
      i6: ToTraversable.Aux[UKeys, Seq, Symbol]
    ): SmartProject[T,U] = SmartProject[T, U]({ from =>
      val names = implicitly[Keys.Aux[URec, UKeys]].apply.to[Seq].map(_.name).map(from.dataset.col)
      TypedDataset.create(from.dataset.toDF().select(names: _*).as[U](TypedExpressionEncoder[U]))
    })
} 
Example 49
Source File: UnaryInputsChecker.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package internals

import shapeless.ops.hlist.Length
import shapeless.{HList, LabelledGeneric, Nat, Witness}

import scala.annotation.implicitNotFound


@implicitNotFound(
  msg = "Cannot prove that ${Inputs} is a valid input type. Input type must have only one field of type ${Expected}"
)
trait UnaryInputsChecker[Inputs, Expected] {
  val inputCol: String
}

object UnaryInputsChecker {

  implicit def checkUnaryInputs[Inputs, Expected, InputsRec <: HList, InputK <: Symbol](
    implicit
    i0: LabelledGeneric.Aux[Inputs, InputsRec],
    i1: Length.Aux[InputsRec, Nat._1],
    i2: SelectorByValue.Aux[InputsRec, Expected, InputK],
    i3: Witness.Aux[InputK]
  ): UnaryInputsChecker[Inputs, Expected] = new UnaryInputsChecker[Inputs, Expected] {
    val inputCol: String = implicitly[Witness.Aux[InputK]].value.name
  }

} 
Example 50
Source File: LinearInputsChecker.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package internals

import org.apache.spark.ml.linalg._
import shapeless.ops.hlist.Length
import shapeless.{HList, LabelledGeneric, Nat, Witness}

import scala.annotation.implicitNotFound


@implicitNotFound(
  msg = "Cannot prove that ${Inputs} is a valid input type. " +
    "Input type must only contain a field of type Double (the label) and a field of type " +
    "org.apache.spark.ml.linalg.Vector (the features) and optional field of float type (weight)."
)
trait LinearInputsChecker[Inputs] {
  val featuresCol: String
  val labelCol: String
  val weightCol: Option[String]
}

object LinearInputsChecker {

  implicit def checkLinearInputs[
  Inputs,
  InputsRec <: HList,
  LabelK <: Symbol,
  FeaturesK <: Symbol](
    implicit
    i0: LabelledGeneric.Aux[Inputs, InputsRec],
    i1: Length.Aux[InputsRec, Nat._2],
    i2: SelectorByValue.Aux[InputsRec, Double, LabelK],
    i3: Witness.Aux[LabelK],
    i4: SelectorByValue.Aux[InputsRec, Vector, FeaturesK],
    i5: Witness.Aux[FeaturesK]
  ): LinearInputsChecker[Inputs] = {
    new LinearInputsChecker[Inputs] {
      val labelCol: String = implicitly[Witness.Aux[LabelK]].value.name
      val featuresCol: String = implicitly[Witness.Aux[FeaturesK]].value.name
      val weightCol: Option[String] = None
    }
  }

  implicit def checkLinearInputs2[
  Inputs,
  InputsRec <: HList,
  LabelK <: Symbol,
  FeaturesK <: Symbol,
  WeightK <: Symbol](
    implicit
    i0: LabelledGeneric.Aux[Inputs, InputsRec],
    i1: Length.Aux[InputsRec, Nat._3],
    i2: SelectorByValue.Aux[InputsRec, Vector, FeaturesK],
    i3: Witness.Aux[FeaturesK],
    i4: SelectorByValue.Aux[InputsRec, Double, LabelK],
    i5: Witness.Aux[LabelK],
    i6: SelectorByValue.Aux[InputsRec, Float, WeightK],
    i7: Witness.Aux[WeightK]
  ): LinearInputsChecker[Inputs] = {
    new LinearInputsChecker[Inputs] {
      val labelCol: String = implicitly[Witness.Aux[LabelK]].value.name
      val featuresCol: String = implicitly[Witness.Aux[FeaturesK]].value.name
      val weightCol: Option[String] = Some(implicitly[Witness.Aux[WeightK]].value.name)
    }
  }

} 
Example 51
Source File: VectorInputsChecker.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package internals

import shapeless.ops.hlist.Length
import shapeless.{HList, LabelledGeneric, Nat, Witness}

import scala.annotation.implicitNotFound
import org.apache.spark.ml.linalg.Vector


@implicitNotFound(
  msg = "Cannot prove that ${Inputs} is a valid input type. " +
    "Input type must only contain a field of type org.apache.spark.ml.linalg.Vector (the features)."
)
trait VectorInputsChecker[Inputs] {
  val featuresCol: String
}

object VectorInputsChecker {
  implicit def checkVectorInput[Inputs, InputsRec <: HList, FeaturesK <: Symbol](
    implicit
      i0: LabelledGeneric.Aux[Inputs, InputsRec],
      i1: Length.Aux[InputsRec, Nat._1],
      i2: SelectorByValue.Aux[InputsRec, Vector, FeaturesK],
      i3: Witness.Aux[FeaturesK]
    ): VectorInputsChecker[Inputs] = {
      new VectorInputsChecker[Inputs] {
        val featuresCol: String = i3.value.name
      }
    }
} 
Example 52
Source File: TreesInputsChecker.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package internals

import shapeless.ops.hlist.Length
import shapeless.{HList, LabelledGeneric, Nat, Witness}
import org.apache.spark.ml.linalg._

import scala.annotation.implicitNotFound


@implicitNotFound(
  msg = "Cannot prove that ${Inputs} is a valid input type. " +
    "Input type must only contain a field of type Double (the label) and a field of type " +
    "org.apache.spark.ml.linalg.Vector (the features)."
)
trait TreesInputsChecker[Inputs] {
  val featuresCol: String
  val labelCol: String
}

object TreesInputsChecker {

  implicit def checkTreesInputs[
  Inputs,
  InputsRec <: HList,
  LabelK <: Symbol,
  FeaturesK <: Symbol](
    implicit
    i0: LabelledGeneric.Aux[Inputs, InputsRec],
    i1: Length.Aux[InputsRec, Nat._2],
    i2: SelectorByValue.Aux[InputsRec, Double, LabelK],
    i3: Witness.Aux[LabelK],
    i4: SelectorByValue.Aux[InputsRec, Vector, FeaturesK],
    i5: Witness.Aux[FeaturesK]
  ): TreesInputsChecker[Inputs] = {
    new TreesInputsChecker[Inputs] {
      val labelCol: String = implicitly[Witness.Aux[LabelK]].value.name
      val featuresCol: String = implicitly[Witness.Aux[FeaturesK]].value.name
    }
  }

} 
Example 53
Source File: TypedVectorAssembler.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless
package ml
package feature

import org.apache.spark.ml.feature.VectorAssembler
import org.apache.spark.ml.linalg.Vector
import shapeless.{HList, HNil, LabelledGeneric}
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.{Keys, Values}
import shapeless._
import scala.annotation.implicitNotFound


final class TypedVectorAssembler[Inputs] private[ml](vectorAssembler: VectorAssembler, inputCols: Array[String])
  extends AppendTransformer[Inputs, TypedVectorAssembler.Output, VectorAssembler] {

  val transformer: VectorAssembler = vectorAssembler
    .setInputCols(inputCols)
    .setOutputCol(AppendTransformer.tempColumnName)

}

object TypedVectorAssembler {
  case class Output(vector: Vector)

  def apply[Inputs](implicit inputsChecker: TypedVectorAssemblerInputsChecker[Inputs]): TypedVectorAssembler[Inputs] = {
    new TypedVectorAssembler(new VectorAssembler(), inputsChecker.inputCols.toArray)
  }
}

@implicitNotFound(
  msg = "Cannot prove that ${Inputs} is a valid input type. Input type must only contain fields of numeric or boolean types."
)
private[ml] trait TypedVectorAssemblerInputsChecker[Inputs] {
  val inputCols: Seq[String]
}

private[ml] object TypedVectorAssemblerInputsChecker {
  implicit def checkInputs[Inputs, InputsRec <: HList, InputsKeys <: HList, InputsVals <: HList](
    implicit
    inputsGen: LabelledGeneric.Aux[Inputs, InputsRec],
    inputsKeys: Keys.Aux[InputsRec, InputsKeys],
    inputsKeysTraverse: ToTraversable.Aux[InputsKeys, Seq, Symbol],
    inputsValues: Values.Aux[InputsRec, InputsVals],
    inputsTypeCheck: TypedVectorAssemblerInputsValueChecker[InputsVals]
  ): TypedVectorAssemblerInputsChecker[Inputs] = new TypedVectorAssemblerInputsChecker[Inputs] {
    val inputCols: Seq[String] = inputsKeys.apply.to[Seq].map(_.name)
  }
}

private[ml] trait TypedVectorAssemblerInputsValueChecker[InputsVals]

private[ml] object TypedVectorAssemblerInputsValueChecker {
  implicit def hnilCheckInputsValue: TypedVectorAssemblerInputsValueChecker[HNil] =
    new TypedVectorAssemblerInputsValueChecker[HNil] {}

  implicit def hlistCheckInputsValueNumeric[H, T <: HList](
    implicit ch: CatalystNumeric[H],
    tt: TypedVectorAssemblerInputsValueChecker[T]
  ): TypedVectorAssemblerInputsValueChecker[H :: T] = new TypedVectorAssemblerInputsValueChecker[H :: T] {}

  implicit def hlistCheckInputsValueBoolean[T <: HList](
    implicit tt: TypedVectorAssemblerInputsValueChecker[T]
  ): TypedVectorAssemblerInputsValueChecker[Boolean :: T] = new TypedVectorAssemblerInputsValueChecker[Boolean :: T] {}
} 
Example 54
Source File: CatalystAverageable.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot compute average of type ${In}.")
trait CatalystAverageable[In, Out]

object CatalystAverageable {
  private[this] val theInstance = new CatalystAverageable[Any, Any] {}
  private[this] def of[In, Out]: CatalystAverageable[In, Out] = theInstance.asInstanceOf[CatalystAverageable[In, Out]]

  implicit val framelessAverageableBigDecimal: CatalystAverageable[BigDecimal, BigDecimal] = of[BigDecimal, BigDecimal]
  implicit val framelessAverageableDouble:     CatalystAverageable[Double, Double]         = of[Double, Double]
  implicit val framelessAverageableLong:       CatalystAverageable[Long, Double]           = of[Long, Double]
  implicit val framelessAverageableInt:        CatalystAverageable[Int, Double]            = of[Int, Double]
  implicit val framelessAverageableShort:      CatalystAverageable[Short, Double]          = of[Short, Double]
} 
Example 55
Source File: CatalystRound.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot compute round on type ${In}.")
trait CatalystRound[In, Out]

object CatalystRound {
  private[this] val theInstance = new CatalystRound[Any, Any] {}
  private[this] def of[In, Out]: CatalystRound[In, Out] = theInstance.asInstanceOf[CatalystRound[In, Out]]

  implicit val framelessBigDecimal: CatalystRound[BigDecimal, java.math.BigDecimal] = of[BigDecimal, java.math.BigDecimal]
  implicit val framelessDouble    : CatalystRound[Double, Long]                     = of[Double, Long]
  implicit val framelessInt       : CatalystRound[Int, Long]                        = of[Int, Long]
  implicit val framelessLong      : CatalystRound[Long, Long]                       = of[Long, Long]
  implicit val framelessShort     : CatalystRound[Short, Long]                      = of[Short, Long]
} 
Example 56
Source File: CatalystOrdered.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound
import shapeless.{Generic, HList, Lazy}
import shapeless.ops.hlist.LiftAll


@implicitNotFound("Cannot compare columns of type ${A}.")
trait CatalystOrdered[A]

object CatalystOrdered {
  private[this] val theInstance = new CatalystOrdered[Any] {}
  private[this] def of[A]: CatalystOrdered[A] = theInstance.asInstanceOf[CatalystOrdered[A]]

  implicit val framelessIntOrdered         : CatalystOrdered[Int]          = of[Int]
  implicit val framelessBooleanOrdered     : CatalystOrdered[Boolean]      = of[Boolean]
  implicit val framelessByteOrdered        : CatalystOrdered[Byte]         = of[Byte]
  implicit val framelessShortOrdered       : CatalystOrdered[Short]        = of[Short]
  implicit val framelessLongOrdered        : CatalystOrdered[Long]         = of[Long]
  implicit val framelessFloatOrdered       : CatalystOrdered[Float]        = of[Float]
  implicit val framelessDoubleOrdered      : CatalystOrdered[Double]       = of[Double]
  implicit val framelessBigDecimalOrdered  : CatalystOrdered[BigDecimal]   = of[BigDecimal]
  implicit val framelessSQLDateOrdered     : CatalystOrdered[SQLDate]      = of[SQLDate]
  implicit val framelessSQLTimestampOrdered: CatalystOrdered[SQLTimestamp] = of[SQLTimestamp]
  implicit val framelessStringOrdered      : CatalystOrdered[String]       = of[String]

  implicit def injectionOrdered[A, B]
    (implicit
      i0: Injection[A, B],
      i1: CatalystOrdered[B]
    ): CatalystOrdered[A] = of[A]

  implicit def deriveGeneric[G, H <: HList]
    (implicit
      i0: Generic.Aux[G, H],
      i1: Lazy[LiftAll[CatalystOrdered, H]]
    ): CatalystOrdered[G] = of[G]
} 
Example 57
Source File: CatalystPivotable.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound

@implicitNotFound("Cannot pivot on type ${A}. Currently supported types to pivot are {Int, Long, Boolean, and String}.")
trait CatalystPivotable[A]

object CatalystPivotable {
  private[this] val theInstance = new CatalystPivotable[Any] {}
  private[this] def of[A]: CatalystPivotable[A] = theInstance.asInstanceOf[CatalystPivotable[A]]

  implicit val framelessIntPivotable    : CatalystPivotable[Int]     = of[Int]
  implicit val framelessLongPivotable   : CatalystPivotable[Long]    = of[Long]
  implicit val framelessBooleanPivotable: CatalystPivotable[Boolean] = of[Boolean]
  implicit val framelessStringPivotable : CatalystPivotable[String]  = of[String]
} 
Example 58
Source File: CatalystIsin.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot do isin operation on columns of type ${A}.")
trait CatalystIsin[A]

object CatalystIsin {
  implicit object framelessBigDecimal extends CatalystIsin[BigDecimal]
  implicit object framelessByte       extends CatalystIsin[Byte]
  implicit object framelessDouble     extends CatalystIsin[Double]
  implicit object framelessFloat      extends CatalystIsin[Float]
  implicit object framelessInt        extends CatalystIsin[Int]
  implicit object framelessLong       extends CatalystIsin[Long]
  implicit object framelessShort      extends CatalystIsin[Short]
  implicit object framelesssString    extends CatalystIsin[String]
} 
Example 59
Source File: CatalystCollection.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound

@implicitNotFound("Cannot do collection operations on columns of type ${C}.")
trait CatalystCollection[C[_]]

object CatalystCollection {
  private[this] val theInstance = new CatalystCollection[Any] {}
  private[this] def of[A[_]]: CatalystCollection[A] = theInstance.asInstanceOf[CatalystCollection[A]]

  implicit val arrayObject : CatalystCollection[Array]  = of[Array]
  implicit val seqObject   : CatalystCollection[Seq]    = of[Seq]
  implicit val listObject  : CatalystCollection[List]   = of[List]
  implicit val vectorObject: CatalystCollection[Vector] = of[Vector]
} 
Example 60
Source File: CatalystSummable.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot compute sum of type ${In}.")
trait CatalystSummable[In, Out] {
  def zero: In
}

object CatalystSummable {
  def apply[In, Out](zero: In): CatalystSummable[In, Out] = {
    val _zero = zero
    new CatalystSummable[In, Out] { val zero: In = _zero }
  }

  implicit val framelessSummableLong      : CatalystSummable[Long, Long]             = CatalystSummable(zero = 0L)
  implicit val framelessSummableBigDecimal: CatalystSummable[BigDecimal, BigDecimal] = CatalystSummable(zero = BigDecimal(0))
  implicit val framelessSummableDouble    : CatalystSummable[Double, Double]         = CatalystSummable(zero = 0.0)
  implicit val framelessSummableInt       : CatalystSummable[Int, Long]              = CatalystSummable(zero = 0)
  implicit val framelessSummableShort     : CatalystSummable[Short, Long]            = CatalystSummable(zero = 0)
} 
Example 61
Source File: CatalystNumeric.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot do numeric operations on columns of type ${A}.")
trait CatalystNumeric[A]

object CatalystNumeric {
  private[this] val theInstance = new CatalystNumeric[Any] {}
  private[this] def of[A]: CatalystNumeric[A] = theInstance.asInstanceOf[CatalystNumeric[A]]

  implicit val framelessbigDecimalNumeric: CatalystNumeric[BigDecimal] = of[BigDecimal]
  implicit val framelessbyteNumeric      : CatalystNumeric[Byte]       = of[Byte]
  implicit val framelessdoubleNumeric    : CatalystNumeric[Double]     = of[Double]
  implicit val framelessintNumeric       : CatalystNumeric[Int]        = of[Int]
  implicit val framelesslongNumeric      : CatalystNumeric[Long]       = of[Long]
  implicit val framelessshortNumeric     : CatalystNumeric[Short]      = of[Short]
} 
Example 62
Source File: CatalystDivisible.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot compute division on type ${In}.")
trait CatalystDivisible[In, Out]

object CatalystDivisible {
  private[this] val theInstance = new CatalystDivisible[Any, Any] {}
  private[this] def of[In, Out]: CatalystDivisible[In, Out] = theInstance.asInstanceOf[CatalystDivisible[In, Out]]

  implicit val framelessDivisibleBigDecimal: CatalystDivisible[BigDecimal, BigDecimal] = of[BigDecimal, BigDecimal]
  implicit val framelessDivisibleDouble    : CatalystDivisible[Double, Double]         = of[Double, Double]
  implicit val framelessDivisibleInt       : CatalystDivisible[Int, Double]            = of[Int, Double]
  implicit val framelessDivisibleLong      : CatalystDivisible[Long, Double]           = of[Long, Double]
  implicit val framelessDivisibleByte      : CatalystDivisible[Byte, Double]           = of[Byte, Double]
  implicit val framelessDivisibleShort     : CatalystDivisible[Short, Double]          = of[Short, Double]
} 
Example 63
Source File: CatalystVariance.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound


@implicitNotFound("Cannot compute variance on type ${A}.")
trait CatalystVariance[A]

object CatalystVariance {
  private[this] val theInstance = new CatalystVariance[Any] {}
  private[this] def of[A]: CatalystVariance[A] = theInstance.asInstanceOf[CatalystVariance[A]]

  implicit val framelessIntVariance       : CatalystVariance[Int]        = of[Int]
  implicit val framelessLongVariance      : CatalystVariance[Long]       = of[Long]
  implicit val framelessShortVariance     : CatalystVariance[Short]      = of[Short]
  implicit val framelessBigDecimalVariance: CatalystVariance[BigDecimal] = of[BigDecimal]
  implicit val framelessDoubleVariance    : CatalystVariance[Double]     = of[Double]
} 
Example 64
Source File: CatalystNotNullable.scala    From frameless   with Apache License 2.0 5 votes vote down vote up
package frameless

import scala.annotation.implicitNotFound

@implicitNotFound("Cannot find evidence that type ${A} is nullable. Currently, only Option[A] is nullable.")
trait CatalystNullable[A]

object CatalystNullable {
  implicit def optionIsNullable[A]: CatalystNullable[Option[A]] = new CatalystNullable[Option[A]] {}
}

@implicitNotFound("Cannot find evidence that type ${A} is not nullable.")
trait NotCatalystNullable[A]

object NotCatalystNullable {
  implicit def everythingIsNotNullable[A]: NotCatalystNullable[A] = new NotCatalystNullable[A] {}
  implicit def nullableIsNotNotNullable[A: CatalystNullable]: NotCatalystNullable[A] = new NotCatalystNullable[A] {}
} 
Example 65
Source File: EnumerationEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding

import io.circe.{ Encoder, Json }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.FieldType

@implicitNotFound(
  """Could not find EnumerationEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationEncoder[A] extends Encoder[A]

object EnumerationEncoder {
  implicit val encodeEnumerationCNil: EnumerationEncoder[CNil] = new EnumerationEncoder[CNil] {
    def apply(a: CNil): Json = sys.error("Cannot encode CNil")
  }

  implicit def encodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    encodeR: EnumerationEncoder[R],
    config: Configuration = Configuration.default
  ): EnumerationEncoder[FieldType[K, V] :+: R] = new EnumerationEncoder[FieldType[K, V] :+: R] {
    def apply(a: FieldType[K, V] :+: R): Json = a match {
      case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name))
      case Inr(r) => encodeR(r)
    }
  }

  implicit def encodeEnumeration[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    encodeR: EnumerationEncoder[Repr]
  ): EnumerationEncoder[A] =
    new EnumerationEncoder[A] {
      def apply(a: A): Json = encodeR(gen.to(a))
    }
} 
Example 66
Source File: UnwrappedEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding

import io.circe.{ Encoder, Json }
import scala.annotation.implicitNotFound
import shapeless.{ ::, Generic, HNil, Lazy }

@implicitNotFound(
  """Could not find UnwrappedEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class UnwrappedEncoder[A] extends Encoder[A]

object UnwrappedEncoder {
  implicit def encodeUnwrapped[A, R](implicit
    gen: Lazy[Generic.Aux[A, R :: HNil]],
    encodeR: Encoder[R]
  ): UnwrappedEncoder[A] = new UnwrappedEncoder[A] {
    override def apply(a: A): Json =
      encodeR(gen.value.to(a).head)
  }
} 
Example 67
Source File: ReprAsObjectEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding
import io.circe.{ Encoder, Json, JsonObject }
import io.circe.generic.extras.ConfigurableDeriver
import scala.annotation.implicitNotFound
import scala.language.experimental.macros


@implicitNotFound(
  """Could not find ReprAsObjectEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
trait ReprAsObjectEncoder[A] extends Encoder.AsObject[A] {
  def configuredEncodeObject(a: A)(
    transformMemberNames: String => String,
    transformDiscriminator: String => String,
    discriminator: Option[String]
  ): JsonObject

  final protected[this] def addDiscriminator[B](
    encode: Encoder[B],
    value: B,
    name: String,
    discriminator: Option[String]
  ): JsonObject = discriminator match {
    case None => JsonObject.singleton(name, encode(value))
    case Some(disc) =>
      encode match {
        case oe: Encoder.AsObject[B] @unchecked => oe.encodeObject(value).add(disc, Json.fromString(name))
        case _                                  => JsonObject.singleton(name, encode(value))
      }
  }

  final def encodeObject(a: A): JsonObject = configuredEncodeObject(a)(Predef.identity, Predef.identity, None)
}

object ReprAsObjectEncoder {
  implicit def deriveReprAsObjectEncoder[R]: ReprAsObjectEncoder[R] =
    macro ConfigurableDeriver.deriveConfiguredEncoder[R]
} 
Example 68
Source File: ConfiguredAsObjectEncoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.encoding

import io.circe.JsonObject
import io.circe.generic.encoding.DerivedAsObjectEncoder
import io.circe.generic.extras.{ Configuration, JsonKey }
import java.util.concurrent.ConcurrentHashMap
import scala.annotation.implicitNotFound
import scala.collection.immutable.Map
import shapeless.{ Annotations, Coproduct, HList, LabelledGeneric, Lazy }
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.Keys

@implicitNotFound(
  """Could not find ConfiguredAsObjectEncoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ConfiguredAsObjectEncoder[A](config: Configuration) extends DerivedAsObjectEncoder[A] {
  private[this] val constructorNameCache: ConcurrentHashMap[String, String] =
    new ConcurrentHashMap[String, String]()

  protected[this] def constructorNameTransformer(value: String): String = {
    val current = constructorNameCache.get(value)

    if (current eq null) {
      val transformed = config.transformConstructorNames(value)
      constructorNameCache.put(value, transformed)
      transformed
    } else {
      current
    }
  }
}

object ConfiguredAsObjectEncoder {
  implicit def encodeCaseClass[A, R <: HList, F <: HList, K <: HList](implicit
    gen: LabelledGeneric.Aux[A, R],
    encode: Lazy[ReprAsObjectEncoder[R]],
    config: Configuration,
    fields: Keys.Aux[R, F],
    fieldsToList: ToTraversable.Aux[F, List, Symbol],
    keys: Annotations.Aux[JsonKey, A, K],
    keysToList: ToTraversable.Aux[K, List, Option[JsonKey]]
  ): ConfiguredAsObjectEncoder[A] = new ConfiguredAsObjectEncoder[A](config) {
    private[this] val keyAnnotations: List[Option[JsonKey]] = keysToList(keys())
    private[this] val hasKeyAnnotations: Boolean = keyAnnotations.exists(_.nonEmpty)

    private[this] val keyAnnotationMap: Map[String, String] =
      fieldsToList(fields())
        .map(_.name)
        .zip(keyAnnotations)
        .collect {
          case (field, Some(keyAnnotation)) => (field, keyAnnotation.value)
        }
        .toMap

    private[this] def memberNameTransformer(value: String): String =
      if (hasKeyAnnotations)
        keyAnnotationMap.getOrElse(value, config.transformMemberNames(value))
      else
        config.transformMemberNames(value)

    private[this] val transformedMemberCache: Map[String, String] = {
      fieldsToList(fields()).map(f => (f.name, memberNameTransformer(f.name))).toMap
    }

    private[this] def transformMemberName(value: String) =
      transformedMemberCache.getOrElse(value, value)

    final def encodeObject(a: A): JsonObject =
      encode.value.configuredEncodeObject(gen.to(a))(
        transformMemberName,
        constructorNameTransformer,
        None
      )
  }

  implicit def encodeAdt[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    encode: Lazy[ReprAsObjectEncoder[R]],
    config: Configuration
  ): ConfiguredAsObjectEncoder[A] = new ConfiguredAsObjectEncoder[A](config) {
    final def encodeObject(a: A): JsonObject =
      encode.value.configuredEncodeObject(gen.to(a))(
        Predef.identity,
        constructorNameTransformer,
        config.discriminator
      )
  }
} 
Example 69
Source File: ConfiguredAsObjectCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Decoder, Encoder, HCursor, JsonObject }
import io.circe.generic.codec.DerivedAsObjectCodec
import io.circe.generic.extras.{ Configuration, JsonKey }
import io.circe.generic.extras.decoding.ConfiguredDecoder
import io.circe.generic.extras.encoding.ConfiguredAsObjectEncoder
import io.circe.generic.extras.util.RecordToMap
import scala.annotation.implicitNotFound
import shapeless.{ Annotations, Coproduct, Default, HList, LabelledGeneric, Lazy }
import shapeless.ops.hlist.ToTraversable
import shapeless.ops.record.Keys

@implicitNotFound(
  """Could not find ConfiguredAsObjectCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ConfiguredAsObjectCodec[A] extends DerivedAsObjectCodec[A]

object ConfiguredAsObjectCodec {
  implicit def codecForCaseClass[A, R <: HList, D <: HList, F <: HList, K <: HList](implicit
    gen: LabelledGeneric.Aux[A, R],
    codec: Lazy[ReprAsObjectCodec[R]],
    defaults: Default.AsRecord.Aux[A, D],
    defaultMapper: RecordToMap[D],
    config: Configuration,
    fields: Keys.Aux[R, F],
    fieldsToList: ToTraversable.Aux[F, List, Symbol],
    keys: Annotations.Aux[JsonKey, A, K],
    keysToList: ToTraversable.Aux[K, List, Option[JsonKey]]
  ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] {
    private[this] val decodeA: Decoder[A] =
      ConfiguredDecoder.decodeCaseClass[A, R, D, F, K](
        gen,
        codec,
        defaults,
        defaultMapper,
        config,
        fields,
        fieldsToList,
        keys,
        keysToList
      )

    private[this] val encodeA: Encoder.AsObject[A] =
      ConfiguredAsObjectEncoder.encodeCaseClass[A, R, F, K](gen, codec, config, fields, fieldsToList, keys, keysToList)

    final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c)
    final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c)

    final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a)
  }

  implicit def codecForAdt[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    codec: Lazy[ReprAsObjectCodec[R]],
    config: Configuration
  ): ConfiguredAsObjectCodec[A] = new ConfiguredAsObjectCodec[A] {
    private[this] val decodeA: Decoder[A] =
      ConfiguredDecoder.decodeAdt[A, R](gen, codec, config)

    private[this] val encodeA: Encoder.AsObject[A] =
      ConfiguredAsObjectEncoder.encodeAdt[A, R](gen, codec, config)

    final def apply(c: HCursor): Decoder.Result[A] = decodeA.apply(c)
    final override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = decodeA.decodeAccumulating(c)

    final def encodeObject(a: A): JsonObject = encodeA.encodeObject(a)
  }
} 
Example 70
Source File: UnwrappedCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Codec, Decoder, Encoder, HCursor, Json }
import scala.annotation.implicitNotFound
import shapeless.{ ::, Generic, HNil, Lazy }

@implicitNotFound(
  """Could not find UnwrappedCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class UnwrappedCodec[A] extends Codec[A]

object UnwrappedCodec {
  implicit def codecForUnwrapped[A, R](implicit
    gen: Lazy[Generic.Aux[A, R :: HNil]],
    decodeR: Decoder[R],
    encodeR: Encoder[R]
  ): UnwrappedCodec[A] = new UnwrappedCodec[A] {

    override def apply(c: HCursor): Decoder.Result[A] =
      decodeR(c) match {
        case Right(unwrapped) => Right(gen.value.from(unwrapped :: HNil))
        case l @ Left(_)      => l.asInstanceOf[Decoder.Result[A]]
      }
    override def apply(a: A): Json =
      encodeR(gen.value.to(a).head)
  }
} 
Example 71
Source File: EnumerationCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import io.circe.{ Codec, Decoder, DecodingFailure, HCursor, Json }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationCodec[A] extends Codec[A]

object EnumerationCodec {
  implicit val codecForEnumerationCNil: EnumerationCodec[CNil] = new EnumerationCodec[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
    def apply(a: CNil): Json = sys.error("Cannot encode CNil")
  }

  implicit def codecForEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    codecForR: EnumerationCodec[R],
    config: Configuration = Configuration.default
  ): EnumerationCodec[FieldType[K, V] :+: R] = new EnumerationCodec[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          codecForR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
    def apply(a: FieldType[K, V] :+: R): Json = a match {
      case Inl(l) => Json.fromString(config.transformConstructorNames(witK.value.name))
      case Inr(r) => codecForR(r)
    }
  }

  implicit def codecForEnumeration[A, R <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, R],
    codecForR: EnumerationCodec[R]
  ): EnumerationCodec[A] =
    new EnumerationCodec[A] {
      def apply(c: HCursor): Decoder.Result[A] = codecForR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
      def apply(a: A): Json = codecForR(gen.to(a))
    }
} 
Example 72
Source File: ReprAsObjectCodec.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.codec

import cats.data.Validated
import io.circe.{ Decoder, DecodingFailure, HCursor, JsonObject }
import io.circe.generic.extras.ConfigurableDeriver
import io.circe.generic.extras.decoding.ReprDecoder
import io.circe.generic.extras.encoding.ReprAsObjectEncoder
import scala.annotation.implicitNotFound
import scala.collection.immutable.Map
import scala.language.experimental.macros
import shapeless.HNil


@implicitNotFound(
  """Could not find ReprAsObjectCodec for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class ReprAsObjectCodec[A] extends ReprDecoder[A] with ReprAsObjectEncoder[A]

object ReprAsObjectCodec {
  implicit def deriveReprAsObjectCodec[R]: ReprAsObjectCodec[R] = macro ConfigurableDeriver.deriveConfiguredCodec[R]

  val hnilReprCodec: ReprAsObjectCodec[HNil] = new ReprAsObjectCodec[HNil] {
    def configuredDecode(c: HCursor)(
      transformMemberNames: String => String,
      transformConstructorNames: String => String,
      defaults: Map[String, Any],
      discriminator: Option[String]
    ): Decoder.Result[HNil] =
      if (c.value.isObject) Right(HNil) else Left(DecodingFailure("HNil", c.history))

    def configuredDecodeAccumulating(c: HCursor)(
      transformMemberNames: String => String,
      transformConstructorNames: String => String,
      defaults: Map[String, Any],
      discriminator: Option[String]
    ): Decoder.AccumulatingResult[HNil] =
      if (c.value.isObject) Validated.valid(HNil) else Validated.invalidNel(DecodingFailure("HNil", c.history))

    def configuredEncodeObject(a: HNil)(
      transformMemberNames: String => String,
      transformDiscriminator: String => String,
      discriminator: Option[String]
    ): JsonObject = JsonObject.empty
  }
} 
Example 73
Source File: UnwrappedDecoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.decoding

import io.circe.{ Decoder, HCursor }
import scala.annotation.implicitNotFound
import shapeless.{ ::, Generic, HNil, Lazy }

@implicitNotFound(
  """Could not find UnwrappedDecoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class UnwrappedDecoder[A] extends Decoder[A]

object UnwrappedDecoder {
  implicit def decodeUnwrapped[A, R](implicit
    gen: Lazy[Generic.Aux[A, R :: HNil]],
    decodeR: Decoder[R]
  ): UnwrappedDecoder[A] = new UnwrappedDecoder[A] {
    override def apply(c: HCursor): Decoder.Result[A] =
      decodeR(c) match {
        case Right(unwrapped) => Right(gen.value.from(unwrapped :: HNil))
        case l @ Left(_)      => l.asInstanceOf[Decoder.Result[A]]
      }
  }
} 
Example 74
Source File: EnumerationDecoder.scala    From circe-generic-extras   with Apache License 2.0 5 votes vote down vote up
package io.circe.generic.extras.decoding

import io.circe.{ Decoder, DecodingFailure, HCursor }
import io.circe.generic.extras.Configuration
import scala.annotation.implicitNotFound
import shapeless.{ :+:, CNil, Coproduct, HNil, Inl, Inr, LabelledGeneric, Witness }
import shapeless.labelled.{ FieldType, field }

@implicitNotFound(
  """Could not find EnumerationDecoder for type ${A}.
Some possible causes for this:
- ${A} isn't a case class or sealed trat
- some of ${A}'s members don't have codecs of their own
- missing implicit Configuration"""
)
abstract class EnumerationDecoder[A] extends Decoder[A]

object EnumerationDecoder {
  implicit val decodeEnumerationCNil: EnumerationDecoder[CNil] = new EnumerationDecoder[CNil] {
    def apply(c: HCursor): Decoder.Result[CNil] = Left(DecodingFailure("Enumeration", c.history))
  }

  implicit def decodeEnumerationCCons[K <: Symbol, V, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    gen: LabelledGeneric.Aux[V, HNil],
    decodeR: EnumerationDecoder[R],
    config: Configuration = Configuration.default
  ): EnumerationDecoder[FieldType[K, V] :+: R] = new EnumerationDecoder[FieldType[K, V] :+: R] {
    def apply(c: HCursor): Decoder.Result[FieldType[K, V] :+: R] =
      c.as[String] match {
        case Right(s) if s == config.transformConstructorNames(witK.value.name) =>
          Right(Inl(field[K](gen.from(HNil))))
        case Right(_) =>
          decodeR.apply(c) match {
            case Right(v)  => Right(Inr(v))
            case Left(err) => Left(err)
          }
        case Left(err) => Left(DecodingFailure("Enumeration", c.history))
      }
  }

  implicit def decodeEnumeration[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    decodeR: EnumerationDecoder[Repr]
  ): EnumerationDecoder[A] =
    new EnumerationDecoder[A] {
      def apply(c: HCursor): Decoder.Result[A] = decodeR(c) match {
        case Right(v)  => Right(gen.from(v))
        case Left(err) => Left(err)
      }
    }
} 
Example 75
Source File: versionspecific.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived.util

import scala.annotation.implicitNotFound
import scala.util.hashing.MurmurHash3

object VersionSpecific {

  private[derived] def productSeed(x: Product): Int =
    MurmurHash3.mix(MurmurHash3.productSeed, x.productPrefix.hashCode)

  @implicitNotFound("could not find Lazy implicit value of type ${A}")
  abstract class Lazy[+A] extends Serializable {
    def value(): A
  }

  object Lazy {
    implicit def instance[A](implicit ev: => A): Lazy[A] = () => ev
  }

  sealed trait OrElse[+A, +B] extends Serializable {
    def fold[C](prim: A => C, sec: B => C): C
    def unify[C >: A](implicit ev: B <:< C): C = fold(identity, ev)
  }

  final class Primary[+A](value: A) extends OrElse[A, Nothing] {
    def fold[C](prim: A => C, sec: Nothing => C): C = prim(value)
  }

  final class Secondary[+B](value: => B) extends OrElse[Nothing, B] {
    def fold[C](prim: Nothing => C, sec: B => C): C = sec(value)
  }

  object OrElse extends OrElse0 {
    implicit def primary[A, B](implicit a: A): A OrElse B = new Primary(a)
  }

  private[util] abstract class OrElse0 {
    implicit def secondary[A, B](implicit b: => B): A OrElse B = new Secondary(b)
  }
} 
Example 76
Source File: eq.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.Eq
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Eq[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have an Eq instance
  * it is a sealed trait where all subclasses have an Eq instance""")
trait MkEq[A] extends Eq[A]

object MkEq extends MkEqDerivation {
  def apply[A](implicit ev: MkEq[A]): MkEq[A] = ev
}

private[derived] abstract class MkEqDerivation {
  implicit val mkEqHNil: MkEq[HNil] = instance((_, _) => true)
  implicit val mkEqCNil: MkEq[CNil] = instance((_, _) => true)

  implicit def mkEqHCons[H, T <: HList](implicit H: Eq[H] OrElse MkEq[H], T: MkEq[T]): MkEq[H :: T] =
    instance { case (hx :: tx, hy :: ty) => H.unify.eqv(hx, hy) && T.eqv(tx, ty) }

  implicit def mkEqCCons[L, R <: Coproduct](implicit L: Eq[L] OrElse MkEq[L], R: MkEq[R]): MkEq[L :+: R] =
    instance {
      case (Inl(lx), Inl(ly)) => L.unify.eqv(lx, ly)
      case (Inr(rx), Inr(ry)) => R.eqv(rx, ry)
      case _ => false
    }

  implicit def mkEqGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkEq[R]]): MkEq[A] =
    instance((x, y) => R.value.eqv(A.to(x), A.to(y)))

  private def instance[A](f: (A, A) => Boolean): MkEq[A] =
    new MkEq[A] {
      def eqv(x: A, y: A) = f(x, y)
    }
} 
Example 77
Source File: commutativeMonoid.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.kernel.CommutativeMonoid
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of CommutativeMonoid[A] where A = ${A}.
Make sure that A is a case class where all fields have a CommutativeMonoid instance.""")
trait MkCommutativeMonoid[A] extends CommutativeMonoid[A]

object MkCommutativeMonoid extends MkCommutativeMonoidDerivation {
  def apply[A](implicit ev: MkCommutativeMonoid[A]): MkCommutativeMonoid[A] = ev
}

private[derived] abstract class MkCommutativeMonoidDerivation {

  implicit val mkCommutativeMonoidHNil: MkCommutativeMonoid[HNil] =
    instance[HNil](HNil)((_, _) => HNil)

  implicit def mkCommutativeMonoidHCons[H, T <: HList](
    implicit H: CommutativeMonoid[H] OrElse MkCommutativeMonoid[H], T: MkCommutativeMonoid[T]
  ): MkCommutativeMonoid[H :: T] = instance(H.unify.empty :: T.empty) {
    case (hx :: tx, hy :: ty) => H.unify.combine(hx, hy) :: T.combine(tx, ty)
  }


  implicit def mkCommutativeMonoidGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkCommutativeMonoid[R]]): MkCommutativeMonoid[A] =
    new MkCommutativeMonoid[A] {
      // Cache empty case classes.
      lazy val empty = A.from(R.value.empty)
      def combine(x: A, y: A) = A.from(R.value.combine(A.to(x), A.to(y)))
    }

  private def instance[A](default: => A)(f: (A, A) => A): MkCommutativeMonoid[A] =
    new MkCommutativeMonoid[A] {
      def empty = default
      def combine(x: A, y: A) = f(x, y)
    }
} 
Example 78
Source File: monoidk.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.{Applicative, Monoid, MonoidK}
import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of MonoidK[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Monoid
  * it is a nested type λ[x => G[H[x]]] where G: MonoidK
  * it is a nested type λ[x => G[H[x]]] where G: Applicative and H: MonoidK
  * it is a generic case class where all fields have a MonoidK instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkMonoidK[F[_]] extends MonoidK[F]

object MkMonoidK extends MkMonoidKDerivation {
  def apply[F[_]](implicit F: MkMonoidK[F]): MkMonoidK[F] = F
}

private[derived] abstract class MkMonoidKDerivation extends MkMonoidKNestedOuter {

  implicit val mkMonoidKHNil: MkMonoidK[Const[HNil]#λ] =
    new MkMonoidK[Const[HNil]#λ] {
      def empty[A] = HNil
      def combineK[A](x: HNil, y: HNil) = HNil
    }

  implicit def mkMonoidKConst[T](implicit T: Monoid[T]): MkMonoidK[Const[T]#λ] =
    new MkMonoidK[Const[T]#λ] {
      def empty[A] = T.empty
      def combineK[A](x: T, y: T) = T.combine(x, y)
    }
}

private[derived] abstract class MkMonoidKNestedOuter extends MkMonoidKNestedInner {

  implicit def mkMonoidKNestedOuter[F[_]](implicit F: Split1[F, MonoidKOrMk, Trivial1]): MkMonoidK[F] =
    new MkMonoidK[F] {
      def empty[A] = F.pack(F.fo.unify.empty[F.I[A]])
      def combineK[A](x: F[A], y: F[A]) = F.pack(F.fo.unify.combineK(F.unpack(x), F.unpack(y)))
    }
}

private[derived] abstract class MkMonoidKNestedInner extends MkMonoidKGeneric {

  implicit def mkMonoidKNestedInner[F[_]](implicit F: Split1[F, Applicative, MonoidKOrMk]): MkMonoidK[F] =
    new MkMonoidK[F] {
      def empty[A] = F.pack(F.fo.pure(F.fi.unify.empty[A]))
      def combineK[A](x: F[A], y: F[A]) = F.pack(F.fo.map2(F.unpack(x), F.unpack(y))(F.fi.unify.combineK(_, _)))
    }
}

private[derived] abstract class MkMonoidKGeneric {
  protected type MonoidKOrMk[F[_]] = MonoidK[F] OrElse MkMonoidK[F]

  implicit def mkMonoidKHcons[F[_]](implicit F: IsHCons1[F, MonoidKOrMk, MkMonoidK]): MkMonoidK[F] =
    new MkMonoidK[F] {
      def empty[A] = F.pack(F.fh.unify.empty, F.ft.empty)

      def combineK[A](x: F[A], y: F[A]) = {
        val (fhx, ftx) = F.unpack(x)
        val (fhy, fty) = F.unpack(y)
        F.pack(F.fh.unify.combineK(fhx, fhy), F.ft.combineK(ftx, fty))
      }
  }

  implicit def mkMonoidKGeneric[F[_]](implicit F: Generic1[F, MkMonoidK]): MkMonoidK[F] =
    new MkMonoidK[F] {
      def empty[A] = F.from(F.fr.empty)
      def combineK[A](x: F[A], y: F[A]) = F.from(F.fr.combineK(F.to(x), F.to(y)))
    }
} 
Example 79
Source File: showPretty.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.Show
import shapeless._
import shapeless.labelled._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

trait ShowPretty[A] extends Show[A] {
  def showLines(a: A): List[String]
  def show(a: A): String = showLines(a).mkString(System.lineSeparator)
}

object ShowPretty {
  def apply[A: ShowPretty]: ShowPretty[A] = implicitly
}

@implicitNotFound("""Could not derive an instance of ShowPretty[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have a Show instance
  * it is a sealed trait where all subclasses have a Show instance""")
trait MkShowPretty[A] extends ShowPretty[A]

object MkShowPretty extends MkShowPrettyDerivation {
  def apply[A](implicit ev: MkShowPretty[A]): MkShowPretty[A] = ev
}

private[derived] abstract class MkShowPrettyDerivation extends MkShowPrettyGenericCoproduct {
  implicit val mkShowPrettyHNil: MkShowPretty[HNil] = instance(_ => Nil)
  implicit val mkShowPrettyCNil: MkShowPretty[CNil] = instance(_ => Nil)

  implicit def mkShowPrettyLabelledHCons[K <: Symbol, V, T <: HList](
    implicit K: Witness.Aux[K], V: Show[V] OrElse MkShowPretty[V], T: MkShowPretty[T]
  ): MkShowPretty[FieldType[K, V] :: T] = instance { case v :: t =>
    val name = K.value.name
    val valueLines = mkShowLines(V)(v)
    val middleLines = valueLines.drop(1)
    val tailLines = T.showLines(t)
    val middleEmpty = middleLines.isEmpty
    val tailEmpty = tailLines.isEmpty
    val value = valueLines.headOption.mkString
    val headLine = if (tailEmpty || !middleEmpty) s"$name = $value" else s"$name = $value,"

    if (tailEmpty) headLine :: middleLines
    else if (middleEmpty) headLine :: tailLines
    else headLine :: middleLines.init ::: s"${middleLines.last}," :: tailLines
  }

  implicit def mkShowPrettyCCons[L, R <: Coproduct](
    implicit L: Show[L] OrElse MkShowPretty[L], R: MkShowPretty[R]
  ): MkShowPretty[L :+: R] = instance {
    case Inl(l) => mkShowLines(L)(l)
    case Inr(r) => R.showLines(r)
  }

  implicit def mkShowPrettyGenericProduct[A, R <: HList](
    implicit A: LabelledGeneric.Aux[A, R], T: Typeable[A], R: Lazy[MkShowPretty[R]]
  ): MkShowPretty[A] = instance { a =>
    val name = T.describe.takeWhile(_ != '[')
    val lines = R.value.showLines(A.to(a)).map("  " + _)
    s"$name(" :: lines ::: ")" :: Nil
  }
}

private[derived] abstract class MkShowPrettyGenericCoproduct {

  protected def instance[A](f: A => List[String]): MkShowPretty[A] =
    new MkShowPretty[A] {
      def showLines(a: A) = f(a)
    }

  protected def mkShowLines[A](show: Show[A] OrElse MkShowPretty[A])(a: A): List[String] =
    show.fold({
      case pretty: ShowPretty[A] => pretty.showLines(a)
      case other => other.show(a).split(System.lineSeparator).toList
    }, _.showLines(a))

  implicit def mkShowPrettyGenericCoproduct[A, R <: Coproduct](
    implicit A: Generic.Aux[A, R], R: Lazy[MkShowPretty[R]]
  ): MkShowPretty[A] = instance(a => R.value.showLines(A.to(a)))
} 
Example 80
Source File: pure.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import alleycats.{Empty, Pure}
import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Pure[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Empty
  * it is a nested type λ[x => G[H[x]]] where G: Pure and H: Pure
  * it is a generic case class where all fields have a Pure instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkPure[F[_]] extends Pure[F]

object MkPure extends MkPureDerivation {
  def apply[F[_]](implicit F: MkPure[F]): MkPure[F] = F
}

private[derived] abstract class MkPureDerivation extends MkPureNested {

  implicit val mkPureHNil: MkPure[Const[HNil]#λ] =
    new MkPure[Const[HNil]#λ] {
      def pure[A](a: A) = HNil
    }

  implicit def mkPureConst[T](implicit T: Empty[T]): MkPure[Const[T]#λ] =
    new MkPure[Const[T]#λ] {
      def pure[A](a: A) = T.empty
    }
}

private[derived] abstract class MkPureNested extends MkPureCons {

  implicit def mkPureNested[F[_]](implicit F: Split1[F, PureOrMk, PureOrMk]): MkPure[F] =
    new MkPure[F] {
      def pure[A](a: A) = F.pack(F.fo.unify.pure(F.fi.unify.pure(a)))
    }
}

private[derived] abstract class MkPureCons extends MkPureGeneric {

  implicit def mkPureHCons[F[_]](implicit F: IsHCons1[F, PureOrMk, MkPure]): MkPure[F] =
    new MkPure[F] {
      def pure[A](a: A) = F.pack((F.fh.unify.pure(a), F.ft.pure(a)))
    }
}

private[derived] abstract class MkPureGeneric {
  protected type PureOrMk[F[_]] = Pure[F] OrElse MkPure[F]

  implicit def mkPureGeneric[F[_]](implicit F: Generic1[F, MkPure]): MkPure[F] =
    new MkPure[F] {
      def pure[A](a: A) = F.from(F.fr.pure(a))
    }
} 
Example 81
Source File: show.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import shapeless.labelled._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound


@implicitNotFound("""Could not derive an instance of Show[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have a Show instance
  * it is a sealed trait where all subclasses have a Show instance""")
trait MkShow[A] extends Show[A]

object MkShow extends MkShowDerivation {
  def apply[A](implicit ev: MkShow[A]): MkShow[A] = ev
}

private[derived] abstract class MkShowDerivation extends MkShowGenericCoproduct {
  implicit val mkShowHNil: MkShow[HNil] = instance(_ => "")
  implicit val mkShowCNil: MkShow[CNil] = instance(_ => "")

  implicit def mkShowLabelledHCons[K <: Symbol, V, T <: HList](
    implicit K: Witness.Aux[K], V: Show[V] OrElse MkShow[V], T: MkShow[T]
  ): MkShow[FieldType[K, V] :: T] = instance { case v :: t =>
    val name = K.value.name
    val value = V.unify.show(v)
    val tail = T.show(t)
    if (tail.isEmpty) s"$name = $value"
    else s"$name = $value, $tail"
  }

  implicit def mkShowCCons[L, R <: Coproduct](
    implicit L: Show[L] OrElse MkShow[L], R: MkShow[R]
  ): MkShow[L :+: R] = instance {
    case Inl(l) => L.unify.show(l)
    case Inr(r) => R.show(r)
  }

  implicit def mkShowGenericProduct[A, R <: HList](
    implicit A: LabelledGeneric.Aux[A, R], T: Typeable[A], R: Lazy[MkShow[R]]
  ): MkShow[A] = instance { a =>
    val name = T.describe.takeWhile(_ != '[')
    val fields = R.value.show(A.to(a))
    s"$name($fields)"
  }
}

private[derived] abstract class MkShowGenericCoproduct {

  implicit def mkShowGenericCoproduct[A, R <: Coproduct](
    implicit A: Generic.Aux[A, R], R: Lazy[MkShow[R]]
  ): MkShow[A] = instance(a => R.value.show(A.to(a)))

  protected def instance[A](f: A => String): MkShow[A] =
    new MkShow[A] {
      def show(value: A): String = f(value)
    }
} 
Example 82
Source File: semigroup.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.Semigroup
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Semigroup[A] where A = ${A}.
Make sure that A is a case class where all fields have a Semigroup instance.""")
trait MkSemigroup[A] extends Semigroup[A]

object MkSemigroup extends MkSemigroupDerivation {
  def apply[A](implicit ev: MkSemigroup[A]): MkSemigroup[A] = ev
}

private[derived] abstract class MkSemigroupDerivation {

  implicit val mkSemigroupHNil: MkSemigroup[HNil] =
    instance((_, _) => HNil)

  implicit def mkSemigroupHCons[H, T <: HList](
    implicit H: Semigroup[H] OrElse MkSemigroup[H], T: MkSemigroup[T]
  ): MkSemigroup[H :: T] = instance { case (hx :: tx, hy :: ty) =>
    H.unify.combine(hx, hy) :: T.combine(tx, ty)
  }

  implicit def mkSemigroupGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkSemigroup[R]]): MkSemigroup[A] =
    instance((x, y) => A.from(R.value.combine(A.to(x), A.to(y))))

  private def instance[A](f: (A, A) => A): MkSemigroup[A] =
    new MkSemigroup[A] {
      def combine(x: A, y: A) = f(x, y)
    }
} 
Example 83
Source File: order.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.Order
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Order[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have an Order instance
  * it is a sealed trait with exactly one subclass that has an Order instance""")
trait MkOrder[A] extends Order[A]

object MkOrder extends MkOrderDerivation {
  def apply[A](implicit ev: MkOrder[A]): MkOrder[A] = ev
}

private[derived] abstract class MkOrderDerivation {
  implicit val mkOrderHNil: MkOrder[HNil] = instance((_, _) => 0)
  implicit val mkOrderCNil: MkOrder[CNil] = instance((_, _) => 0)

  implicit def mkOrderHCons[H, T <: HList](
    implicit H: Order[H] OrElse MkOrder[H], T: MkOrder[T]
  ): MkOrder[H :: T] = instance { case (hx :: tx, hy :: ty) =>
    val cmpH = H.unify.compare(hx, hy)
    if (cmpH != 0) cmpH else T.compare(tx, ty)
  }

  implicit def mkOrderCCons[L](implicit L: Order[L] OrElse MkOrder[L]): MkOrder[L :+: CNil] =
    instance {
      case (Inl(lx), Inl(ly)) => L.unify.compare(lx, ly)
      case _ => 0
    }

  implicit def mkOrderGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkOrder[R]]): MkOrder[A] =
    instance((x, y) => R.value.compare(A.to(x), A.to(y)))

  private def instance[A](f: (A, A) => Int): MkOrder[A] =
    new MkOrder[A] {
      def compare(x: A, y: A) = f(x, y)
    }
} 
Example 84
Source File: partialOrder.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.PartialOrder
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of PartialOrder[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have a PartialOrder instance
  * it is a sealed trait where all subclasses have a PartialOrder instance""")
trait MkPartialOrder[A] extends PartialOrder[A]

object MkPartialOrder extends MkPartialOrderDerivation {
  def apply[A](implicit ev: MkPartialOrder[A]): MkPartialOrder[A] = ev
}

private[derived] abstract class MkPartialOrderDerivation {
  implicit val mkPartialOrderHNil: MkPartialOrder[HNil] = instance((_, _) => 0)
  implicit val mkPartialOrderCNil: MkPartialOrder[CNil] = instance((_, _) => 0)

  implicit def mkPartialOrderHcons[H, T <: HList](
    implicit H: PartialOrder[H] OrElse MkPartialOrder[H], T: MkPartialOrder[T]
  ): MkPartialOrder[H :: T] = instance { case (hx :: tx, hy :: ty) =>
    val cmpH = H.unify.partialCompare(hx, hy)
    if (cmpH != 0) cmpH else T.partialCompare(tx, ty)
  }

  implicit def mkPartialOrderCCons[L, R <: Coproduct](
    implicit L: PartialOrder[L] OrElse MkPartialOrder[L], R: MkPartialOrder[R]
  ): MkPartialOrder[L :+: R] = instance {
    case (Inl(lx), Inl(ly)) => L.unify.partialCompare(lx, ly)
    case (Inr(rx), Inr(ry)) => R.partialCompare(rx, ry)
    case _ => Double.NaN
  }

  implicit def mkPartialOrderGeneric[A, R](
    implicit A: Generic.Aux[A, R], R: Lazy[MkPartialOrder[R]]
  ): MkPartialOrder[A] = instance((x, y) => R.value.partialCompare(A.to(x), A.to(y)))

  private def instance[A](f: (A, A) => Double): MkPartialOrder[A] =
    new MkPartialOrder[A] {
      def partialCompare(x: A, y: A) = f(x, y)
    }
} 
Example 85
Source File: semigroupk.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.{Apply, Semigroup, SemigroupK}
import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of SemigroupK[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Semigroup
  * it is a nested type λ[x => G[H[x]]] where G: SemigroupK
  * it is a nested type λ[x => G[H[x]]] where G: Apply and H: SemigroupK
  * it is a generic case class where all fields have a SemigroupK instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkSemigroupK[F[_]] extends SemigroupK[F]

object MkSemigroupK extends MkSemigroupKDerivation {
  def apply[F[_]](implicit F: MkSemigroupK[F]): MkSemigroupK[F] = F
}

private[derived] abstract class MkSemigroupKDerivation extends MkSemigroupKNestedOuter {

  implicit val mkSemigroupKHNil: MkSemigroupK[Const[HNil]#λ] =
    new MkSemigroupK[Const[HNil]#λ] {
      def combineK[A](x: HNil, y: HNil) = HNil
    }

  implicit def mkSemigroupKConst[T](implicit T: Semigroup[T]): MkSemigroupK[Const[T]#λ] =
    new MkSemigroupK[Const[T]#λ] {
      def combineK[A](x: T, y: T) = T.combine(x, y)
    }
}

private[derived] abstract class MkSemigroupKNestedOuter extends MkSemigroupKNestedInner {

  implicit def mkSemigroupKNestedOuter[F[_]](implicit F: Split1[F, SemigroupKOrMk, Trivial1]): MkSemigroupK[F] =
    new MkSemigroupK[F] {

      def combineK[A](x: F[A], y: F[A]) =
        F.pack(F.fo.unify.combineK(F.unpack(x), F.unpack(y)))
    }
}

private[derived] abstract class  MkSemigroupKNestedInner extends MkSemigroupKGeneric {

  implicit def mkSemigroupKNestedInner[F[_]](implicit F: Split1[F, Apply, SemigroupKOrMk]): MkSemigroupK[F] =
    new MkSemigroupK[F] {

      def combineK[A](x: F[A], y: F[A]) =
        F.pack(F.fo.map2(F.unpack(x), F.unpack(y))(F.fi.unify.combineK(_, _)))
    }
}

private[derived] abstract class MkSemigroupKGeneric {
  protected type SemigroupKOrMk[F[_]] = SemigroupK[F] OrElse MkSemigroupK[F]

  implicit def mkSemigroupKHCons[F[_]](implicit F: IsHCons1[F, SemigroupKOrMk, MkSemigroupK]): MkSemigroupK[F] =
    new MkSemigroupK[F] {

      def combineK[A](x: F[A], y: F[A]) = {
        val (fhx, ftx) = F.unpack(x)
        val (fhy, fty) = F.unpack(y)
        F.pack(F.fh.unify.combineK(fhx, fhy), F.ft.combineK(ftx, fty))
      }
    }

  implicit def mkSemigroupKGeneric[F[_]](implicit F: Generic1[F, MkSemigroupK]): MkSemigroupK[F] =
    new MkSemigroupK[F] {

      def combineK[A](x: F[A], y: F[A]) =
        F.from(F.fr.combineK(F.to(x), F.to(y)))
    }
} 
Example 86
Source File: emptyk.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import alleycats.{Empty, EmptyK, Pure}
import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of EmptyK[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Empty
  * it is a nested type λ[x => G[H[x]]] where G: EmptyK
  * it is a nested type λ[x => G[H[x]]] where G: Pure and H: EmptyK
  * it is a generic case class where all fields have an EmptyK instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkEmptyK[F[_]] extends EmptyK[F]

object MkEmptyK extends MkEmptyKDerivation {
  def apply[F[_]](implicit F: MkEmptyK[F]): MkEmptyK[F] = F
}

private[derived] abstract class MkEmptyKDerivation extends MkEmptyKNestedOuter {

  implicit val mkEmptyKHNil: MkEmptyK[Const[HNil]#λ] =
    new MkEmptyK[Const[HNil]#λ] {
      def empty[A] = HNil
    }

  implicit def mkEmptyKConst[T](implicit T: Empty[T]): MkEmptyK[Const[T]#λ] =
    new MkEmptyK[Const[T]#λ] {
      def empty[A] = T.empty
    }
}

private[derived] abstract class MkEmptyKNestedOuter extends MkEmptyKNestedInner {

  implicit def mkEmptyKNestedOuter[F[_]](implicit F: Split1[F, EmptyKOrMk, Trivial1]): MkEmptyK[F] =
    new MkEmptyK[F] {
      def empty[A] = F.pack(F.fo.unify.empty)
    }
}

private[derived] abstract class MkEmptyKNestedInner extends MkEmptyKCons {

  implicit def mkEmptyKNestedInner[F[_]](implicit F: Split1[F, Pure, EmptyKOrMk]): MkEmptyK[F] =
    new MkEmptyK[F] {
      def empty[A] = F.pack(F.fo.pure(F.fi.unify.empty))
    }
}

private[derived] abstract class MkEmptyKCons extends MkEmptyKGeneric {

  implicit def mkEmptyKHCons[F[_]](implicit F: IsHCons1[F, EmptyKOrMk, MkEmptyK]): MkEmptyK[F] =
    new MkEmptyK[F] {
      def empty[A] = F.pack((F.fh.unify.empty, F.ft.empty))
    }
}

private[derived] abstract class MkEmptyKGeneric {
  protected type EmptyKOrMk[F[_]] = EmptyK[F] OrElse MkEmptyK[F]

  implicit def mkEmptyKGeneric[F[_]](implicit F: Generic1[F, MkEmptyK]): MkEmptyK[F] =
    new MkEmptyK[F] {
      def empty[A] = F.from(F.fr.empty)
    }
} 
Example 87
Source File: invariant.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Invariant[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T]
  * it is a nested type λ[x => G[H[x]]] where G: Invariant and H: Invariant
  * it is a generic case class where all fields have an Invariant instance
  * it is a generic sealed trait where all subclasses have an Invariant instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkInvariant[F[_]] extends Invariant[F] {
  def safeImap[A, B](fa: F[A])(g: A => Eval[B])(f: B => Eval[A]): Eval[F[B]]
  def imap[A, B](fa: F[A])(g: A => B)(f: B => A): F[B] =
    safeImap(fa)(a => Eval.later(g(a)))(b => Eval.later(f(b))).value
}
object MkInvariant extends MkInvariantDerivation {
  def apply[F[_]](implicit F: MkInvariant[F]): MkInvariant[F] = F
}
private[derived] abstract class MkInvariantDerivation extends MkInvariantNested {
  implicit val mkInvariantHNil: MkInvariant[Const[HNil]#λ] = mkInvariantConst
  implicit val mkInvariantCNil: MkInvariant[Const[CNil]#λ] = mkInvariantConst

  implicit def mkInvariantConst[T]: MkInvariant[Const[T]#λ] =
    new MkInvariant[Const[T]#λ] {
      def safeImap[A, B](t: T)(g: A => Eval[B])(f: B => Eval[A]): Eval[T] = Eval.now(t)
    }
}

private[derived] abstract class MkInvariantNested extends MkInvariantCons {
  implicit def mkFunctorInvariantNested[F[_]](implicit F: Split1[F, InvariantOrMk, InvariantOrMk]): MkInvariant[F] =
    new MkInvariant[F] {
      def safeImap[A, B](fa: F[A])(g: A => Eval[B])(f: B => Eval[A]): Eval[F[B]] =
        mkImapSafe[F.O, F.I[B], F.I[A]](F.fo)(F.unpack(fa))(
          mkImapSafe(F.fi)(_)(g)(f))(
          mkImapSafe(F.fi)(_)(f)(g)
        ).map(F.pack)
    }
}

private[derived] abstract class MkInvariantCons extends MkInvariantGeneric {
  implicit def mkInvariantHCons[F[_]](implicit F: IsHCons1[F, InvariantOrMk, MkInvariant]): MkInvariant[F] =
    new MkInvariant[F] {
      def safeImap[A, B](fa: F[A])(g: A => Eval[B])(f: B => Eval[A]): Eval[F[B]] =
        Eval.now(F.unpack(fa)).flatMap { case (fha, fta) =>
          for {
            fhb <- mkImapSafe(F.fh)(fha)(g)(f)
            ftb <- F.ft.safeImap(fta)(g)(f)
          } yield F.pack(fhb, ftb)
        }
    }

  implicit def mkInvariantCCons[F[_]](implicit F: IsCCons1[F, InvariantOrMk, MkInvariant]): MkInvariant[F] =
    new MkInvariant[F] {
      def safeImap[A, B](fa: F[A])(g: A => Eval[B])(f: B => Eval[A]): Eval[F[B]] = F.unpack(fa) match {
        case Left(fha) => mkImapSafe(F.fh)(fha)(g)(f).map(fhb => F.pack(Left(fhb)))
        case Right(fta) => F.ft.safeImap(fta)(g)(f).map(ftb => F.pack(Right(ftb)))
      }
    }
}
private[derived] abstract class MkInvariantGeneric {
  protected type InvariantOrMk[F[_]] = Invariant[F] OrElse MkInvariant[F]

  protected def mkImapSafe[F[_], A, B](F: InvariantOrMk[F])(fa: F[B])(g: B => Eval[A])(f: A => Eval[B]): Eval[F[A]] =
    F.unify match {
      case mk: MkInvariant[F] => mk.safeImap(fa)(g)(f)
      case p => Eval.later(p.imap(fa)(g(_).value)(f(_).value))
    }

  implicit def mkInvariantGeneric[F[_]](implicit F: Generic1[F, MkInvariant]): MkInvariant[F] =
    new MkInvariant[F] {
      def safeImap[A, B](fa: F[A])(g: A => Eval[B])(f: B => Eval[A]): Eval[F[B]] =
        F.fr.safeImap(F.to(fa))(g)(f).map(F.from[B])
    }
} 
Example 88
Source File: functor.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Functor[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T]
  * it is a nested type λ[x => G[H[x]]] where G: Functor and H: Functor
  * it is a nested type λ[x => G[H[x]]] where G: Contravariant and H: Contravariant
  * it is a generic case class where all fields have a Functor instance
  * it is a generic sealed trait where all subclasses have a Functor instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkFunctor[F[_]] extends Functor[F] {
  def safeMap[A, B](fa: F[A])(f: A => Eval[B]): Eval[F[B]]

  def map[A, B](fa: F[A])(f: A => B): F[B] =
    safeMap(fa)(a => Eval.later(f(a))).value
}

object MkFunctor extends MkFunctorDerivation {
  def apply[F[_]](implicit F: MkFunctor[F]): MkFunctor[F] = F
}

private[derived] abstract class MkFunctorDerivation extends MkFunctorNested {
  implicit val mkFunctorHNil: MkFunctor[Const[HNil]#λ] = mkFunctorConst
  implicit val mkFunctorCNil: MkFunctor[Const[CNil]#λ] = mkFunctorConst

  implicit def mkFunctorConst[T]: MkFunctor[Const[T]#λ] =
    new MkFunctor[Const[T]#λ] {
      def safeMap[A, B](t: T)(f: A => Eval[B]) = Eval.now(t)
    }
}

private[derived] abstract class MkFunctorNested extends MkFunctorNestedContra {

  implicit def mkFunctorNested[F[_]](implicit F: Split1[F, FunctorOrMk, FunctorOrMk]): MkFunctor[F] =
    new MkFunctor[F] {

      def safeMap[A, B](fa: F[A])(f: A => Eval[B]) =
        mkSafeMap(F.fo)(F.unpack(fa))(mkSafeMap(F.fi)(_)(f)).map(F.pack)
    }
}

private[derived] abstract class MkFunctorNestedContra extends MkFunctorCons {

  implicit def mkFunctorNestedContra[F[_]](implicit F: Split1[F, Contravariant, Contravariant]): MkFunctor[F] =
    new MkFunctor[F] {

      def safeMap[A, B](fa: F[A])(f: A => Eval[B]) =
        Eval.later(F.pack(F.fo.contramap(F.unpack(fa))(F.fi.contramap(_)(f(_).value))))
    }
}

private[derived] abstract class MkFunctorCons extends MkFunctorGeneric {

  implicit def mkFunctorHCons[F[_]](implicit F: IsHCons1[F, FunctorOrMk, MkFunctor]): MkFunctor[F] =
    new MkFunctor[F] {

      def safeMap[A, B](fa: F[A])(f: A => Eval[B]) =
        Eval.now(F.unpack(fa)).flatMap { case (fha, fta) =>
          for {
            fhb <- mkSafeMap(F.fh)(fha)(f)
            ftb <- F.ft.safeMap(fta)(f)
          } yield F.pack(fhb, ftb)
        }
    }

  implicit def mkFunctorCCons[F[_]](implicit F: IsCCons1[F, FunctorOrMk, MkFunctor]): MkFunctor[F] =
    new MkFunctor[F] {

      def safeMap[A, B](fa: F[A])(f: A => Eval[B]) = F.unpack(fa) match {
        case Left(fha) => mkSafeMap(F.fh)(fha)(f).map(fhb => F.pack(Left(fhb)))
        case Right(fta) => F.ft.safeMap(fta)(f).map(ftb => F.pack(Right(ftb)))
      }
    }
}

private[derived] abstract class MkFunctorGeneric {
  protected type FunctorOrMk[F[_]] = Functor[F] OrElse MkFunctor[F]

  protected def mkSafeMap[F[_], A, B](F: FunctorOrMk[F])(fa: F[A])(f: A => Eval[B]): Eval[F[B]] =
    F.unify match {
      case mk: MkFunctor[F] => mk.safeMap(fa)(f)
      case p => Eval.later(p.map(fa)(f(_).value))
    }

  implicit def mkFunctorGeneric[F[_]](implicit F: Generic1[F, MkFunctor]): MkFunctor[F] =
    new MkFunctor[F] {

      def safeMap[A, B](fa: F[A])(f: A => Eval[B]) =
        F.fr.safeMap(F.to(fa))(f).map(F.from)
    }
} 
Example 89
Source File: empty.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import alleycats.Empty
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Empty[A] where A = ${A}.
Make sure that A satisfies one of the following conditions:
  * it is a case class where all fields have an Empty instance
  * it is a sealed trait where exactly one subclass has an Empty instance""")
trait MkEmpty[A] extends Empty[A]

object MkEmpty extends MkEmptyDerivation {
  def apply[A](implicit ev: MkEmpty[A]): MkEmpty[A] = ev
}

private[derived] abstract class MkEmptyDerivation {
  protected type EmptyOrMk[A] = Empty[A] OrElse MkEmpty[A]

  implicit val mkEmptyHNil: MkEmpty[HNil] =
    instance(HNil)

  implicit def mkEmptyHCons[H, T <: HList](implicit H: EmptyOrMk[H], T: MkEmpty[T]): MkEmpty[H :: T] =
    instance(H.unify.empty :: T.empty)

  implicit def mkEmptyCoproduct[C <: Coproduct, E <: HList, A](
    implicit lift: util.LiftSome.Aux[EmptyOrMk, C, E],
    unique: E <:< (EmptyOrMk[A] :: HNil),
    inject: ops.coproduct.Inject[C, A]
  ): MkEmpty[C] = instance(inject(lift.instances.head.unify.empty))

  implicit def mkEmptyGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkEmpty[R]]): MkEmpty[A] =
    new MkEmpty[A] {
      // Cache empty case classes and sealed traits.
      lazy val empty = A.from(R.value.empty)
    }

  private def instance[A](default: A): MkEmpty[A] =
    new MkEmpty[A] {
      def empty = default
    }
} 
Example 90
Source File: apply.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Apply[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Semigroup
  * it is a nested type λ[x => G[H[x]]] where G: Apply and H: Apply
  * it is a generic case class where all fields have an Apply instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkApply[F[_]] extends Apply[F]

object MkApply extends MkApplyDerivation {
  def apply[F[_]](implicit F: MkApply[F]): MkApply[F] = F
}

private[derived] abstract class MkApplyDerivation extends MkApplyNested {

  implicit val mkApplyHNil: MkApply[Const[HNil]#λ] = new MkApply[Const[HNil]#λ] {
    def ap[A, B](ff: HNil)(fa: HNil) = ff
    def map[A, B](fa: HNil)(f: A => B) = fa
  }

  implicit def mkApplyConst[T](implicit T: Semigroup[T]): MkApply[Const[T]#λ] =
    new MkApply[Const[T]#λ] {
      def ap[A, B](ff: T)(fa: T) = T.combine(ff, fa)
      def map[A, B](fa: T)(f: A => B) = fa
    }
}

private[derived] abstract class MkApplyNested extends MkApplyGeneric {

  implicit def mkApplyNested[F[_]](implicit F: Split1[F, ApplyOrMk, ApplyOrMk]): MkApply[F] =
    new MkApply[F] {

      def ap[A, B](ff: F[A => B])(fa: F[A]) = {
        val fo = F.fo.unify
        F.pack(fo.ap(fo.map(F.unpack(ff))(fif => F.fi.unify.ap(fif)(_: F.I[A])))(F.unpack(fa)))
      }

      def map[A, B](fa: F[A])(f: A => B) =
        F.pack(F.fo.unify.map(F.unpack(fa))(F.fi.unify.map(_)(f)))
    }
}

private[derived] abstract class MkApplyGeneric {
  protected type ApplyOrMk[F[_]] = Apply[F] OrElse MkApply[F]

  implicit def mkApplyHCons[F[_]](implicit F: IsHCons1[F, ApplyOrMk, MkApply]): MkApply[F] =
    new MkApply[F] {

      def ap[A, B](ff: F[A => B])(fa: F[A]) = {
        val (fhf, ftf) = F.unpack(ff)
        val (fha, fta) = F.unpack(fa)
        F.pack(F.fh.unify.ap(fhf)(fha), F.ft.ap(ftf)(fta))
      }

      def map[A, B](fa: F[A])(f: A => B) = {
        val (fha, fta) = F.unpack(fa)
        F.pack(F.fh.unify.map(fha)(f), F.ft.map(fta)(f))
      }
    }

  implicit def mkApplyGeneric[F[_]](implicit F: Generic1[F, MkApply]): MkApply[F] =
    new MkApply[F] {
      def ap[A, B](ff: F[A => B])(fa: F[A]) = F.from(F.fr.ap(F.to(ff))(F.to(fa)))
      def map[A, B](fa: F[A])(f: A => B) = F.from(F.fr.map(F.to(fa))(f))
    }
} 
Example 91
Source File: applicative.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Applicative[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T] where T: Monoid
  * it is a nested type λ[x => G[H[x]]] where G: Applicative and H: Applicative
  * it is a generic case class where all fields have an Applicative instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkApplicative[F[_]] extends Applicative[F]

object MkApplicative extends MkApplicativeDerivation {
  def apply[F[_]](implicit F: MkApplicative[F]): MkApplicative[F] = F
}

private[derived] abstract class MkApplicativeDerivation extends MkApplicativeNested {

  implicit val mkApplicativeHNil: MkApplicative[Const[HNil]#λ] = new MkApplicative[Const[HNil]#λ] {
    def pure[A](x: A) = HNil
    def ap[A, B](ff: HNil)(fa: HNil) = ff
    override def map[A, B](fa: HNil)(f: A => B) = fa
  }

  implicit def mkApplicativeConst[T](implicit T: Monoid[T]): MkApplicative[Const[T]#λ] =
    new MkApplicative[Const[T]#λ] {
      def pure[A](x: A) = T.empty
      def ap[A, B](ff: T)(fa: T) = T.combine(ff, fa)
      override def map[A, B](fa: T)(f: A => B) = fa
    }
}

private[derived] abstract class MkApplicativeNested extends MkApplicativeGeneric {

  implicit def mkApplicativeNested[F[_]](implicit F: Split1[F, ApplicativeOrMk, ApplicativeOrMk]): MkApplicative[F] =
    new MkApplicative[F] {

      def pure[A](x: A) =
        F.pack(F.fo.unify.pure(F.fi.unify.pure(x)))

      def ap[A, B](ff: F[A => B])(fa: F[A]) = {
        val fo = F.fo.unify
        F.pack(fo.ap(fo.map(F.unpack(ff))(fif => F.fi.unify.ap(fif)(_: F.I[A])))(F.unpack(fa)))
      }

      override def map[A, B](fa: F[A])(f: A => B) =
        F.pack(F.fo.unify.map(F.unpack(fa))(F.fi.unify.map(_)(f)))
    }
}

private[derived] abstract class MkApplicativeGeneric {
  protected type ApplicativeOrMk[F[_]] = Applicative[F] OrElse MkApplicative[F]

  implicit def mkApplicativeHCons[F[_]](implicit F: IsHCons1[F, ApplicativeOrMk, MkApplicative]): MkApplicative[F] =
    new MkApplicative[F] {

      def pure[A](x: A) =
        F.pack(F.fh.unify.pure(x), F.ft.pure(x))

      def ap[A, B](ff: F[A => B])(fa: F[A]) = {
        val (fhf, ftf) = F.unpack(ff)
        val (fha, fta) = F.unpack(fa)
        F.pack(F.fh.unify.ap(fhf)(fha), F.ft.ap(ftf)(fta))
      }

      override def map[A, B](fa: F[A])(f: A => B) = {
        val (fha, fta) = F.unpack(fa)
        F.pack(F.fh.unify.map(fha)(f), F.ft.map(fta)(f))
      }
    }

  implicit def mkApplicativeGeneric[F[_]](implicit F: Generic1[F, MkApplicative]): MkApplicative[F] =
    new MkApplicative[F] {
      def pure[A](x: A) = F.from(F.fr.pure(x))
      def ap[A, B](ff: F[A => B])(fa: F[A]) = F.from(F.fr.ap(F.to(ff))(F.to(fa)))
      override def map[A, B](fa: F[A])(f: A => B) = F.from(F.fr.map(F.to(fa))(f))
    }
} 
Example 92
Source File: commutativeSemigroup.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.kernel.CommutativeSemigroup
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of CommutativeSemigroup[A] where A = ${A}.
Make sure that A is a case class where all fields have a CommutativeSemigroup instance.""")
trait MkCommutativeSemigroup[A] extends CommutativeSemigroup[A]

object MkCommutativeSemigroup extends MkCommutativeSemigroupDerivation {
  def apply[A](implicit ev: MkCommutativeSemigroup[A]): MkCommutativeSemigroup[A] = ev
}

private[derived] abstract class MkCommutativeSemigroupDerivation {

  implicit val mkCommutativeSemigroupHNil: MkCommutativeSemigroup[HNil] =
    instance((_, _) => HNil)

  implicit def mkCommutativeSemigroupHCons[H, T <: HList](
    implicit H: CommutativeSemigroup[H] OrElse MkCommutativeSemigroup[H], T: MkCommutativeSemigroup[T]
  ): MkCommutativeSemigroup[H :: T] = instance { case (hx :: tx, hy :: ty) =>
    H.unify.combine(hx, hy) :: T.combine(tx, ty)
  }

  implicit def mkCommutativeSemigroupGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkCommutativeSemigroup[R]]): MkCommutativeSemigroup[A] =
    instance((x, y) => A.from(R.value.combine(A.to(x), A.to(y))))

  private def instance[A](f: (A, A) => A): MkCommutativeSemigroup[A] =
    new MkCommutativeSemigroup[A] {
      def combine(x: A, y: A) = f(x, y)
    }
} 
Example 93
Source File: consk.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import alleycats.ConsK
import shapeless._

import scala.annotation.implicitNotFound

@implicitNotFound("Could not derive an instance of ConsK[${F}]")
trait MkConsK[F[_], G[_]] extends Serializable {
  def cons[A](head: A, tail: G[A]): F[A]
}

object MkConsK extends MkConsKDerivation {
  def apply[F[_], G[_]](implicit ev: MkConsK[F, G]): MkConsK[F, G] = ev

  def consK[F[_]](implicit F: MkConsK[F, F]): ConsK[F] =
    new ConsK[F] {
      def cons[A](head: A, tail: F[A]) = F.cons(head, tail)
    }
}

private[derived] abstract class MkConsKDerivation extends MkConsKRight {

  implicit def mkConsKHConsLeft[G[_]]: MkConsK[λ[t => t :: G[t] :: HNil], G] =
    new MkConsK[λ[t => t :: G[t] :: HNil], G] {
      def cons[A](head: A, tail: G[A]) = head :: tail :: HNil
    }

  implicit def mkConsKCConsLeft[F[_], G[_]](implicit F: IsCCons1[F, MkConsK[*[_], G], Trivial1]): MkConsK[F, G] =
      new MkConsK[F, G] {
        def cons[A](head: A, tail: G[A]) = F.pack(Left(F.fh.cons(head, tail)))
      }
}

private[derived] abstract class MkConsKRight extends MkConsKGeneric {

  implicit def mkConsKHConsRight[G[_]]: MkConsK[λ[t => G[t] :: t :: HNil], G] =
    new MkConsK[λ[t => G[t] :: t :: HNil], G] {
      def cons[A](head: A, tail: G[A]) = tail :: head :: HNil
    }

  implicit def mkConsKCConsRight[F[_], G[_]](implicit F: IsCCons1[F, Trivial1, MkConsK[*[_], G]]): MkConsK[F, G] =
    new MkConsK[F, G] {
      def cons[A](head: A, tail: G[A]) = F.pack(Right(F.ft.cons(head, tail)))
    }
}

private[derived] abstract class MkConsKGeneric {

  implicit def mkConsKGeneric[F[_], G[_]](implicit F: Generic1[F, MkConsK[*[_], G]]): MkConsK[F, G] =
    new MkConsK[F, G] {
      def cons[A](head: A, tail: G[A]) = F.from(F.fr.cons(head, tail))
    }
} 
Example 94
Source File: contravariant.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats
package derived

import shapeless._
import util.VersionSpecific.OrElse

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Contravariant[F] where F = ${F}.
Make sure that F[_] satisfies one of the following conditions:
  * it is a constant type λ[x => T]
  * it is a nested type λ[x => G[H[x]]] where G: Functor and H: Contravariant
  * it is a generic case class where all fields have a Contravariant instance
  * it is a generic sealed trait where all subclasses have a Contravariant instance

Note: using kind-projector notation - https://github.com/typelevel/kind-projector""")
trait MkContravariant[F[_]] extends Contravariant[F] {
  def safeContramap[A, B](fa: F[A])(f: B => Eval[A]): Eval[F[B]]
  def contramap[A, B](fa: F[A])(f: B => A): F[B] = safeContramap(fa)((b: B) => Eval.later(f(b))).value
}

object MkContravariant extends MkContravariantDerivation {
  def apply[F[_]](implicit F: MkContravariant[F]): MkContravariant[F] = F
}

private[derived] abstract class MkContravariantDerivation extends MkFunctorContraNested {
  implicit val mkContraHNil: MkContravariant[Const[HNil]#λ] = mkContraConst
  implicit val mkContraCNil: MkContravariant[Const[CNil]#λ] = mkContraConst

  implicit def mkContraConst[T]: MkContravariant[Const[T]#λ] =
    new MkContravariant[Const[T]#λ] {
      def safeContramap[A, B](t: T)(f: B => Eval[A]): Eval[T] = Eval.now(t)
    }
}

private[derived] abstract class MkFunctorContraNested extends MkContravariantCons {

  implicit def mkFunctorContraNested[F[_]](implicit F: Split1[F, Functor, ContraOrMk]): MkContravariant[F] =
    new MkContravariant[F] {

      def safeContramap[A, B](fa: F[A])(f: B => Eval[A]): Eval[F[B]] =
        Eval.later(F.pack(F.fo.map(F.unpack(fa))(mkContraSafe(F.fi)(_)(f).value)))
    }
}

private[derived] abstract class MkContravariantCons extends MkContravariantGeneric {

  implicit def mkContraHCons[F[_]](implicit F: IsHCons1[F, ContraOrMk, MkContravariant]): MkContravariant[F] =
    new MkContravariant[F] {

      def safeContramap[A, B](fa: F[A])(f: B => Eval[A]): Eval[F[B]] =
        Eval.now(F.unpack(fa)).flatMap { case (fha, fta) =>
          for {
            fhb <- mkContraSafe(F.fh)(fha)(f)
            ftb <- F.ft.safeContramap(fta)(f)
          } yield F.pack(fhb, ftb)
        }
    }

  implicit def mkContraCCons[F[_]](implicit F: IsCCons1[F, ContraOrMk, MkContravariant]): MkContravariant[F] =
    new MkContravariant[F] {

      def safeContramap[A, B](fa: F[A])(f: B => Eval[A]): Eval[F[B]] = F.unpack(fa) match {
        case Left(fha) => mkContraSafe(F.fh)(fha)(f).map(fhb => F.pack(Left(fhb)))
        case Right(fta) => F.ft.safeContramap(fta)(f).map(ftb => F.pack(Right(ftb)))
      }
    }
}

private[derived] abstract class MkContravariantGeneric {
  protected type ContraOrMk[F[_]] = Contravariant[F] OrElse MkContravariant[F]

  protected def mkContraSafe[F[_], A, B](F: ContraOrMk[F])(fa: F[B])(f: A => Eval[B]): Eval[F[A]] =
    F.unify match {
      case mk: MkContravariant[F] => mk.safeContramap(fa)(f)
      case p => Eval.later(p.contramap(fa)(f(_).value))
    }

  implicit def mkContraGeneric[F[_]](implicit F: Generic1[F, MkContravariant]): MkContravariant[F] =
    new MkContravariant[F] {

      def safeContramap[A, B](fa: F[A])(f: B => Eval[A]): Eval[F[B]] =
        F.fr.safeContramap(F.to(fa))(f).map(F.from)
    }
} 
Example 95
Source File: monoid.scala    From kittens   with Apache License 2.0 5 votes vote down vote up
package cats.derived

import cats.Monoid
import shapeless._
import util.VersionSpecific.{OrElse, Lazy}

import scala.annotation.implicitNotFound

@implicitNotFound("""Could not derive an instance of Monoid[A] where A = ${A}.
Make sure that A is a case class where all fields have a Monoid instance.""")
trait MkMonoid[A] extends Monoid[A]

object MkMonoid extends MkMonoidDerivation {
  def apply[A](implicit ev: MkMonoid[A]): MkMonoid[A] = ev
}

private[derived] abstract class MkMonoidDerivation {

  implicit val mkMonoidHNil: MkMonoid[HNil] =
    instance[HNil](HNil)((_, _) => HNil)

  implicit def mkMonoidHCons[H, T <: HList](
    implicit H: Monoid[H] OrElse MkMonoid[H], T: MkMonoid[T]
  ): MkMonoid[H :: T] = instance(H.unify.empty :: T.empty) {
    case (hx :: tx, hy :: ty) => H.unify.combine(hx, hy) :: T.combine(tx, ty)
  }


  implicit def mkMonoidGeneric[A, R](implicit A: Generic.Aux[A, R], R: Lazy[MkMonoid[R]]): MkMonoid[A] =
    new MkMonoid[A] {
      // Cache empty case classes.
      lazy val empty = A.from(R.value.empty)
      def combine(x: A, y: A) = A.from(R.value.combine(A.to(x), A.to(y)))
    }

  private def instance[A](default: => A)(f: (A, A) => A): MkMonoid[A] =
    new MkMonoid[A] {
      def empty = default
      def combine(x: A, y: A) = f(x, y)
    }
} 
Example 96
Source File: ObjectEncoder.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package mist.api.encoding

import mist.api.data.{JsData, JsMap}
import shadedshapeless.labelled.FieldType
import shadedshapeless._

import scala.annotation.implicitNotFound

@implicitNotFound(msg =
  "Couldn't find mist.api.encoding.ObjectEncoder[${A}]" +
  " Ensure that JsEncoder instances exists for it's fields" +
  " or add `import mist.api.encoding.defaults._`"
)
trait ObjectEncoder[A] { self =>
  def apply(a : A): JsMap
}

object ObjectEncoder {

  def apply[A](implicit enc: ObjectEncoder[A]): ObjectEncoder[A] = enc

  def create[A](f: A => JsMap): ObjectEncoder[A] = new ObjectEncoder[A] {
    override def apply(a: A): JsMap = f(a)
  }

  implicit val hNilEnc: ObjectEncoder[HNil] = ObjectEncoder.create[HNil](_ => JsMap.empty)

  implicit def hlistExt[K <: Symbol, H, T <: HList](implicit
    witness: Witness.Aux[K],
    lHenc: Lazy[JsEncoder[H]],
    tEnc: ObjectEncoder[T]
  ): ObjectEncoder[FieldType[K, H] :: T] = {
    val hEnc = lHenc.value
    val key = witness.value.name
    ObjectEncoder.create[FieldType[K, H] :: T](hlist => {
      val h = hEnc(hlist.head)
      val t = tEnc(hlist.tail)
      val values = (key -> h) +: t.fields
      JsMap(values: _*)
    })
  }

  implicit def labelled[A, H <: HList](implicit labGen: LabelledGeneric.Aux[A, H], enc: ObjectEncoder[H]): ObjectEncoder[A] =
    ObjectEncoder.create(a => enc(labGen.to(a)))
} 
Example 97
Source File: ObjectExtractor.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package mist.api.encoding

import mist.api._
import mist.api.data.{JsData, JsMap, JsNull}
import shadedshapeless.labelled.FieldType
import shadedshapeless._
import shadedshapeless.record._

import scala.annotation.implicitNotFound
import scala.reflect.ClassTag

@implicitNotFound("Couldn't find ObjectExtractor instances for ${A}. Ensure that there are JsExtractor instances for every field type of ${A}")
trait ObjectExtractor[A] {
  def `type`: MObj
  def apply(js: JsData): Extraction[A]
}

object ObjectExtractor {

  def apply[A](argType: MObj)(f: JsMap => Extraction[A]): ObjectExtractor[A] = new ObjectExtractor[A] {
    def apply(js: JsData): Extraction[A] = js match {
      case m: JsMap => f(m)
      case other =>
        Failed.InvalidType(argType.toString, other.toString)
    }
    val `type`: MObj = argType
  }

  implicit val hNilExt: ObjectExtractor[HNil] = ObjectExtractor(MObj.empty)(_ => Extracted(HNil))

  implicit def hlistExt[K <: Symbol, H, T <: HList](implicit
    witness: Witness.Aux[K],
    lHExt: Lazy[JsExtractor[H]],
    tExt: ObjectExtractor[T]
  ): ObjectExtractor[FieldType[K, H] :: T] = {
    val key = witness.value.name
    val hExt = lHExt.value.transformFailure(f => Failed.InvalidField(key, f))
    val headType = witness.value.name -> hExt.`type`
    val `type` = MObj(headType +: tExt.`type`.fields)

    ObjectExtractor(`type`)(map => {
      val headV = map.fieldValue(key)
      (hExt(headV), tExt(map)) match {
        case (Extracted(h), Extracted(t)) => Extracted((h :: t).asInstanceOf[FieldType[K, H] :: T])
        case (Extracted(h), f: Failed) => f
        case (f: Failed, Extracted(t)) => f
        case (f1: Failed, f2: Failed) => Failed.toComplex(f1, f2)
      }
    })
  }

  implicit def labelled[A, H <: HList](
    implicit
    labGen: LabelledGeneric.Aux[A, H],
    clzTag: ClassTag[A],
    ext: ObjectExtractor[H]
  ): ObjectExtractor[A] =
    ObjectExtractor(ext.`type`)(map => {
      ext(map) match {
        case Extracted(h) => Extracted(labGen.from(h))
        case f: Failed => Failed.IncompleteObject(clzTag.runtimeClass.getName, f)
      }
    })
} 
Example 98
Source File: DefaultsPatcher.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package mist.api.encoding

import mist.api.data.{JsMap, JsNull}
import shadedshapeless.labelled.FieldType
import shadedshapeless._

import scala.annotation.implicitNotFound


@implicitNotFound("Couldn't find DefaultsPatcher for ${A}. Ensure that there are JsEncoder instances for default values in current scope")
trait DefaultsPatcher[A] {
  def apply(js: JsMap): JsMap
}

object DefaultsPatcher {

  trait InternalPatcher[A] {
    def apply(a: A, js: JsMap): JsMap
  }

  object InternalPatcher {
    def create[A](f: (A, JsMap) => JsMap): InternalPatcher[A] = new InternalPatcher[A] {
      override def apply(a: A, js: JsMap): JsMap = f(a, js)
    }

    implicit val hHNilPatcher: InternalPatcher[HNil] = InternalPatcher.create((_, js) => js)

    implicit def hlistPatcher[K <: Symbol, H, T <: HList](implicit
      witness: Witness.Aux[K],
      lEnc: Lazy[JsEncoder[H]],
      tPath: InternalPatcher[T]
    ): InternalPatcher[FieldType[K, H] :: T] = {
      val enc = lEnc.value
      val key = witness.value.name
      InternalPatcher.create[FieldType[K, H] :: T]((hList, js) => {
        val patched = js.fieldValue(key) match {
          case JsNull => JsMap((key -> enc(hList.head)) +: js.fields: _*)
          case _ => js
        }
        tPath(hList.tail, patched)
      })
    }
  }


  implicit def labelled[A, H <: HList](implicit
    defaults: Default.AsRecord.Aux[A, H],
    intPatch: InternalPatcher[H]
  ): DefaultsPatcher[A] = new DefaultsPatcher[A] {
    override def apply(js: JsMap): JsMap = {
      intPatch.apply(defaults(), js)
    }
  }

  def apply[A](implicit patcher: DefaultsPatcher[A]): DefaultsPatcher[A] = patcher
} 
Example 99
Source File: JsEncoder.scala    From mist   with Apache License 2.0 5 votes vote down vote up
package mist.api.encoding

import mist.api.data._

import scala.annotation.implicitNotFound

@implicitNotFound("Couldn't find JsEncoder instance for ${A}. Check that function return value type has encoder instance or import default `mist.api.encoder.defaults._`")
trait JsEncoder[A] { self =>
  def apply(a : A): JsData
}

object JsEncoder {
  def apply[A](f: A => JsData): JsEncoder[A] = new JsEncoder[A] {
    override def apply(a: A): JsData = f(a)
  }
}

trait defaultEncoders {

  implicit val identity: JsEncoder[JsData] = JsEncoder(data => data)
  implicit val unitEnc: JsEncoder[Unit] = JsEncoder(_ => JsUnit)

  implicit val booleanEnc: JsEncoder[Boolean] = JsEncoder(b => JsBoolean(b))
  implicit val shortEnc: JsEncoder[Short] = JsEncoder(n => JsNumber(n.toInt))
  implicit val intEnc: JsEncoder[Int] = JsEncoder(i => JsNumber(i))
  implicit val longEnc: JsEncoder[Long] = JsEncoder(i => JsNumber(i))
  implicit val floatEnc: JsEncoder[Float] = JsEncoder(f => JsNumber(f.toDouble))
  implicit val doubleEnc: JsEncoder[Double] = JsEncoder(d => JsNumber(d))
  implicit val stringEnc: JsEncoder[String] = JsEncoder(s => JsString(s))

  implicit def seqEnc[A](implicit enc: JsEncoder[A]): JsEncoder[Seq[A]] = JsEncoder(seq => JsList(seq.map(v => enc(v))))
  implicit def listEnc[A](implicit enc: JsEncoder[A]): JsEncoder[List[A]] = JsEncoder(list => JsList(list.map(v => enc(v))))
  implicit def arrEnc[A](implicit enc: JsEncoder[Seq[A]]): JsEncoder[Array[A]] = JsEncoder(arr => enc(arr.toSeq))
  implicit def optEnc[A](implicit enc: JsEncoder[A]): JsEncoder[Option[A]] = JsEncoder {
    case Some(a) => enc(a)
    case None => JsNull
  }
  implicit def mapEnc[A](implicit enc: JsEncoder[A]): JsEncoder[Map[String, A]] = JsEncoder(m => JsMap(m.mapValues(enc.apply)))
}

object defaultEncoders extends defaultEncoders 
Example 100
Source File: Resolvable.scala    From cornichon   with Apache License 2.0 5 votes vote down vote up
package com.github.agourlay.cornichon.resolver

import java.util.UUID

import com.github.agourlay.cornichon.json.CornichonJson
import cats.instances.string._
import io.circe.Json

import scala.annotation.implicitNotFound

@implicitNotFound("No instance of typeclass Resolvable found for type ${A} - this instance is required if you are trying to use ${A} as custom HTTP body type")
trait Resolvable[A] {

  def toResolvableForm(r: A): String
  def fromResolvableForm(r: String): A

  def transformResolvableForm(r: A)(transf: String => String): A = {
    val rf = toResolvableForm(r)
    val updated = transf(rf)
    // If the transformation function had no effect
    // we can return the original value directly
    // and avoid an extra transformation from the resolved form
    if (updated == rf) r else fromResolvableForm(updated)
  }

}

object Resolvable {

  def apply[A](implicit resolvable: Resolvable[A]): Resolvable[A] = resolvable

  implicit val stringResolvable = new Resolvable[String] {
    def toResolvableForm(s: String) = s
    def fromResolvableForm(s: String) = s
  }

  implicit val booleanResolvable = new Resolvable[Boolean] {
    def toResolvableForm(b: Boolean) = b.toString
    def fromResolvableForm(b: String) = java.lang.Boolean.parseBoolean(b)
  }

  implicit val intResolvable = new Resolvable[Int] {
    def toResolvableForm(i: Int) = i.toString
    def fromResolvableForm(i: String) = java.lang.Integer.parseInt(i)
  }

  implicit val shortResolvable = new Resolvable[Short] {
    def toResolvableForm(s: Short) = s.toString
    def fromResolvableForm(s: String) = java.lang.Short.parseShort(s)
  }

  implicit val doubleResolvable = new Resolvable[Double] {
    def toResolvableForm(d: Double) = d.toString
    def fromResolvableForm(d: String) = java.lang.Double.parseDouble(d)
  }

  implicit val floatResolvable = new Resolvable[Float] {
    def toResolvableForm(f: Float) = f.toString
    def fromResolvableForm(f: String) = java.lang.Float.parseFloat(f)
  }

  implicit val longResolvable = new Resolvable[Long] {
    def toResolvableForm(l: Long) = l.toString
    def fromResolvableForm(l: String) = java.lang.Long.parseLong(l)
  }

  implicit val bigDecResolvable = new Resolvable[BigDecimal] {
    def toResolvableForm(b: BigDecimal) = b.toString
    def fromResolvableForm(b: String) = BigDecimal(b)
  }

  implicit val uuidResolvable = new Resolvable[UUID] {
    def toResolvableForm(u: UUID) = u.toString
    def fromResolvableForm(u: String) = UUID.fromString(u)
  }

  implicit val jsonResolvable = new Resolvable[Json] {
    def toResolvableForm(j: Json) = j.spaces2
    def fromResolvableForm(j: String) = CornichonJson.parseDslJsonUnsafe(j)
  }

} 
Example 101
Source File: ZioHasBuilder.scala    From tofu   with Apache License 2.0 5 votes vote down vote up
package tofu.logging.zlogs

import izumi.reflect.Tag
import tofu.logging.Loggable
import tofu.logging.zlogs.ZioHasBuilder.UnHas
import zio.Has

import scala.annotation.implicitNotFound

class ZioHasBuilder[R](val loggable: Loggable[R]) extends AnyVal { self =>
  def of[U <: Has[_]](implicit U: UnHas[U]) =
    new ZioHasBuilder[R with U](loggable.narrow[R with U] + U.loggable.narrow[R with U])

  def make[R1 <: R]: ZLogs[R1] = ZLogs.withContext[R1](loggable.narrow[R1])
}

object ZioHasBuilder {
  @implicitNotFound(
    "Could not understand ${U} as zio loggable module. Check it is `Has[SomeService]` and `SomeService` has `Loggable` instance"
  )
  class UnHas[U](val loggable: Loggable[U]) extends AnyVal

  object UnHas {
    implicit def unHas[S: Tag](implicit S: Loggable[S]) =
      new UnHas[Has[S]](S.contramap(_.get))
  }
} 
Example 102
Source File: package.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s

import java.nio.charset.Charset

import org.apache.pulsar.client.api.Schema
import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType}

import scala.annotation.implicitNotFound

package object sprayjson {

  import spray.json._

  @implicitNotFound("No RootJsonWriter for type ${T} found. Bring an implicit RootJsonWriter[T] instance in scope")
  implicit def spraySchema[T: Manifest](implicit w: RootJsonWriter[T], r: RootJsonReader[T]): Schema[T] = new Schema[T] {
    override def clone(): Schema[T] = this
    override def encode(t: T): Array[Byte] = w.write(t).compactPrint.getBytes(Charset.forName("UTF-8"))
    override def decode(bytes: Array[Byte]): T = r.read(new String(bytes, "UTF-8").parseJson)
    override def getSchemaInfo: SchemaInfo =
      new SchemaInfo()
        .setName(manifest[T].runtimeClass.getCanonicalName)
        .setType(SchemaType.JSON)
        .setSchema("""{"type":"any"}""".getBytes("UTF-8"))
  }
} 
Example 103
Source File: package.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s

import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.nio.charset.StandardCharsets

import com.sksamuel.avro4s.AvroSchema
import com.sksamuel.avro4s.AvroInputStream
import com.sksamuel.avro4s.AvroOutputStream
import com.sksamuel.avro4s.Decoder
import com.sksamuel.avro4s.Encoder
import com.sksamuel.avro4s.SchemaFor
import org.apache.pulsar.client.api.Schema
import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType}

import scala.annotation.implicitNotFound


package object avro {

  @implicitNotFound("No Avro Schema for type ${T} found.")
  implicit def avroSchema[T: Manifest: SchemaFor: Encoder: Decoder]: Schema[T] = new Schema[T] {

    val schema: org.apache.avro.Schema = AvroSchema[T]

    override def clone(): Schema[T] = this

    override def encode(t: T): Array[Byte] = {
      val baos = new ByteArrayOutputStream
      val aos = AvroOutputStream.binary[T].to(baos).build(schema)
      aos.write(t)
      aos.flush()
      aos.close()
      baos.toByteArray()
    }

    override def decode(bytes: Array[Byte]): T = {
      val bais = new ByteArrayInputStream(bytes)
      val ais = AvroInputStream.binary[T].from(bais).build(schema)
      val first = ais.iterator.next()
      ais.close()
      first
    }

    override def getSchemaInfo: SchemaInfo =
      new SchemaInfo()
        .setName(manifest[T].runtimeClass.getCanonicalName)
        .setType(SchemaType.AVRO)
        .setSchema(schema.toString.getBytes(StandardCharsets.UTF_8))
  }
} 
Example 104
Source File: playjson.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s

import java.nio.charset.Charset

import org.apache.pulsar.client.api.Schema
import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType}
import play.api.libs.json.{Json, Reads, Writes}

import scala.annotation.implicitNotFound

package object playjson {

  @implicitNotFound("No Writes or Reads for type ${T} found. Bring an implicit Writes[T] and Reads[T] instance in scope")
  implicit def playSchema[T: Manifest](implicit w: Writes[T], r: Reads[T]): Schema[T] = new Schema[T] {
    override def clone(): Schema[T] = this
    override def encode(t: T): Array[Byte] = Json.stringify(Json.toJson(t)(w)).getBytes(Charset.forName("UTF-8"))
    override def decode(bytes: Array[Byte]): T = Json.parse(bytes).as[T]
    override def getSchemaInfo: SchemaInfo =
      new SchemaInfo()
        .setName(manifest[T].runtimeClass.getCanonicalName)
        .setType(SchemaType.JSON)
        .setSchema("""{"type":"any"}""".getBytes("UTF-8"))
  }
} 
Example 105
Source File: package.scala    From pulsar4s   with Apache License 2.0 5 votes vote down vote up
package com.sksamuel.pulsar4s

import java.nio.charset.StandardCharsets

import io.circe.{Decoder, Encoder, Json, Printer}
import org.apache.pulsar.client.api.Schema
import org.apache.pulsar.common.schema.{SchemaInfo, SchemaType}

import scala.annotation.implicitNotFound


package object circe {

  @implicitNotFound(
    "No Encoder for type ${T} found. Use 'import io.circe.generic.auto._' or provide an implicit Encoder instance ")
  implicit def circeSchema[T: Manifest](implicit
                                        encoder: Encoder[T],
                                        decoder: Decoder[T],
                                        printer: Json => String = Printer.noSpaces.print): Schema[T] = new Schema[T] {
    override def clone(): Schema[T] = this
    override def encode(t: T): Array[Byte] = printer(encoder(t)).getBytes(StandardCharsets.UTF_8)
    override def decode(bytes: Array[Byte]): T =
      io.circe.jawn.decode[T](new String(bytes, StandardCharsets.UTF_8)).fold(throw _, identity)
    override def getSchemaInfo: SchemaInfo =
      new SchemaInfo()
        .setName(manifest[T].runtimeClass.getCanonicalName)
        .setType(SchemaType.JSON)
        .setSchema("""{"type":"any"}""".getBytes("UTF-8"))
  }
} 
Example 106
Source File: Twiddler.scala    From skunk   with MIT License 5 votes vote down vote up
// Copyright (c) 2018-2020 by Rob Norris
// This software is licensed under the MIT License (MIT).
// For more information see LICENSE or https://opensource.org/licenses/MIT

package skunk.util

import shapeless.{ HList, ::, HNil, Generic }
import shapeless.ops.hlist.Init
import shapeless.ops.hlist.Last
import shapeless.ops.hlist.Prepend
import scala.annotation.implicitNotFound


@implicitNotFound("Cannot construct a mapping between ${A} (which must be a twiddle-list type) and the specified target type (which must be a case class of the same structure).")
trait Twiddler[A] {
  type Out
  def to(h: A): Out
  def from(o: Out): A
}

object Twiddler {

  def apply[H](implicit ev: Twiddler[H]): ev.type = ev

  type Aux[A, O] = Twiddler[A] { type Out = O }

  implicit def base[A]: Aux[A :: HNil, A] =
    new Twiddler[A :: HNil] {
      type Out = A
      def to(a: A :: HNil) = a.head
      def from(o: Out) = o :: HNil
    }

  implicit def inductive[A <: HList, IO <: HList, LO, TO](
    implicit in: Init.Aux[A, IO],
             la: Last.Aux[A, LO],
             tw: Twiddler.Aux[IO, TO],
             pp: Prepend.Aux[IO, LO :: HNil, A]
  ): Aux[A, (TO, LO)] =
    new Twiddler[A] {
      type Out = (TO, LO)
      def from(o: Out): A = tw.from(o._1) :+ o._2
      def to(h: A): Out = (tw.to(in(h)), la(h))
    }

  implicit def generic[A, R, TO](
    implicit ge: Generic.Aux[A, R],
             tw: Twiddler.Aux[R, TO]
  ): Aux[A, TO] =
    new Twiddler[A] {
      type Out = TO
      def to(h: A): Out = tw.to(ge.to(h))
      def from(o: Out): A = ge.from(tw.from(o))
    }

} 
Example 107
Source File: package.scala    From sttp   with Apache License 2.0 5 votes vote down vote up
package sttp.client

import java.io.{ByteArrayOutputStream, InputStream, OutputStream}
import java.nio.{Buffer, ByteBuffer}

import scala.annotation.{implicitNotFound, tailrec}

package object internal {
  private[client] def contentTypeWithCharset(ct: String, charset: String): String =
    s"$ct; charset=$charset"

  private[client] def charsetFromContentType(ct: String): Option[String] =
    ct.split(";").map(_.trim.toLowerCase).collectFirst {
      case s if s.startsWith("charset=") && s.substring(8).trim != "" => s.substring(8).trim
    }

  private[client] def transfer(is: InputStream, os: OutputStream): Unit = {
    var read = 0
    val buf = new Array[Byte](1024)

    @tailrec
    def transfer(): Unit = {
      read = is.read(buf, 0, buf.length)
      if (read != -1) {
        os.write(buf, 0, read)
        transfer()
      }
    }

    transfer()
  }

  private[client] def toByteArray(is: InputStream): Array[Byte] = {
    val os = new ByteArrayOutputStream
    transfer(is, os)
    os.toByteArray
  }

  private[client] def concatByteBuffers(bb1: ByteBuffer, bb2: ByteBuffer): ByteBuffer = {
    val buf = ByteBuffer
      .allocate(bb1.array().length + bb2.array().length)
      .put(bb1)
      .put(bb2)
    // rewind() returns Buffer in Java8, and ByteBuffer in Java11
    // calling the method from the base class to avoid NoSuchMethodError
    (buf: Buffer).rewind()
    buf
  }

  
  private[client] def sanitizeCharset(charset: String): String = {
    val c2 = charset.trim()
    val c3 = if (c2.startsWith("\"")) c2.substring(1) else c2
    if (c3.endsWith("\"")) c3.substring(0, c3.length - 1) else c3
  }

  @implicitNotFound(
    "This is a partial request, the method & url are not specified. Use " +
      ".get(...), .post(...) etc. to obtain a non-partial request."
  )
  private[client] type IsIdInRequest[U[_]] = U[Unit] =:= Identity[Unit]

  private[client] val Utf8 = "utf-8"
  private[client] val Iso88591 = "iso-8859-1"
  private[client] val CrLf = "\r\n"
} 
Example 108
Source File: Streamable.scala    From swave   with Mozilla Public License 2.0 5 votes vote down vote up
package swave.core

import org.reactivestreams.Publisher
import scala.annotation.implicitNotFound
import scala.collection.immutable
import scala.concurrent.Future
import scala.util.Try
import swave.core.impl.util.RingBuffer
import swave.core.io.Bytes

@implicitNotFound(
  msg =
    "Don't know how to create a stream from instances of type ${T}. Maybe you'd like to provide an `implicit Streamable[${T}]`?")
//#source-quote
abstract class Streamable[-T] {
  type Out
  def apply(value: T): Spout[Out]
}
//#source-quote

object Streamable {
  type Aux[T, O] = Streamable[T] { type Out = O }

  private val spout =
    new Streamable[Spout[AnyRef]] {
      type Out = AnyRef
      def apply(value: Spout[AnyRef]) = value
    }
  implicit def forSpout[T]: Aux[Spout[T], T] = spout.asInstanceOf[Aux[Spout[T], T]]

  private val option =
    new Streamable[Option[AnyRef]] {
      type Out = AnyRef
      def apply(value: Option[AnyRef]) = Spout.fromOption(value)
    }
  implicit def forOption[T]: Aux[Option[T], T] = option.asInstanceOf[Aux[Option[T], T]]

  private val iterable =
    new Streamable[immutable.Iterable[AnyRef]] {
      type Out = AnyRef
      def apply(value: immutable.Iterable[AnyRef]) = Spout.fromIterable(value)
    }
  implicit def forIterable[T]: Aux[immutable.Iterable[T], T] =
    iterable.asInstanceOf[Aux[immutable.Iterable[T], T]]

  private val iterator =
    new Streamable[Iterator[AnyRef]] {
      type Out = AnyRef
      def apply(value: Iterator[AnyRef]) = Spout.fromIterator(value)
    }
  implicit def forIterator[T]: Aux[Iterator[T], T] = iterator.asInstanceOf[Aux[Iterator[T], T]]

  private val publisher =
    new Streamable[Publisher[AnyRef]] {
      type Out = AnyRef
      def apply(value: Publisher[AnyRef]) = Spout.fromPublisher(value)
    }
  implicit def forPublisher[T]: Aux[Publisher[T], T] =
    publisher.asInstanceOf[Aux[Publisher[T], T]]

  private val ringBuffer =
    new Streamable[RingBuffer[AnyRef]] {
      type Out = AnyRef
      def apply(value: RingBuffer[AnyRef]) = Spout.fromRingBuffer(value)
    }
  private[swave] implicit def forRingBuffer[T]: Aux[RingBuffer[T], T] =
    ringBuffer.asInstanceOf[Aux[RingBuffer[T], T]]

  private val future =
    new Streamable[Future[AnyRef]] {
      type Out = AnyRef
      def apply(value: Future[AnyRef]) = Spout.fromFuture(value)
    }
  implicit def forFuture[T]: Aux[Future[T], T] = future.asInstanceOf[Aux[Future[T], T]]

  private val tryy =
    new Streamable[Try[AnyRef]] {
      type Out = AnyRef
      def apply(value: Try[AnyRef]) = Spout.fromTry(value)
    }
  implicit def forTry[T]: Aux[Try[T], T] = tryy.asInstanceOf[Aux[Try[T], T]]

  implicit def forBytes[T](implicit ev: Bytes[T]): Aux[T, Byte] =
    new Streamable[T] {
      type Out = Byte
      def apply(value: T): Spout[Byte] = Spout.fromIterator(ev.toSeq(value).iterator)
    }

  implicit def lazyStreamable[T, O](implicit ev: Streamable.Aux[T, O]): Aux[() ⇒ T, O] =
    new Streamable[() ⇒ T] {
      type Out = O
      def apply(f: () ⇒ T) = ev(f())
    }
} 
Example 109
Source File: Mutation.scala    From sangria-relay   with Apache License 2.0 5 votes vote down vote up
package sangria.relay

import sangria.execution.FieldTag
import sangria.marshalling.FromInput
import sangria.schema._

import scala.annotation.implicitNotFound
import scala.reflect.ClassTag

trait Mutation {
  def clientMutationId: Option[String]
}

object Mutation {
  val ClientMutationIdFieldName = "clientMutationId"

  def fieldWithClientMutationId[Ctx, Val, Res : MutationLike : ClassTag, Input: FromInput](
        fieldName: String,
        typeName: String,
        mutateAndGetPayload: (Input, Context[Ctx, Val]) => Action[Ctx, Res],
        inputFields: List[InputField[_]] = Nil,
        outputFields: List[Field[Ctx, Res]] = Nil,
        tags: List[FieldTag] = Nil,
        complexity: Option[(Ctx, Args, Double) => Double] = None,
        fieldDescription: Option[String] = None) = {
    val inputType = InputObjectType[Input](typeName + "Input",
      fields = inputFields :+ InputField(ClientMutationIdFieldName, OptionInputType(StringType)))

    val outputType = ObjectType(typeName + "Payload",
      outputFields :+
        Field(ClientMutationIdFieldName, OptionType(StringType),
          resolve = (ctx: Context[Ctx, Res]) => implicitly[MutationLike[Res]].clientMutationId(ctx.value)))

    val inputArg = Argument("input", inputType)

    Field(fieldName, OptionType(outputType),
      description = fieldDescription,
      tags = tags,
      complexity = complexity,
      arguments = inputArg :: Nil,
      resolve = (ctx: Context[Ctx, Val]) => mutateAndGetPayload(ctx.arg(inputArg), ctx))
  }
}

@implicitNotFound("Type ${T} can't be used as a Mutation. Please consider defining implicit instance of sangria.relay.MutationLike for type ${T} or extending sangria.relay.Mutation trait.")
trait MutationLike[T] {
  def clientMutationId(value: T): Option[String]
}

object MutationLike {
  private object MutationIsMutationLike extends MutationLike[Mutation] {
    override def clientMutationId(value: Mutation) = value.clientMutationId
  }

  implicit def MutationIsMutationLike[T <: Mutation]: MutationLike[T] =
    MutationIsMutationLike.asInstanceOf[MutationLike[T]]
} 
Example 110
Source File: Marshallable.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package transmitter

import scala.annotation.implicitNotFound
import scala.concurrent.Future
import scala.util.control.NonFatal
import scala.util.{Success, Try}

@implicitNotFound("${B} is not marshallable")
trait Marshallable[B, R, P] {
  def marshal(value: B, abstraction: AbstractionRef): MessageBuffer
  def unmarshal(value: MessageBuffer, abstraction: AbstractionRef): Try[R]
  def unmarshal(value: Notice.Steady[Try[MessageBuffer]], abstraction: AbstractionRef): P

  type Type = Marshallable[B, R, P]

  @inline final def self: Type = this

  def connected: Boolean
}

sealed trait MarshallableResolution {
  @inline def apply[T](implicit marshallable: Marshallable[T, _, _])
  : marshallable.Type = marshallable.self

  @inline def Argument[T](implicit marshallable: Marshallable[T, T, _])
  : marshallable.Type = marshallable.self

  implicit def marshallable[B, I, R, P, T <: Transmittables](implicit
      resolution: Transmittable.Aux.Resolution[B, I, R, P, T],
      serializer: Serializable[I],
      contextBuilder: ContextBuilder[T]): Marshallable[B, R, P] =
    new Marshallable[B, R, P] {
      val transmittable = resolution.transmittable

      def connected = (transmittable: Transmittable[B, I, R]) match {
        case _: ConnectedTransmittable[_, _, _] => true
        case _: ConnectedTransmittable.Proxy[_, _, _] => true
        case _ => false
      }

      def marshal(value: B, abstraction: AbstractionRef) =
        try {
          implicit val context = contextBuilder(
            transmittable.transmittables, abstraction, ContextBuilder.sending)
          serializer serialize (transmittable buildIntermediate value)
        }
        catch {
          case NonFatal(exception) =>
            throw new RemoteAccessException(s"marshalling failed: $value").initCause(exception)
        }

      def unmarshal(value: MessageBuffer, abstraction: AbstractionRef) =
        try {
          implicit val context = contextBuilder(
            transmittable.transmittables, abstraction, ContextBuilder.receiving)
          serializer deserialize value map transmittable.buildResult
        }
        catch {
          case NonFatal(exception) =>
            throw new RemoteAccessException(s"unmarshalling failed: $value").initCause(exception)
        }

      def unmarshal(value: Notice.Steady[Try[MessageBuffer]], abstraction: AbstractionRef) =
        try {
          implicit val context = contextBuilder(
            transmittable.transmittables, abstraction, ContextBuilder.receiving)
          transmittable buildProxy (
            value map { _ flatMap serializer.deserialize })
        }
        catch {
          case NonFatal(exception) =>
            throw new RemoteAccessException("unmarshalling failed: could not create proxy object").initCause(exception)
        }
    }
}

object Marshallable extends MarshallableResolution {
  implicit object unit extends Marshallable[Unit, Unit, Future[Unit]] {
    def marshal(value: Unit, abstraction: AbstractionRef) =
      MessageBuffer.empty
    def unmarshal(value: MessageBuffer, abstraction: AbstractionRef) =
      Success(())
    def unmarshal(value: Notice.Steady[Try[MessageBuffer]], abstraction: AbstractionRef) =
      (value map { _ map { _ => () } }).toFutureFromTry
    def connected = false
  }

  implicit object nothing extends Marshallable[Nothing, Nothing, Future[Nothing]] {
    def nothing = throw new RemoteAccessException("Unexpected value of bottom type")
    def marshal(value: Nothing, abstraction: AbstractionRef) =
      nothing
    def unmarshal(value: MessageBuffer, abstraction: AbstractionRef) =
      nothing
    def unmarshal(value: Notice.Steady[Try[MessageBuffer]], abstraction: AbstractionRef) =
      (value map { _ map { _ => nothing } }).toFutureFromTry
    def connected = false
  }
} 
Example 111
Source File: Serializable.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package transmitter

import scala.annotation.{compileTimeOnly, implicitNotFound}
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
import scala.util.Try

@implicitNotFound("${T} is not serializable")
trait Serializable[T] {
  def serialize(value: T): MessageBuffer
  def deserialize(value: MessageBuffer): Try[T]
}

object Serializable {
  @inline def apply[T](implicit serializable: Serializable[T]): Serializable[T] =
    serializable

  @compileTimeOnly("Value is not serializable")
  final implicit def resolutionFailure[T](implicit ev: DummyImplicit.Resolvable): Serializable[T] =
    macro SerializableResolutionFailure[T]

  @compileTimeOnly("Value is not serializable")
  final def dummy[T]: Serializable[T] = throw new NotImplementedError
}

object SerializableResolutionFailure {
  def apply[T: c.WeakTypeTag](c: whitebox.Context)(ev: c.Tree): c.Tree = {
    import c.universe._

    // the current macro expansion always appears twice
    // see: http://stackoverflow.com/a/20466423
    val recursionCount = c.openMacros.count { other =>
      c.enclosingPosition == other.enclosingPosition &&
        c.macroApplication.toString == other.macroApplication.toString
    }
    if (recursionCount > 2)
      c.abort(c.enclosingPosition, "Skipping serializable resolution failure macro for recursive invocation")

    val serializableType = weakTypeOf[Serializable[T]]

    if ((c inferImplicitValue serializableType).nonEmpty)
      c.abort(c.enclosingPosition, "Skipping serializable resolution failure macro to prioritize other implicit")

    val tpe = weakTypeOf[T]
    val message = s"$tpe is not serializable"

    q"""{
      @${termNames.ROOTPKG}.scala.annotation.compileTimeOnly($message) def resolutionFailure() = ()
      resolutionFailure()
      ${termNames.ROOTPKG}.loci.transmitter.Serializable.dummy[$tpe]
    }"""
  }
} 
Example 112
Source File: Placement.scala    From scala-loci   with Apache License 2.0 5 votes vote down vote up
package loci
package language

import scala.annotation.implicitNotFound

object Placement {
  @implicitNotFound("Expression must be placed on a peer")
  sealed trait Context[P]

  sealed trait On[P] {
    def apply[T, U](v: Context[P] => T)(implicit ev: PlacedClean[U on P, P, T, T, U]): U on P
    def local[T, U](v: Context[P] => T)(implicit ev: PlacedClean[U on P, P, T, T, U]): Local[U] on P
    def sbj[R, T, U](v: Context[P] => Remote[R] => T)(implicit ev: PlacedClean[U on P, P, T, T, U]): U per R on P
  }

  sealed trait Placed {
    def apply[P, T, U, S](v: Context[P] => T)(implicit ev0: PlacedType[T, S], ev1: PlacedClean[U on P, P, S, S, U]): U on P
  }

  sealed trait Select[Command[_, _[_, _]]] {
    def apply[P, Q, _on_[T, P] <: T on P](r: Remote[P] _on_ Q): Command[P, fromSingle]
    def apply[P](r: Remote[P]): Command[P, fromSingle]
    def apply[P](r0: Remote[P], r1: Remote[P], rn: Remote[P]*): Command[P, fromMultiple]
  }

  sealed trait Run[P, placed[_, _]] {
    def run: Capture[P, placed] with Block[P, placed]
  }

  sealed trait Capture[P, placed[_, _]] {
    def capture(v: Any*): Block[P, placed]
  }

  sealed trait Block[P, placed[_, _]] {
    def apply[T, U](v: Context[P] => T)(implicit ev: PlacedClean[U on P, P, T, T, U]): U placed P
    def sbj[R, T, U](v: Context[P] => Remote[R] => T)(implicit ev: PlacedClean[U on P, P, T, T, U]): U per R placed P
  }

  sealed trait Narrow {
    def apply[P, T, _on_[T, P] <: T on P](v: T _on_ P): T from P
  }

  sealed trait Call[Q, placed[_, _]] {
    def call[P, R, T, _on_[T, P] <: T on P](v: T _on_ R)(implicit ev: PeerType[Q, R, P]): T placed P
  }
} 
Example 113
Source File: TroyCodec.scala    From troy   with Apache License 2.0 5 votes vote down vote up
package troy
package driver.codecs

import com.datastax.driver.core._
import scala.annotation.implicitNotFound
import scala.collection.JavaConverters._
import troy.driver.{ CassandraDataType => CT }

@implicitNotFound("Incompatible column type ${S} <--> ${C}")
trait TroyCodec[C <: CT, S] {
  def get(gettable: GettableByIndexData, i: Int): S
  def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: S): T
}

object TroyCodec extends PrimitivesCodecs {

  def instance[C <: CT, S](typeCodec: TypeCodec[S]) =
    new TroyCodec[C, S] {
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: S) = settable.set(i, value, typeCodec)
      override def get(gettable: GettableByIndexData, i: Int) = gettable.get(i, typeCodec)
    }

  implicit def wrapJavaTypeCodecs[S <: AnyRef, C <: CT](implicit hasTypeCodec: HasTypeCodec[S, C]) =
    instance[C, S](hasTypeCodec.typeCodec)

  implicit def wrapOptional[C <: CT, S <: AnyRef](implicit hasTypeCodec: HasTypeCodec[S, C]) =
    instance[C, Option[S]](new OptionTypeCodec(hasTypeCodec.typeCodec))

  implicit def listOfNonPrimitives[C <: CT.Native, S <: AnyRef](implicit inner: HasTypeCodec[S, C]) =
    new TroyCodec[CT.List[C], Seq[S]] {
      val codec = TypeCodec.list(inner.typeCodec)
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Seq[S]) = settable.set(i, value.asJava, codec)
      override def get(gettable: GettableByIndexData, i: Int) = gettable.get(i, codec).asScala
    }

  implicit def listOfPrimitives[J <: AnyRef, S <: AnyVal, C <: CT.Native](implicit inner: TroyCodec[CT.List[C], Seq[J]], converter: PrimitivesConverter[J, S]) =
    new TroyCodec[CT.List[C], Seq[S]] {
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Seq[S]) = inner.set(settable, i, value.map(converter.toJava))
      override def get(gettable: GettableByIndexData, i: Int) = inner.get(gettable, i).map(converter.toScala)
    }

  implicit def setOfNonPrimitives[S <: AnyRef, C <: CT.Native](implicit inner: HasTypeCodec[S, C]) =
    new TroyCodec[CT.Set[C], Set[S]] {
      val codec = TypeCodec.set(inner.typeCodec)
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Set[S]) = settable.set(i, value.asJava, codec)
      override def get(gettable: GettableByIndexData, i: Int) = gettable.get(i, codec).asScala.toSet
    }

  implicit def setOfPrimitives[J <: AnyRef, S <: AnyVal, C <: CT.Native](implicit inner: TroyCodec[CT.Set[C], Set[J]], converter: PrimitivesConverter[J, S]) =
    new TroyCodec[CT.Set[C], Set[S]] {
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Set[S]) = inner.set(settable, i, value.map(converter.toJava))
      override def get(gettable: GettableByIndexData, i: Int) = inner.get(gettable, i).map(converter.toScala)
    }

  implicit def mapOfNonPrimitives[KS <: AnyRef, KC <: CT.Native, VS <: AnyRef, VC <: CT.Native](implicit keyInner: HasTypeCodec[KS, KC], valueInner: HasTypeCodec[VS, VC]) =
    new TroyCodec[CT.Map[KC, VC], Map[KS, VS]] {
      val codec = TypeCodec.map(keyInner.typeCodec, valueInner.typeCodec)
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Map[KS, VS]) = settable.set(i, value.asJava, codec)
      override def get(gettable: GettableByIndexData, i: Int) = gettable.get(i, codec).asScala.toMap
    }

  implicit def mapOfPrimitives[KJ, KS, KC <: CT.Native, VJ, VS, VC <: CT.Native](implicit inner: TroyCodec[CT.Map[KC, VC], Map[KJ, VJ]], converter: PrimitivesConverter[(KJ, VJ), (KS, VS)]) =
    new TroyCodec[CT.Map[KC, VC], Map[KS, VS]] {
      override def set[T <: SettableByIndexData[T]](settable: T, i: Int, value: Map[KS, VS]) = inner.set(settable, i, value.map(converter.toJava))
      override def get(gettable: GettableByIndexData, i: Int) = inner.get(gettable, i).map(converter.toScala)
    }
} 
Example 114
Source File: HasTypeCodec.scala    From troy   with Apache License 2.0 5 votes vote down vote up
package troy
package driver.codecs

import java.net.InetAddress
import java.nio.ByteBuffer
import java.util.{ Date, UUID }

import com.datastax.driver.core.{ LocalDate, TypeCodec }
import troy.driver.{ CassandraDataType => CT }

import scala.annotation.implicitNotFound

case class HasTypeCodec[S, C <: CT](typeCodec: TypeCodec[S]) extends AnyVal

object HasTypeCodec {
  import TypeCodec._

  implicit val BooleanHasCodecAsBoolean = HasTypeCodec[java.lang.Boolean, CT.Boolean](cboolean)
  implicit val TinyIntHasCodecAsByte = HasTypeCodec[java.lang.Byte, CT.TinyInt](tinyInt)
  implicit val SmallIntHasCodecAsShort = HasTypeCodec[java.lang.Short, CT.SmallInt](smallInt)
  implicit val IntHasCodecAsInteger = HasTypeCodec[java.lang.Integer, CT.Int](cint)
  implicit val BigIntHasCodecAsLong = HasTypeCodec[java.lang.Long, CT.BigInt](bigint)
  implicit val CounterHasCodecAsLong = HasTypeCodec[java.lang.Long, CT.Counter](counter)
  implicit val FloatHasCodecAsFloat = HasTypeCodec[java.lang.Float, CT.Float](cfloat)
  implicit val DoubleHasCodecAsDouble = HasTypeCodec[java.lang.Double, CT.Double](cdouble)
  implicit val VarIntHasCodecAsBigInteger = HasTypeCodec[java.math.BigInteger, CT.VarInt](varint)
  implicit val DecimalHasCodecAsBigDecimal = HasTypeCodec[java.math.BigDecimal, CT.Decimal](decimal)
  implicit val AsciiHasCodecAsString = HasTypeCodec[String, CT.Ascii](ascii)
  implicit val VarCharHasCodecAsString = HasTypeCodec[String, CT.VarChar](varchar)
  implicit val TextHasCodecAsString = HasTypeCodec[String, CT.Text](varchar)
  implicit val BlobHasCodecAsByteBuffer = HasTypeCodec[ByteBuffer, CT.Blob](blob)
  implicit val DateHasCodecAsLocalDate = HasTypeCodec[LocalDate, CT.Date](date)
  implicit val TimeHasCodecAsLong = HasTypeCodec[java.lang.Long, CT.Time](time)
  implicit val TimestampHasCodecAsDate = HasTypeCodec[Date, CT.Timestamp](timestamp)
  implicit val UuidHasCodecAsUUID = HasTypeCodec[UUID, CT.Uuid](uuid)
  implicit val TimeUuidHasCodecAsUUID = HasTypeCodec[UUID, CT.TimeUuid](timeUUID)
  implicit val InetHasCodecAsInetAddress = HasTypeCodec[InetAddress, CT.Inet](inet)
} 
Example 115
Source File: Effect.scala    From cats-effect   with Apache License 2.0 5 votes vote down vote up
package cats
package effect

import simulacrum._
import cats.data.{EitherT, WriterT}
import scala.annotation.implicitNotFound
import scala.util.Either


  implicit def catsWriterTEffect[F[_]: Effect, L: Monoid]: Effect[WriterT[F, L, *]] =
    new WriterTEffect[F, L] { def F = Effect[F]; def L = Monoid[L] }

  private[effect] trait EitherTEffect[F[_]]
      extends Effect[EitherT[F, Throwable, *]]
      with Async.EitherTAsync[F, Throwable] {
    protected def F: Effect[F]

    def runAsync[A](fa: EitherT[F, Throwable, A])(cb: Either[Throwable, A] => IO[Unit]): SyncIO[Unit] =
      F.runAsync(fa.value)(cb.compose(_.flatMap(x => x)))

    override def toIO[A](fa: EitherT[F, Throwable, A]): IO[A] =
      F.toIO(F.rethrow(fa.value))
  }

  private[effect] trait WriterTEffect[F[_], L] extends Effect[WriterT[F, L, *]] with Async.WriterTAsync[F, L] {
    protected def F: Effect[F]
    protected def L: Monoid[L]

    def runAsync[A](fa: WriterT[F, L, A])(cb: Either[Throwable, A] => IO[Unit]): SyncIO[Unit] =
      F.runAsync(fa.run)(cb.compose(_.map(_._2)))

    override def toIO[A](fa: WriterT[F, L, A]): IO[A] =
      F.toIO(fa.value(F))
  }
} 
Example 116
Source File: test4_rewrite.scala    From lms-clean   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lms
package experimental

import lms.core.utils
import scala.annotation.implicitNotFound

class RewriteTest extends TutorialFunSuite {
  val under = "experimental/rewrite-"

  val IR: DSL with BaseExp = new Impl {}
  import IR._ // Int means IR.Int
  import codeBuilder.Exp

  def rewrite[A:Typ,B:Typ,C:Typ](f: (A,B) => Rewrite[C]): Unit = {
    val a = typ[A].from(Exp("?A"))
    val b = typ[B].from(Exp("?B"))
    val rw = codeBuilder.reifyPattern(f(a,b))
    val u = typ[C].to(rw.a)
    val v = typ[C].to(rw.b)
    println("rewrite: " + u + " ===> " + v)
  }


  test("01") {
    val res = utils.captureOut {

      def foo1(x: Int, y: Int): Int = reflect[Int]("foo1",ref(x),ref(y))
      def foo2(x: Int, y: Int): Int = reflect[Int]("foo2",ref(x),ref(y))

      rewrite((a:Int,b:Int) => Rewrite(foo1(a,b),foo2(a,b)))

    }
    check("01", res)
  }

  test("02") {
    val res = utils.captureOut {

      def foo1[A:Typ,B:Typ](x: A, y: B): A = reflect[A]("foo1",typ[A],typ[B],ref(x),ref(y))
      def foo2[A:Typ,B:Typ](x: A, y: B): A = reflect[A]("foo2",typ[A],typ[B],ref(x),ref(y))

      case class Param1(exp:Exp)
      case class Param2(exp:Exp)

      implicit object p1typ extends Typ[Param1] {
        def from(e: RewriteTest.this.IR.codeBuilder.Exp): Param1 = Param1(e)
        def to(x: Param1): RewriteTest.this.IR.codeBuilder.Exp = x.exp
        override def toString = "P1?"
      }
      implicit object p2typ extends Typ[Param2] {
        def from(e: RewriteTest.this.IR.codeBuilder.Exp): Param2 = Param2(e)
        def to(x: Param2): RewriteTest.this.IR.codeBuilder.Exp = x.exp
        override def toString = "P2?"
      }

      object Generic {
        type T = Param1
        type U = Param2
        type T1 = Param1
        type T2 = Param2
      }


      rewrite((a: Generic.T1, b: Generic.T2) => Rewrite(foo1(a,b),foo2(a,b)))

    }
    check("02", res)
  }


} 
Example 117
Source File: test2_auto.scala    From lms-clean   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lms
package experimental

import lms.core.utils
import scala.annotation.implicitNotFound

class AutoTest extends TutorialFunSuite {
  val under = "experimental/auto-"

  test("one") {
    val res = utils.captureOut {
      val IR: DSL with BaseExp = new Impl {}
      import IR._ // Int means IR.Int

      @ir def test1(x: Int, y: => Int): Int
      // transformed to:
      // def test1(x: Int, y: => Int): Int = reflect[Int]("test1",ref(x),ref(y))

      @ir def test2(x: Int, y: Int): Int = 666
      // transformed to:
      // def test2(x: Int, y: Int): Int = reflect[Int]("test2",ref(x),ref(y))
      // def test2_next(x: Int, y: Int): Int = 666
      // lower((x: Int, y: Int) => Rewrite(test2(x,y),test2_next(x,y))

      println(test1(3,7))

      println(test2(3,7))

      println(test2_next(3,7))

    }
    check("one", res)
  }

} 
Example 118
Source File: test3_cgen.scala    From lms-clean   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package lms
package experimental

import lms.core.utils
import scala.annotation.implicitNotFound

class CGenTest extends TutorialFunSuite {
  val under = "experimental/cgen-"

  test("01") {
    val res = utils.captureOut {
      import c._

      gen"""
      void main(argc: int, argv: char**) {
        puts("Hello!");
      }
      """
    }
    check("01", res)
  }

  test("02") {
    val res = utils.captureOut {
      import c._

      case class StringE(exp: Exp)
      implicit def lift(s: String) = StringE(Exp("\""+s+"\""))

      def puts(s: StringE) = gen"""
        puts(${s.exp});
      """

      def body() = puts("Hello!")

      val argc, argv = fresh
      gen"""
      void main($argc: int, $argv: char**) {
        ${body()}
      }
      """
    }
    check("02", res)
  }

} 
Example 119
Source File: client.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc

import shapeless.ops.hlist.ToSized
import shapeless.ops.sized.ToHList
import shapeless._

import scala.annotation.implicitNotFound
import scala.collection.LinearSeq
import scala.concurrent.duration._

trait ClientBase[F[_], Env] {
  def defaultTimeout: FiniteDuration = 20.seconds

  def send[In <: HList, Out <: HList](in: In, timeout: FiniteDuration)(implicit handler: Handler.Aux[F, Env, In, Out]): F[Out]
  final def send[In <: HList, Out <: HList](in: In)(implicit ev: Handler.Aux[F, Env, In, Out]): F[Out] = send(in, defaultTimeout)

  final def send[A1](protocolA1: Protocol.Aux[A1], timeout: FiniteDuration)(
      implicit F: Functor[F],
      ev: Handler.Aux[F, Env, Protocol.Aux[A1] :: HNil, Maybe[A1] :: HNil]
  ): F[Maybe[A1]] = F.map(send(protocolA1 :: HNil, timeout))(_.head)
  final def send[A1](protocolA1: Protocol.Aux[A1])(
      implicit F: Functor[F],
      ev: Handler.Aux[F, Env, Protocol.Aux[A1] :: HNil, Maybe[A1] :: HNil]
  ): F[Maybe[A1]] = send(protocolA1, defaultTimeout)

  final def send[CC[x] <: LinearSeq[x], A, N <: Nat, In <: HList, Out <: HList](
      sizedSeq: Sized[CC[Protocol.Aux[A]], N],
      timeout: FiniteDuration
  )(
      implicit F: Functor[F],
      toHList: ToHList.Aux[CC[Protocol.Aux[A]], N, In],
      ev0: Handler.Aux[F, Env, In, Out],
      ev1: ToSized.Aux[Out, CC, Maybe[A], N]
  ): F[Sized[CC[Maybe[A]], N]] = F.map(send(toHList(sizedSeq), timeout))(_.toSized)
  final def send[CC[x] <: LinearSeq[x], A, N <: Nat, In <: HList, Out <: HList](sizedSeq: Sized[CC[Protocol.Aux[A]], N])(
      implicit F: Functor[F],
      toHList: ToHList.Aux[CC[Protocol.Aux[A]], N, In],
      ev0: Handler.Aux[F, Env, In, Out],
      ev1: ToSized.Aux[Out, CC, Maybe[A], N]
  ): F[Sized[CC[Maybe[A]], N]] = send(sizedSeq, defaultTimeout)
}

trait Client[F[_], Env] extends ClientBase[F, Env] with ClientExt[F, Env]

trait Handler[F[_], Env, In <: HList] extends DepFn2[Env, In] {
  override final type Out = F[LOut]
  type LOut <: HList
}

object Handler {
  @implicitNotFound(
    """Cannot derive Handler[${F}, ${Env}, ${In}] { type Out = ${LOut0} }

This could depend on many things but most likely:
  - ${In} is not an HList of only laserdisc.Protocol types
  - deriving this Handler requires other type classes to be available in implicit scope

Try running scalac with -Xlog-implicits (or https://github.com/tek/splain)
"""
  ) type Aux[F[_], Env, In <: HList, LOut0 <: HList] = Handler[F, Env, In] { type LOut = LOut0 }
} 
Example 120
Source File: RESPParamWrite.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc.protocol

import shapeless._
import shapeless.labelled.FieldType

import scala.annotation.implicitNotFound

@implicitNotFound(
  """Implicit not found RESPParamWrite[${A}].

Normally you would not need to define one manually, as one will be derived for you automatically iff:
- an instance of Show[${A}] is in scope
- ${A} is a List whose LUB has a RESPParamWrite instance defined
- ${A} is an HList whose elements all have a RESPParamWrite instance defined
"""
) trait RESPParamWrite[A] {
  def write(a: A): Seq[GenBulk]
}

object RESPParamWrite extends RESPParamWriteInstances {
  @inline final def apply[A](implicit instance: RESPParamWrite[A]): RESPParamWrite[A] = instance

  final def const[A](thunk: =>Seq[GenBulk]): RESPParamWrite[A] =
    (_: A) => thunk
  final def instance[A](f: A => Seq[GenBulk]): RESPParamWrite[A] =
    (a: A) => f(a)
}

private[protocol] sealed trait RESPParamWriteInstances extends RESPParamWriteInstances1 {
  implicit final def showRESPParamWrite[A: Show]: RESPParamWrite[A] = RESPParamWrite.instance(a => Seq(Bulk(a)))
  implicit final def pairRESPParamWrite[A, B](
      implicit A: RESPParamWrite[A],
      B: RESPParamWrite[B]
  ): RESPParamWrite[(A, B)] =
    RESPParamWrite.instance {
      case (a, b) => A.write(a) ++ B.write(b)
    }
  implicit final def listRESPParamWrite[A](implicit A: RESPParamWrite[A]): RESPParamWrite[List[A]] =
    RESPParamWrite.instance(_.flatMap(A.write))
  implicit final def taggedRESPParamWrite[K <: Symbol, V](
      implicit K: Witness.Aux[K],
      V: RESPParamWrite[V]
  ): RESPParamWrite[FieldType[K, V]] = RESPParamWrite.instance(Bulk(K.value.name) +: V.write(_))
}

private[protocol] sealed trait RESPParamWriteInstances1 {
  implicit final val nilRESPParamWrite: RESPParamWrite[Nil.type] = RESPParamWrite.const(Seq.empty)
  implicit final val hNilRESPParamWrite: RESPParamWrite[HNil]    = RESPParamWrite.const(Seq.empty)

  implicit final def hConsRESPParamWrite[H, T <: HList](
      implicit H: RESPParamWrite[H],
      T: RESPParamWrite[T]
  ): RESPParamWrite[H :: T] =
    RESPParamWrite.instance {
      case h :: t => H.write(h) ++: T.write(t)
    }
} 
Example 121
Source File: RESPRead.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc
package protocol

import shapeless._
import shapeless.ops.coproduct._

import scala.annotation.implicitNotFound

@implicitNotFound(
  """Implicit not found RESPRead[${A}].

You should not need to define one manually, as one will be derived for you automatically iff:
- evidence of a Read instance from some sum/co-product to ${A} can be provided
- this sum/co-product is a subset of the sum-co-product for RESP
  """
) trait RESPRead[A] {
  type Sub

  def read(resp: RESP): Maybe[A]
}

object RESPRead {
  import RESP._

  final type Aux[Sub0, A] = RESPRead[A] { type Sub = Sub0 }
  final def apply[Sub, A](implicit instance: RESPRead.Aux[Sub, A]): RESPRead.Aux[Sub, A] = instance

  private[this] implicit val respInject: Inject[RESPCoproduct, RESP] =
    (resp: RESP) =>
      resp match {
        case arr: Arr   => Inl(arr)
        case bulk: Bulk => Inr(Inl(bulk))
        case err: Err   => Inr(Inr(Inl(err)))
        case NilArr     => Inr(Inr(Inr(Inl(NilArr))))
        case NullBulk   => Inr(Inr(Inr(Inr(Inl(NullBulk)))))
        case num: Num   => Inr(Inr(Inr(Inr(Inr(Inl(num))))))
        case str: Str   => Inr(Inr(Inr(Inr(Inr(Inr(Inl(str)))))))
      }

  sealed abstract class DefaultRESPRead[A <: Coproduct, B, Rest <: Coproduct](R: A ==> B)(
      implicit ev0: Basis.Aux[RESPCoproduct, A, Rest],
      ev1: Selector[Rest, Err]
  ) extends RESPRead[B] {
    override final type Sub = A
    override def read(resp: RESP): Maybe[B] =
      Coproduct[RESPCoproduct](resp).deembed match {
        case Right(R(Right(b))) => Right(b)
        case Right(R(Left(RESPDecErr(m)))) =>
          Left(RESPDecErr(s"RESP type(s) of $resp matched but failed to deserialize correctly with error $m")).widenLeft[Throwable]
        case Left(rest) =>
          rest
            .select[Err]
            .fold(Left(RESPDecErr(s"RESP type(s) did not match: $resp")).widenLeft[Throwable])(Left(_).widenLeft[Throwable])
      }
  }

  final def instance[A <: Coproduct, B, Rest <: Coproduct](R: A ==> B)(
      implicit ev0: Basis.Aux[RESPCoproduct, A, Rest],
      ev1: Selector[Rest, Err]
  ): RESPRead.Aux[A, B] = new DefaultRESPRead(R) {}

  implicit final def derive[A <: Coproduct, B, Rest <: Coproduct](
      implicit R: A ==> B,
      basis: Basis.Aux[RESPCoproduct, A, Rest],
      selector: Selector[Rest, Err]
  ): RESPRead.Aux[A, B] = new DefaultRESPRead(R) {}
} 
Example 122
Source File: Show.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc
package protocol

import eu.timepit.refined.api.Refined

import scala.annotation.implicitNotFound

@implicitNotFound(
  """Implicit not found Show[${A}].

Try writing your own, for example:

implicit final val myShow: Show[${A}] = new Show[${A}] {
  override final def show(a: ${A}): String = ???
}
"""
) trait Show[A] {
  def show(a: A): String

  final def contramap[B](f: B => A): Show[B] = Show.instance(show _ compose f)
}

object Show extends ShowInstances {
  @inline final def apply[A](implicit instance: Show[A]): Show[A] = instance

  final def const[A](s: =>String): Show[A] =
    new Show[A] {
      override def show(a: A): String = s
    }
  final def unsafeFromToString[A]: Show[A] =
    new Show[A] {
      override def show(a: A): String = a.toString
    }
  final def instance[A](f: A => String): Show[A] =
    new Show[A] {
      override def show(a: A): String = f(a)
    }
}

private[protocol] sealed trait ShowInstances {
  private[this] final val refinedDoubleCases: PartialFunction[Refined[Double, _], String] = {
    case d if d.value == Double.NegativeInfinity => "-inf"
    case d if d.value == Double.PositiveInfinity => "+inf"
    case d                                       => d.value.toString
  }

  implicit final val doubleShow: Show[Double] = Show.unsafeFromToString
  implicit final val intShow: Show[Int]       = Show.unsafeFromToString
  implicit final val longShow: Show[Long]     = Show.unsafeFromToString
  implicit final val stringShow: Show[String] = Show.instance(identity)
  implicit final val symbolShow: Show[Symbol] = Show.instance(_.name)

  implicit final val connectionNameShow: Show[ConnectionName] = Show.unsafeFromToString
  implicit final val dbIndexShow: Show[DbIndex]               = Show.unsafeFromToString
  implicit final val globPatternShow: Show[GlobPattern]       = Show.unsafeFromToString
  implicit final val hostShow: Show[Host]                     = Show.unsafeFromToString
  implicit final val indexShow: Show[Index]                   = Show.unsafeFromToString
  implicit final val keyShow: Show[Key]                       = Show.unsafeFromToString
  implicit final val latitudeShow: Show[Latitude]             = Show.unsafeFromToString
  implicit final val longitudeShow: Show[Longitude]           = Show.unsafeFromToString
  implicit final val nodeIdShow: Show[NodeId]                 = Show.unsafeFromToString
  implicit final val nonNegDoubleShow: Show[NonNegDouble]     = Show.instance(refinedDoubleCases)
  implicit final val nonNegIntShow: Show[NonNegInt]           = Show.unsafeFromToString
  implicit final val nonNegLongShow: Show[NonNegLong]         = Show.unsafeFromToString
  implicit final val nonZeroDoubleShow: Show[NonZeroDouble]   = Show.instance(refinedDoubleCases)
  implicit final val nonZeroIntShow: Show[NonZeroInt]         = Show.unsafeFromToString
  implicit final val nonZeroLongShow: Show[NonZeroLong]       = Show.unsafeFromToString
  implicit final val portShow: Show[Port]                     = Show.unsafeFromToString
  implicit final val posIntShow: Show[PosInt]                 = Show.unsafeFromToString
  implicit final val posLongShow: Show[PosLong]               = Show.unsafeFromToString
  implicit final val rangeOffsetShow: Show[RangeOffset]       = Show.unsafeFromToString
  implicit final val slotShow: Show[Slot]                     = Show.unsafeFromToString
  implicit final val stringLengthShow: Show[StringLength]     = Show.unsafeFromToString
  implicit final val validDoubleShow: Show[ValidDouble]       = Show.instance(refinedDoubleCases)
} 
Example 123
Source File: Routable.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.akkaHttp
import akka.http.scaladsl.marshalling.ToResponseMarshaller
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.Route

import scala.annotation.implicitNotFound
import scala.concurrent.Future

@implicitNotFound("could not route ${Res} knowing that result should be ${Out}")
trait Routable[Res, Out] {
  def route(res: => Res): Route
}

object Routable {

  implicit def single[A](implicit marshaller: ToResponseMarshaller[A]): Routable[A, A]         = complete(_)
  implicit def future[A](implicit marshaller: ToResponseMarshaller[A]): Routable[Future[A], A] = complete(_)
}

@implicitNotFound("could not route ${Res} knowing that result should be ${Out}")
trait RoutableIn[In, Res, Out] {
  def route(in: In, res: => Res): Route
}

object RoutableIn {
  implicit def byRoutable[Res, Out, In](implicit routable: Routable[Res, Out]): RoutableIn[In, Res, Out] =
    (_, res) => routable.route(res)
} 
Example 124
Source File: SwaggerContent.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema.swagger

import ru.tinkoff.tschema.Decompose.{Cons, Last, NotFound}
import ru.tinkoff.tschema.{Composite, Decompose, ResponseStatus}
import shapeless.Lazy
import cats.syntax.option._
import derevo.Derivation
import magnolia.{CaseClass, Magnolia, SealedTrait}
import ru.tinkoff.tschema.swagger.SwaggerContent.Content
import cats.syntax.foldable._
import cats.instances.list._

import scala.annotation.implicitNotFound

@implicitNotFound("SwaggerContent for ${T} is not found, try supply Swagger[T], e.g. using Swagger.derive")
final case class SwaggerContent[T](content: Content) {
  def collectTypes: Map[String, DescribedType] =
    content.foldLeft[Map[String, DescribedType]](Map()) { case (m, (_, ot)) => ot.foldLeft(m)(_ ++ _.collectTypes) }
}


object SwaggerContent extends Derivation[SwaggerContent] {
  type Typeclass[A] = SwaggerContent[A]

  type Content = List[(Int, Option[SwaggerType])]

  def by = BuilderBy(Nil)

  final case class BuilderBy(types: Content) extends AnyVal {
    def apply[T](implicit t: SwaggerTypeable[T], s: ResponseStatus[T] = ResponseStatus.default[T]) =
      BuilderBy((s.status -> t.typ.some) :: types)
    def of[T]: SwaggerContent[T]                                                                   = SwaggerContent[T](types)
  }

  final implicit def bySingleTypeable[T](implicit
      t: SwaggerTypeable[T],
      s: ResponseStatus[T] = ResponseStatus.default[T]
  ): SwaggerContent[T]                                              =
    SwaggerContent(List(s.status -> t.typ.some))

  final implicit val notFoundContent: SwaggerContent[NotFound.type] = SwaggerContent(List(404 -> None))
  final implicit val noneContent: SwaggerContent[None.type]         = SwaggerContent(List(404 -> None))

  def combine[T](cc: CaseClass[Typeclass, T])(implicit no: SwaggerContentNotCombineable) = no.absurd

  def dispatch[T](st: SealedTrait[Typeclass, T]): SwaggerContent[T] =
    SwaggerContent(st.subtypes.toList.foldMap(_.typeclass.content))

  def instance[T]: SwaggerContent[T] = macro Magnolia.gen[T]
}

@implicitNotFound("SwagerContent could be derived only for sealed traits")
final abstract class SwaggerContentNotCombineable {
  def absurd: Nothing
} 
Example 125
Source File: Completing.scala    From typed-schema   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.tschema
package finagle
import cats.syntax.flatMap._
import cats.{Applicative, Contravariant, Functor, Monad, MonoidK}
import com.twitter.finagle.http.{Response, Status}
import ru.tinkoff.tschema.Decompose
import ru.tinkoff.tschema.Decompose.{Cons, Last, NotFound}
import ru.tinkoff.tschema.finagle.util.message
import shapeless.Lazy
import cats.syntax.applicative._
import cats.syntax.apply._

import scala.annotation.implicitNotFound

@implicitNotFound(
  "Could not complete ${A} knowing that result should be ${Out} using ${In} in ${F}. Make sure you have appropriate serializing instance and imported complete implementation from tethysIntances, circeInstances, etc."
)
trait CompleteIn[F[_], -In, Out, A] {
  def completeIn(a: A, in: In): F[Response]

  def as[Out1]: CompleteIn[F, In, Out1, A] = this.asInstanceOf[CompleteIn[F, In, Out1, A]]
}

object CompleteIn

trait Completing[F[_], R, A] extends CompleteIn[F, Any, R, A] {
  def complete(a: A): F[Response]

  def completeIn(a: A, in: Any): F[Response] = complete(a)

  override def as[R1]: Completing[F, R1, A] = this.asInstanceOf[Completing[F, R1, A]]
}

object Completing {
  implicit def contravariant[F[_], R]: Contravariant[Completing[F, R, *]] =
    new Contravariant[Completing[F, R, *]] {
      def contramap[A, B](fa: Completing[F, R, A])(f: B => A): Completing[F, R, B] = b => fa.complete(f(b))
    }
} 
Example 126
Source File: JsonApiFormat.scala    From jsonapi-scala   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
package com.qvantel.jsonapi

import scala.annotation.implicitNotFound
import _root_.spray.json._

@implicitNotFound(msg = "Cannot find JsonApiReader or JsonApiFormat type class for ${T}")
trait JsonApiReader[T] extends RootJsonReader[T] {
  override def read(primary: JsValue): T = read(primary, Map.empty[(String, String), JsObject], Set.empty[String], "")
  def read(primary: JsValue, included: Set[JsObject]): T =
    read(primary, handleIncludes(included), Set.empty[String], "")
  def read(primary: JsValue, included: Set[JsObject], includePaths: Set[String], includePath: String): T =
    read(primary, handleIncludes(included), includePaths, includePath)
  def read(primary: JsValue,
           included: Map[(String, String), JsObject],
           includePaths: Set[String],
           includePath: String): T

  
  private[this] def handleIncludes(includes: Set[JsObject]): Map[(String, String), JsObject] = {
    import _root_.spray.json.DefaultJsonProtocol._
    import _root_.spray.json.lenses.JsonLenses._

    includes.map { json =>
      val id  = json.extract[String]('id)
      val tpe = json.extract[String]('type)

      ((id, tpe), json)
    }.toMap
  }
}

@implicitNotFound(msg = "Cannot find JsonApiWriter or JsonApiFormat type class for ${T}")
trait JsonApiWriter[T] extends RootJsonWriter[T] {
  override def write(obj: T): JsValue = write(obj, Map.empty)
  def included(obj: T, sparseFields: Map[String, List[String]] = Map.empty): Set[JsObject]
  def write(obj: T, sparseFields: Map[String, List[String]]): JsValue
}

@implicitNotFound(msg = "Cannot find JsonApiFormat type class for ${T}")
trait JsonApiFormat[T] extends JsonApiReader[T] with JsonApiWriter[T] with RootJsonFormat[T] 
Example 127
Source File: IdentifierType.scala    From warp-core   with MIT License 5 votes vote down vote up
package com.workday.warp.persistence

import scala.annotation.implicitNotFound


@implicitNotFound("Could not find an implicit value for evidence of type class IdentifierType[${T}]." +
  " You might pass an (implicit ev: IdentifierType[${T}]) parameter to your method or import ${T}Type._")
trait IdentifierType[T] {
  def methodSignature(identifier: T): String
  def idTestDefinition(identifier: T): Int
}

object IdentifierType {
  def apply[T: IdentifierType]: IdentifierType[T] = implicitly[IdentifierType[T]]
}

object IdentifierSyntax {
  implicit class IdentifierOps[I: IdentifierType](identifier: I) {
    def methodSignature: String = IdentifierType[I].methodSignature(identifier)
    def idTestDefinition: Int = IdentifierType[I].idTestDefinition(identifier)
  }
}