eu.timepit.refined.api.RefType Scala Examples

The following examples show how to use eu.timepit.refined.api.RefType. 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: ApplyRefPartiallyApplied.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.internal

import eu.timepit.refined.api.{RefType, Validate}


final class ApplyRefPartiallyApplied[FTP] {

  def apply[F[_, _], T, P](t: T)(
      implicit ev: F[T, P] =:= FTP,
      rt: RefType[F],
      v: Validate[T, P]
  ): Either[String, FTP] =
    rt.refine[P](t).right.map(ev)

  def unsafeFrom[F[_, _], T, P](t: T)(
      implicit ev: F[T, P] =:= FTP,
      rt: RefType[F],
      v: Validate[T, P]
  ): FTP =
    ev(rt.refine[P].unsafeFrom(t))
} 
Example 2
Source File: DecodingInstances.scala    From phobos   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.phobos.refined.decoding

import eu.timepit.refined.api.{RefType, Validate}
import ru.tinkoff.phobos.decoding._
import cats.syntax.either._
import scala.reflect.runtime.universe.TypeTag

trait DecodingInstances {
  implicit def refinedTextDecoder[F[_, _], T: TypeTag, P: TypeTag](
      implicit underlying: TextDecoder[T],
      refType: RefType[F],
      validate: Validate[T, P]
  ): TextDecoder[F[T, P]] = {
    underlying.emap { (history, raw) =>
      refType.refine[P](raw).leftMap(mkDecodingError[T, P](raw, _, history))
    }
  }

  implicit def refinedElementDecoder[F[_, _], T: TypeTag, P: TypeTag](
      implicit underlying: ElementDecoder[T],
      refType: RefType[F],
      validate: Validate[T, P]
  ): ElementDecoder[F[T, P]] = {
    underlying.emap { (history, raw) =>
      refType.refine[P](raw).leftMap(mkDecodingError[T, P](raw, _, history))
    }
  }

  private def mkDecodingError[T: TypeTag, P: TypeTag](
      rawValue: T,
      error: String,
      history: List[String]
  ): DecodingError = {
    val T = implicitly[TypeTag[T]].tpe.toString
    val P = implicitly[TypeTag[P]].tpe.toString

    DecodingError(
      s"Failed to verify $P refinement for value=$rawValue of raw type $T: $error",
      history
    )
  }
} 
Example 3
Source File: EncodingInstances.scala    From phobos   with Apache License 2.0 5 votes vote down vote up
package ru.tinkoff.phobos.refined.encoding

import eu.timepit.refined.api.RefType
import ru.tinkoff.phobos.encoding._

trait EncodingInstances {
  implicit def refinedTextEncoder[F[_, _], T, P](
      implicit underlying: TextEncoder[T],
      refType: RefType[F]
  ): TextEncoder[F[T, P]] =
    underlying.contramap(refType.unwrap)

  implicit def refinedElementEncoder[F[_, _], T, P](
      implicit underlying: ElementEncoder[T],
      refType: RefType[F]
  ): ElementEncoder[F[T, P]] = underlying.contramap(refType.unwrap)
} 
Example 4
Source File: package.scala    From zio-config   with Apache License 2.0 5 votes vote down vote up
package zio.config

import eu.timepit.refined.api.{ RefType, Refined, Validate }

package object refined
    extends NumericSupport
    with StringSupport
    with CharSupport
    with BooleanSupport
    with CollectionSupport {

  
  def asRefined[A, P](
    desc: ConfigDescriptor[A]
  )(
    implicit ev: Validate[A, P]
  ): ConfigDescriptor[Refined[A, P]] =
    desc
      .xmapEither[Refined[A, P]](
        RefType.applyRef[Refined[A, P]](_),
        rf => Right(rf.value)
      )
} 
Example 5
Source File: ApiConfigGenerators.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.tapir.config

import com.wegtam.books.pfhais.tapir.{ NonEmptyString, PortNumber }
import eu.timepit.refined.api.RefType
import eu.timepit.refined.auto._
import org.scalacheck.{ Arbitrary, Gen }

object ApiConfigGenerators {
  val DefaultHost: NonEmptyString = "api.example.com"
  val DefaultPort: PortNumber     = 1234

  val genApiConfig: Gen[ApiConfig] = for {
    gh <- Gen.nonEmptyListOf(Gen.alphaNumChar)
    gp <- Gen.choose(1, 65535)
    h = RefType.applyRef[NonEmptyString](gh.mkString).getOrElse(DefaultHost)
    p = RefType.applyRef[PortNumber](gp).getOrElse(DefaultPort)
  } yield ApiConfig(host = h, port = p)

  implicit val arbitraryApiConfig: Arbitrary[ApiConfig] = Arbitrary(genApiConfig)

} 
Example 6
Source File: DatabaseConfigGenerators.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.tapir.config

import com.wegtam.books.pfhais.tapir._
import eu.timepit.refined.api.RefType
import eu.timepit.refined.auto._
import org.scalacheck.{ Arbitrary, Gen }

object DatabaseConfigGenerators {
  val DefaultPassword: DatabasePassword = "secret"

  val genDatabaseConfig: Gen[DatabaseConfig] = for {
    gp <- Gen.nonEmptyListOf(Gen.alphaNumChar)
    p = RefType.applyRef[DatabasePassword](gp.mkString).getOrElse(DefaultPassword)
  } yield DatabaseConfig(
    driver = "org.postgresql.Driver",
    url = "jdbc:postgresql://localhost:5422/test-database",
    user = "tapir",
    pass = p
  )

  implicit val arbitraryDatabaseConfig: Arbitrary[DatabaseConfig] = Arbitrary(genDatabaseConfig)

} 
Example 7
Source File: ApiConfigGenerators.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.pure.config

import com.wegtam.books.pfhais.pure.{ NonEmptyString, PortNumber }
import eu.timepit.refined.api.RefType
import eu.timepit.refined.auto._
import org.scalacheck.{ Arbitrary, Gen }

object ApiConfigGenerators {
  val DefaultHost: NonEmptyString = "api.example.com"
  val DefaultPort: PortNumber     = 1234

  val genApiConfig: Gen[ApiConfig] = for {
    gh <- Gen.nonEmptyListOf(Gen.alphaNumChar)
    gp <- Gen.choose(1, 65535)
    h = RefType.applyRef[NonEmptyString](gh.mkString).getOrElse(DefaultHost)
    p = RefType.applyRef[PortNumber](gp).getOrElse(DefaultPort)
  } yield ApiConfig(host = h, port = p)

  implicit val arbitraryApiConfig: Arbitrary[ApiConfig] = Arbitrary(genApiConfig)

} 
Example 8
Source File: DatabaseConfigGenerators.scala    From pfhais   with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
package com.wegtam.books.pfhais.pure.config

import com.wegtam.books.pfhais.pure._
import eu.timepit.refined.api.RefType
import eu.timepit.refined.auto._
import org.scalacheck.{ Arbitrary, Gen }

object DatabaseConfigGenerators {
  val DefaultPassword: DatabasePassword = "secret"

  val genDatabaseConfig: Gen[DatabaseConfig] = for {
    gp <- Gen.nonEmptyListOf(Gen.alphaNumChar)
    p = RefType.applyRef[DatabasePassword](gp.mkString).getOrElse(DefaultPassword)
  } yield DatabaseConfig(
    driver = "org.postgresql.Driver",
    url = "jdbc:postgresql://localhost:5422/test-database",
    user = "pure",
    pass = p
  )

  implicit val arbitraryDatabaseConfig: Arbitrary[DatabaseConfig] = Arbitrary(genDatabaseConfig)

} 
Example 9
Source File: AcceptanceSpecData.scala    From renku   with Apache License 2.0 5 votes vote down vote up
package ch.renku.acceptancetests.tooling

import java.lang.System.getProperty

import cats.implicits._
import ch.renku.acceptancetests.model.users.UserCredentials
import ch.renku.acceptancetests.pages.GitLabPages.GitLabBaseUrl
import ch.renku.acceptancetests.pages.RenkuPage.RenkuBaseUrl
import ch.renku.acceptancetests.workflows.LoginType
import ch.renku.acceptancetests.workflows.LoginType.{LoginWithProvider, LoginWithoutProvider}
import eu.timepit.refined.api.{RefType, Refined}
import eu.timepit.refined.auto._
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.string.Url

trait AcceptanceSpecData {

  private val testsDefaults = TestsDefaults()

  protected implicit lazy val renkuBaseUrl: RenkuBaseUrl = {
    val env = Option(getProperty("env")) orElse sys.env.get("RENKU_TEST_URL") orElse testsDefaults.env
    toBaseUrl(env.get) getOrElse showErrorAndStop(
      "-Denv argument or RENKU_TEST_URL environment variable is not a valid URL"
    )
  }

  private lazy val toBaseUrl: String => Either[String, RenkuBaseUrl] = (url) => {
    val baseUrl = if (url.endsWith("/")) url.substring(0, url.length - 1) else url;
    RefType
      .applyRef[String Refined Url](baseUrl)
      .map(RenkuBaseUrl.apply)
  }

  protected implicit lazy val userCredentials: UserCredentials = {
    for {
      email    <- Option(getProperty("email")) orElse sys.env.get("RENKU_TEST_EMAIL") orElse testsDefaults.email flatMap toNonEmpty
      username <- Option(getProperty("username")) orElse sys.env.get("RENKU_TEST_USERNAME") orElse testsDefaults.username flatMap toNonEmpty
      password <- Option(getProperty("password")) orElse sys.env.get("RENKU_TEST_PASSWORD") orElse testsDefaults.password flatMap toNonEmpty
      fullName <- Option(getProperty("fullname")) orElse sys.env.get("RENKU_TEST_FULL_NAME") orElse testsDefaults.fullname flatMap toNonEmpty
      useProvider = Option(getProperty("provider")) orElse sys.env.get("RENKU_TEST_PROVIDER") match {
        case Some(s) => s.nonEmpty
        case None    => false
      }
      register = Option(getProperty("register")) orElse sys.env.get("RENKU_TEST_REGISTER") match {
        case Some(s) => s.nonEmpty
        case None    => false
      }
    } yield UserCredentials(email, username, password, fullName, useProvider, register)
  } getOrElse showErrorAndStop(
    "You must provide either the arguments -Dusername -Dfullname, -Demail or/and -Dpassword args invalid or missing" +
      " or set the environment variables RENKU_TEST_EMAIL RENKU_TEST_USERNAME RENKU_TEST_PASSWORD and/or RENKU_TEST_FULL_NAME"
  )

  private lazy val toNonEmpty: String => Option[String Refined NonEmpty] =
    RefType
      .applyRef[String Refined NonEmpty](_)
      .toOption

  private def showErrorAndStop[T](message: String Refined NonEmpty): T = {
    Console.err.println(message)
    System.exit(1)
    throw new IllegalArgumentException(message)
  }

  protected implicit def gitLabBaseUrlFrom(implicit loginType: LoginType, renkuBaseUrl: RenkuBaseUrl): GitLabBaseUrl =
    loginType match {
      case LoginWithProvider    => gitLabProviderBaseUrl(renkuBaseUrl.value)
      case LoginWithoutProvider => GitLabBaseUrl(renkuBaseUrl.value)
    }

  private def gitLabProviderBaseUrl(baseUrl: String): GitLabBaseUrl =
    if (baseUrl.endsWith("dev.renku.ch"))
      GitLabBaseUrl("https://dev.renku.ch")
    else
      GitLabBaseUrl("https://renkulab.io")

  implicit lazy val renkuCliConfig: RenkuCliConfig = RenkuCliConfig(
    version = Option(getProperty("renkuVersion"))
      .orElse(sys.env.get("RENKU_TEST_CLI_VERSION"))
      .orElse(testsDefaults.renkuVersion.some)
      .map(RenkuVersion)
      .getOrElse(showErrorAndStop("No renku cli version found")),
    installCommand = RenkuInstallCommand(testsDefaults.renkuInstallCommand)
  )
} 
Example 10
Source File: package.scala    From cormorant   with MIT License 5 votes vote down vote up
package io.chrisdavenport.cormorant

import cats.implicits._
import eu.timepit.refined.api.{RefType, Validate}

package object refined {

  implicit final def refinedPut[T, P, F[_, _]](
      implicit
      underlying: Put[T],
      refType: RefType[F]): Put[F[T, P]] = underlying.contramap(refType.unwrap)

  implicit final def refinedGet[T, P, F[_, _]](
      implicit
      underlying: Get[T],
      validate: Validate[T, P],
      refType: RefType[F]): Get[F[T, P]] = new Get[F[T, P]] {
    def get(field: CSV.Field): Either[Error.DecodeFailure, F[T, P]] =
      underlying.get(field) match {
        case Right(t) =>
          refType.refine(t) match {
            case Left(err) => Either.left(Error.DecodeFailure.single(err))
            case Right(ftp) => Either.right(ftp)
          }
        case Left(d) => Either.left(d)
      }

  }
} 
Example 11
Source File: Refinements.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package refined

import eu.timepit.refined.api.{ RefType, Validate }

import core.Refinement

object Refinements extends Refinements

trait Refinements {

  implicit def forRefType[R[_, _], A, P](implicit R: RefType[R], v: Validate[A, P], id: SemanticId[P]): Refinement.Aux[R[A, P], A] = {
    new Refinement[R[A, P]] {
      override type Repr = A
      override val uuid = id.semantics.uuid
      override def repr = id.semantics.repr
      override def from(a: A): Either[String, R[A, P]] = R.refine[P](a)
      override def to(pa: R[A, P]): A = R.unwrap(pa)
    }
  }
} 
Example 12
Source File: ReifiedInstances.scala    From seals   with Apache License 2.0 5 votes vote down vote up
package dev.tauri.seals
package refined

import eu.timepit.refined.api.RefType

import core.Refinement

object ReifiedInstances extends ReifiedInstances

trait ReifiedInstances {

  implicit def reifiedFromRefinedType[A, M <: Model, P, R[_, _]](
    implicit
    A: Reified.Aux2[A, M],
    R: RefType[R],
    refinement: Refinement.Aux[R[A, P], A],
    canRefine: Model.CanBeRefined[M]
  ): Reified.Aux[R[A, P], M, A.Fold] = A.refined[R[A, P]](refinement)
} 
Example 13
Source File: derivation.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.cats

import cats.{Contravariant, MonadError}
import eu.timepit.refined.api.{RefType, Validate}

object derivation extends DerivationInstances

trait DerivationInstances {

  
  implicit def refTypeViaMonadError[F[_, _], G[_], T, P](
      implicit
      m: MonadError[G, String],
      rt: RefType[F],
      v: Validate[T, P],
      gt: G[T]
  ): G[F[T, P]] =
    m.flatMap(gt)(t => m.fromEither(rt.refine[P](t)))
} 
Example 14
Source File: typeable.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.shapeless

import _root_.shapeless.Typeable
import eu.timepit.refined.api.{RefType, Validate}
import scala.util.Right

package object typeable {

  
  implicit def refTypeTypeable[F[_, _], T, P](
      implicit rt: RefType[F],
      V: Validate[T, P],
      T: Typeable[T],
      P: Typeable[P]
  ): Typeable[F[T, P]] =
    new Typeable[F[T, P]] {
      override def cast(t: Any): Option[F[T, P]] =
        T.cast(t)
          .flatMap(casted =>
            rt.refine[P](casted) match {
              case Right(v) => Some(v)
              case _        => None
            }
          )
      override def describe: String = s"Refined[${T.describe}, ${P.describe}]"
    }
} 
Example 15
Source File: RefineMacro.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.macros

import eu.timepit.refined.api.{RefType, Validate}
import eu.timepit.refined.char.{Digit, Letter, LowerCase, UpperCase, Whitespace}
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.internal.Resources
import eu.timepit.refined.numeric.{Negative, NonNegative, NonPositive, Positive}
import scala.reflect.macros.blackbox

class RefineMacro(val c: blackbox.Context) extends MacroUtils with LiteralMatchers {

  import c.universe._

  def impl[F[_, _], T: c.WeakTypeTag, P: c.WeakTypeTag](t: c.Expr[T])(
      rt: c.Expr[RefType[F]],
      v: c.Expr[Validate[T, P]]
  ): c.Expr[F[T, P]] = {
    val tValue: T = t.tree match {
      case Literal(Constant(value)) => value.asInstanceOf[T]
      case BigDecimalMatcher(value) => value.asInstanceOf[T]
      case BigIntMatcher(value)     => value.asInstanceOf[T]
      case _                        => abort(Resources.refineNonCompileTimeConstant)
    }

    val validate = validateInstance(v)
    val res = validate.validate(tValue)
    if (res.isFailed) {
      abort(validate.showResult(tValue, res))
    }

    refTypeInstance(rt).unsafeWrapM(c)(t)
  }

  def implApplyRef[FTP, F[_, _], T: c.WeakTypeTag, P: c.WeakTypeTag](t: c.Expr[T])(
      ev: c.Expr[F[T, P] =:= FTP],
      rt: c.Expr[RefType[F]],
      v: c.Expr[Validate[T, P]]
  ): c.Expr[FTP] =
    c.Expr[FTP](impl(t)(rt, v).tree)

  private def validateInstance[T, P](v: c.Expr[Validate[T, P]])(
      implicit
      T: c.WeakTypeTag[T],
      P: c.WeakTypeTag[P]
  ): Validate[T, P] =
    validateInstances
      .collectFirst {
        case (tpeT, instancesForT) if tpeT =:= T.tpe =>
          instancesForT.collectFirst {
            case (tpeP, validate) if tpeP =:= P.tpe =>
              validate.asInstanceOf[Validate[T, P]]
          }
      }
      .flatten
      .getOrElse(eval(v))

  private val validateInstances: List[(Type, List[(Type, Any)])] = {
    def instance[T, P](implicit P: c.WeakTypeTag[P], v: Validate[T, P]): (Type, Validate[T, P]) =
      P.tpe -> v

    List(
      weakTypeOf[Int] -> List(
        instance[Int, Positive],
        instance[Int, NonPositive],
        instance[Int, Negative],
        instance[Int, NonNegative]
      ),
      weakTypeOf[Long] -> List(
        instance[Long, Positive],
        instance[Long, NonPositive],
        instance[Long, Negative],
        instance[Long, NonNegative]
      ),
      weakTypeOf[Double] -> List(
        instance[Double, Positive],
        instance[Double, NonPositive],
        instance[Double, Negative],
        instance[Double, NonNegative]
      ),
      weakTypeOf[String] -> List(
        instance[String, NonEmpty]
      ),
      weakTypeOf[Char] -> List(
        instance[Char, Digit],
        instance[Char, Letter],
        instance[Char, LowerCase],
        instance[Char, UpperCase],
        instance[Char, Whitespace]
      )
    )
  }
} 
Example 16
Source File: InferMacro.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.macros

import eu.timepit.refined.api.Inference.==>
import eu.timepit.refined.api.RefType
import eu.timepit.refined.internal.Resources
import scala.reflect.macros.blackbox

class InferMacro(val c: blackbox.Context) extends MacroUtils {
  import c.universe._

  def impl[F[_, _], T: c.WeakTypeTag, A: c.WeakTypeTag, B: c.WeakTypeTag](ta: c.Expr[F[T, A]])(
      rt: c.Expr[RefType[F]],
      ir: c.Expr[A ==> B]
  ): c.Expr[F[T, B]] = {

    val inference = eval(ir)
    if (inference.notValid) {
      abort(Resources.invalidInference(weakTypeOf[A].toString, weakTypeOf[B].toString))
    }

    refTypeInstance(rt).unsafeRewrapM(c)(ta)
  }
} 
Example 17
Source File: MacroUtils.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.macros

import eu.timepit.refined.api.{Refined, RefType}
import scala.reflect.macros.blackbox
import scala.util.{Success, Try}
import shapeless.tag.@@

trait MacroUtils {
  val c: blackbox.Context
  import c.universe.weakTypeOf

  def abort(msg: String): Nothing =
    c.abort(c.enclosingPosition, msg)

  def eval[T](t: c.Expr[T]): T = {
    // Duplicate and untypecheck before calling `eval`, see:
    // http://www.scala-lang.org/api/2.12.0/scala-reflect/scala/reflect/macros/Evals.html#eval[T]%28expr:Evals.this.Expr[T]%29:T
    val expr = c.Expr[T](c.untypecheck(t.tree.duplicate))

    // Try evaluating expr twice before failing, see
    // https://github.com/fthomas/refined/issues/3
    tryN(2, c.eval(expr))
  }

  def tryN[T](n: Int, t: => T): T =
    Stream.fill(n)(Try(t)).collectFirst { case Success(r) => r }.getOrElse(t)

  protected def refTypeInstance[F[_, _]](rt: c.Expr[RefType[F]]): RefType[F] =
    if (rt.tree.tpe =:= weakTypeOf[RefType[Refined]])
      RefType.refinedRefType.asInstanceOf[RefType[F]]
    else if (rt.tree.tpe =:= weakTypeOf[RefType[@@]])
      RefType.tagRefType.asInstanceOf[RefType[F]]
    else
      eval(rt)
} 
Example 18
Source File: package.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import _root_.scodec._
import _root_.scodec.bits.BitVector
import eu.timepit.refined.api.{RefType, Validate}

package object scodec {

  implicit def refTypeCodec[F[_, _], T, P](
      implicit codec: Codec[T],
      refType: RefType[F],
      validate: Validate[T, P]
  ): Codec[F[T, P]] =
    new Codec[F[T, P]] {
      override def sizeBound: SizeBound =
        codec.sizeBound

      override def decode(bits: BitVector): Attempt[DecodeResult[F[T, P]]] =
        codec.decode(bits).flatMap { t =>
          refType.refine[P](t.value) match {
            case Right(tp) => Attempt.successful(DecodeResult(tp, t.remainder))
            case Left(err) => Attempt.failure(Err(err))
          }
        }

      override def encode(value: F[T, P]): Attempt[BitVector] =
        codec.encode(refType.unwrap(value))
    }
} 
Example 19
Source File: collection.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.{Refined, RefType}
import eu.timepit.refined.collection.{NonEmpty, Size}
import org.scalacheck.{Arbitrary, Gen}
import org.scalacheck.util.Buildable


object collection extends CollectionInstances with CollectionInstancesBinCompat1

trait CollectionInstances {

  implicit def listSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P](
      implicit arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[List[T], Size[P]]] =
    buildableSizeArbitrary[F, List[T], T, P]

  implicit def vectorSizeArbitrary[F[_, _]: RefType, T: Arbitrary, P](
      implicit arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[Vector[T], Size[P]]] =
    buildableSizeArbitrary[F, Vector[T], T, P]

  // This is private and not implicit because it could produce invalid
  // values for some collections:
  //
  // scala> buildableSizeArbitrary[Refined, Set[Boolean], Boolean, Equal[3]].arbitrary.sample
  // res0: Option[Refined[Set[Boolean], Size[Equal[3]]]] = Some(Set(false, true))
  private[scalacheck] def buildableSizeArbitrary[F[_, _]: RefType, C, T, P](
      implicit
      arbT: Arbitrary[T],
      arbSize: Arbitrary[Int Refined P],
      ev1: Buildable[T, C],
      ev2: C => Traversable[T]
  ): Arbitrary[F[C, Size[P]]] =
    arbitraryRefType(arbSize.arbitrary.flatMap { n =>
      Gen.buildableOfN[C, T](n.value, arbT.arbitrary)
    })
}

trait CollectionInstancesBinCompat1 {

  implicit def listNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary]
      : Arbitrary[F[List[T], NonEmpty]] =
    buildableNonEmptyArbitrary[F, List[T], T]

  implicit def vectorNonEmptyArbitrary[F[_, _]: RefType, T: Arbitrary]
      : Arbitrary[F[Vector[T], NonEmpty]] =
    buildableNonEmptyArbitrary[F, Vector[T], T]

  private[scalacheck] def buildableNonEmptyArbitrary[F[_, _]: RefType, C, T](
      implicit
      arbT: Arbitrary[T],
      ev1: Buildable[T, C],
      ev2: C => Traversable[T]
  ): Arbitrary[F[C, NonEmpty]] =
    arbitraryRefType(Gen.nonEmptyBuildableOf(arbT.arbitrary))
} 
Example 20
Source File: reftype.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.{RefinedType, RefType, Validate}
import org.scalacheck.{Arbitrary, Cogen, Gen, Prop}

object reftype extends RefTypeInstances

trait RefTypeInstances {

  def arbitraryRefType[F[_, _], T, P](gen: Gen[T])(implicit rt: RefType[F]): Arbitrary[F[T, P]] =
    Arbitrary(gen.map(rt.unsafeWrap))

  def checkArbitraryRefType[F[_, _], T, P](
      implicit arb: Arbitrary[F[T, P]],
      rt: RefType[F],
      v: Validate[T, P]
  ): Prop =
    Prop.forAll((tp: F[T, P]) => v.isValid(rt.unwrap(tp)))

  def checkArbitraryRefinedType[FTP](implicit arb: Arbitrary[FTP], rt: RefinedType[FTP]): Prop =
    Prop.forAll((tp: FTP) => rt.validate.isValid(rt.refType.unwrap(rt.dealias(tp))))

  implicit def refTypeCogen[F[_, _], T: Cogen, P](implicit rt: RefType[F]): Cogen[F[T, P]] =
    Cogen[T].contramap(tp => rt.unwrap(tp))
} 
Example 21
Source File: string.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.{Refined, RefType}
import eu.timepit.refined.collection.{NonEmpty, Size}
import eu.timepit.refined.string.{EndsWith, StartsWith, Trimmed, Uuid}
import eu.timepit.refined.types.string.TrimmedString
import org.scalacheck.Arbitrary
import shapeless.Witness


object string extends StringInstances with StringInstancesBinCompat1

trait StringInstances {

  implicit def endsWithArbitrary[F[_, _], S <: String](
      implicit rt: RefType[F],
      ws: Witness.Aux[S]
  ): Arbitrary[F[String, EndsWith[S]]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(_ + ws.value))

  implicit def startsWithArbitrary[F[_, _], S <: String](
      implicit rt: RefType[F],
      ws: Witness.Aux[S]
  ): Arbitrary[F[String, StartsWith[S]]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(ws.value + _))

  implicit def nonEmptyStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, NonEmpty]] =
    collection.buildableNonEmptyArbitrary[F, String, Char]

  implicit def stringSizeArbitrary[F[_, _]: RefType, P](
      implicit
      arbChar: Arbitrary[Char],
      arbSize: Arbitrary[Int Refined P]
  ): Arbitrary[F[String, Size[P]]] =
    collection.buildableSizeArbitrary[F, String, Char, P]

  implicit def uuidStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, Uuid]] =
    arbitraryRefType(Arbitrary.arbUuid.arbitrary.map(_.toString))
}

trait StringInstancesBinCompat1 {
  implicit def trimmedStringArbitrary[F[_, _]](
      implicit rt: RefType[F]
  ): Arbitrary[F[String, Trimmed]] =
    arbitraryRefType(Arbitrary.arbString.arbitrary.map(TrimmedString.trim(_).value))
} 
Example 22
Source File: boolean.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalacheck

import eu.timepit.refined.api.RefType
import eu.timepit.refined.boolean.Or
import org.scalacheck.{Arbitrary, Gen}


object boolean extends BooleanInstances

trait BooleanInstances {

  implicit def orArbitrary[F[_, _], T, A, B](
      implicit rt: RefType[F],
      arbA: Arbitrary[F[T, A]],
      arbB: Arbitrary[F[T, B]]
  ): Arbitrary[F[T, A Or B]] = {
    val genA = arbA.arbitrary.map(rt.unwrap)
    val genB = arbB.arbitrary.map(rt.unwrap)
    arbitraryRefType(Gen.oneOf(genA, genB))
  }
} 
Example 23
Source File: package.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import _root_.pureconfig.{ConfigConvert, ConfigCursor}
import _root_.pureconfig.error.{CannotConvert, ConfigReaderFailures, ConvertFailure}
import com.typesafe.config.ConfigValue
import eu.timepit.refined.api.{RefType, Validate}
import scala.reflect.runtime.universe.WeakTypeTag

package object pureconfig {

  implicit def refTypeConfigConvert[F[_, _], T, P](
      implicit configConvert: ConfigConvert[T],
      refType: RefType[F],
      validate: Validate[T, P],
      typeTag: WeakTypeTag[F[T, P]]
  ): ConfigConvert[F[T, P]] = new ConfigConvert[F[T, P]] {
    override def from(cur: ConfigCursor): Either[ConfigReaderFailures, F[T, P]] =
      configConvert.from(cur) match {
        case Right(t) =>
          refType.refine[P](t) match {
            case Left(because) =>
              Left(
                ConfigReaderFailures(
                  ConvertFailure(
                    reason = CannotConvert(
                      value = cur.value.render(),
                      toType = typeTag.tpe.toString,
                      because = because
                    ),
                    cur = cur
                  )
                )
              )

            case Right(refined) =>
              Right(refined)
          }

        case Left(configReaderFailures) =>
          Left(configReaderFailures)
      }

    override def to(t: F[T, P]): ConfigValue =
      configConvert.to(refType.unwrap(t))
  }
} 
Example 24
Source File: RefTypeSpecScalazTag.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scalaz

import _root_.scalaz.@@
import _root_.scalaz.std.anyVal._
import _root_.scalaz.syntax.equal._
import _root_.scalaz.syntax.show._
import eu.timepit.refined.TestUtils._
import eu.timepit.refined.api.{RefType, RefTypeSpec}
import eu.timepit.refined.numeric._
import eu.timepit.refined.scalaz.auto._
import org.scalacheck.Prop._
import shapeless.test.illTyped

class RefTypeSpecScalazTag extends RefTypeSpec[@@]("scalaz.@@") {

  property("refineM with type alias") = secure {
    type PositiveInt = Int @@ Positive

    val x: PositiveInt = RefType[@@].refineM(5)
    val y: PositiveInt = 5
    val z = 5: PositiveInt
    illTyped("val a: PositiveInt = -5", "Predicate failed: \\(-5 > 0\\).*")
    x == y && y == z
  }

  property("(T @@ P) <!: T") = wellTyped {
    illTyped("implicitly[(Int @@ Positive) <:< Int]", "Cannot prove.*")
  }

  property("scalaz.Equal") = secure {
    type PosInt = Int @@ Positive
    val x: PosInt = 5
    val y: PosInt = 5
    x === y
  }

  property("scalaz.Show") = secure {
    type PosInt = Int @@ Positive
    val x: PosInt = 5
    x.shows ?= "5"
  }
} 
Example 25
Source File: package.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import _root_.scalaz.{@@, Contravariant, Equal, MonadError, Show}
import eu.timepit.refined.api.{RefType, Validate}
import scala.reflect.macros.blackbox

package object scalaz {

  implicit val scalazTagRefType: RefType[@@] =
    new RefType[@@] {
      override def unsafeWrap[T, P](t: T): T @@ P =
        t.asInstanceOf[T @@ P]

      override def unwrap[T](tp: T @@ _): T =
        tp.asInstanceOf[T]

      override def unsafeRewrap[T, A, B](ta: T @@ A): T @@ B =
        ta.asInstanceOf[T @@ B]

      override def unsafeWrapM[T: c.WeakTypeTag, P: c.WeakTypeTag](
          c: blackbox.Context
      )(t: c.Expr[T]): c.Expr[T @@ P] =
        c.universe.reify(t.splice.asInstanceOf[T @@ P])

      override def unsafeRewrapM[T: c.WeakTypeTag, A: c.WeakTypeTag, B: c.WeakTypeTag](
          c: blackbox.Context
      )(ta: c.Expr[T @@ A]): c.Expr[T @@ B] =
        c.universe.reify(ta.splice.asInstanceOf[T @@ B])
    }

  
  implicit def refTypeShow[F[_, _], T: Show, P](implicit rt: RefType[F]): Show[F[T, P]] =
    scalaz.derivation.refTypeViaContravariant[F, Show, T, P]

  @deprecated("Generic derivation instances have been moved into the `derivation` object", "0.9.4")
  def refTypeContravariant[R[_, _], F[_], A, B](
      implicit
      C: Contravariant[F],
      R: RefType[R],
      F: F[A]
  ): F[R[A, B]] =
    scalaz.derivation.refTypeViaContravariant[R, F, A, B]

  @deprecated("Generic derivation instances have been moved into the `derivation` object", "0.9.4")
  def refTypeMonadError[R[_, _], F[_], A, B](
      implicit
      M: MonadError[F, String],
      R: RefType[R],
      V: Validate[A, B],
      F: F[A]
  ): F[R[A, B]] =
    scalaz.derivation.refTypeViaMonadError[R, F, A, B]
} 
Example 26
Source File: derivation.scala    From refined   with MIT License 5 votes vote down vote up
// Copyright: 2015 - 2018 Frank S. Thomas and Sam Halliday
// License: https://opensource.org/licenses/MIT

package eu.timepit.refined.scalaz

import eu.timepit.refined.api.{RefType, Validate}
import scalaz.{Contravariant, MonadError}

object derivation extends DerivationInstances

trait DerivationInstances {

  
  implicit def refTypeViaMonadError[F[_, _], G[_], T, P](
      implicit
      m: MonadError[G, String],
      rt: RefType[F],
      v: Validate[T, P],
      gt: G[T]
  ): G[F[T, P]] =
    m.bind(gt) { f =>
      rt.refine(f) match {
        case Left(s)    => m.raiseError(s)
        case Right(ftp) => m.pure(ftp)
      }
    }
}