eu.timepit.refined.api.Validate Scala Examples

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

import eu.timepit.refined.api.Validate
import eu.timepit.refined.boolean.Or


  type LetterOrDigit = Letter Or Digit

  object Digit {
    implicit def digitValidate: Validate.Plain[Char, Digit] =
      Validate.fromPredicate(_.isDigit, t => s"isDigit('$t')", Digit())
  }

  object Letter {
    implicit def letterValidate: Validate.Plain[Char, Letter] =
      Validate.fromPredicate(_.isLetter, t => s"isLetter('$t')", Letter())
  }

  object LowerCase {
    implicit def lowerCaseValidate: Validate.Plain[Char, LowerCase] =
      Validate.fromPredicate(_.isLower, t => s"isLower('$t')", LowerCase())
  }

  object UpperCase {
    implicit def upperCaseValidate: Validate.Plain[Char, UpperCase] =
      Validate.fromPredicate(_.isUpper, t => s"isUpper('$t')", UpperCase())
  }

  object Whitespace {
    implicit def whitespaceValidate: Validate.Plain[Char, Whitespace] =
      Validate.fromPredicate(_.isWhitespace, t => s"isWhitespace('$t')", Whitespace())
  }
} 
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: TapirCodecRefined.scala    From tapir   with Apache License 2.0 5 votes vote down vote up
package sttp.tapir.codec.refined

import sttp.tapir._
import eu.timepit.refined.api.{Refined, Validate}
import eu.timepit.refined.collection.NonEmpty
import eu.timepit.refined.refineV
import eu.timepit.refined.string.MatchesRegex
import eu.timepit.refined.numeric.{Greater, GreaterEqual, Less, LessEqual}
import shapeless.Witness

import scala.reflect.ClassTag

trait TapirCodecRefined extends LowPriorityValidatorForPredicate {
  implicit def codecForRefined[R, V, P, CF <: CodecFormat](implicit
      tm: Codec[R, V, CF],
      refinedValidator: Validate[V, P],
      refinedValidatorTranslation: ValidatorForPredicate[V, P]
  ): Codec[R, V Refined P, CF] = {
    implicitly[Codec[R, V, CF]]
      .validate(
        refinedValidatorTranslation.validator
      ) // in reality if this validator has to fail, it will fail before in mapDecode while trying to construct refined type
      .mapDecode { v: V =>
        refineV[P](v) match {
          case Right(refined) => DecodeResult.Value(refined)
          case Left(errorMessage) =>
            DecodeResult.InvalidValue(refinedValidatorTranslation.validationErrors(v, errorMessage))
        }
      }(_.value)
  }

  //

  implicit def validatorFromPredicate[V, P](implicit vfp: ValidatorForPredicate[V, P]): Validator[V Refined P] =
    vfp.validator.contramap(_.value)

  //

  implicit val validatorForNonEmptyString: ValidatorForPredicate[String, NonEmpty] =
    ValidatorForPredicate.fromPrimitiveValidator[String, NonEmpty](Validator.minLength(1))

  implicit def validatorForMatchesRegexp[S <: String](implicit
      ws: Witness.Aux[S]
  ): ValidatorForPredicate[String, MatchesRegex[S]] =
    ValidatorForPredicate.fromPrimitiveValidator(Validator.pattern(ws.value))

  implicit def validatorForLess[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): ValidatorForPredicate[N, Less[NM]] =
    ValidatorForPredicate.fromPrimitiveValidator(Validator.max(ws.value, exclusive = true))

  implicit def validatorForLessEqual[N: Numeric, NM <: N](implicit
      ws: Witness.Aux[NM]
  ): ValidatorForPredicate[N, LessEqual[NM]] =
    ValidatorForPredicate.fromPrimitiveValidator(Validator.max(ws.value))

  implicit def validatorForGreater[N: Numeric, NM <: N](implicit ws: Witness.Aux[NM]): ValidatorForPredicate[N, Greater[NM]] =
    ValidatorForPredicate.fromPrimitiveValidator(Validator.min(ws.value, exclusive = true))

  implicit def validatorForGreaterEqual[N: Numeric, NM <: N](implicit
      ws: Witness.Aux[NM]
  ): ValidatorForPredicate[N, GreaterEqual[NM]] =
    ValidatorForPredicate.fromPrimitiveValidator(Validator.min(ws.value))
}

trait ValidatorForPredicate[V, P] {
  def validator: Validator[V]
  def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]]
}

object ValidatorForPredicate {
  def fromPrimitiveValidator[V, P](v: Validator.Primitive[V]): ValidatorForPredicate[V, P] =
    new ValidatorForPredicate[V, P] {
      override def validator: Validator[V] = v
      override def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]] = List(ValidationError[V](v, value))
    }
}

trait LowPriorityValidatorForPredicate {
  implicit def genericValidatorForPredicate[V, P: ClassTag](implicit
      refinedValidator: Validate[V, P]
  ): ValidatorForPredicate[V, P] =
    new ValidatorForPredicate[V, P] {
      override val validator: Validator.Custom[V] = Validator.Custom(
        refinedValidator.isValid,
        implicitly[ClassTag[P]].runtimeClass.toString
      ) //for the moment there is no way to get a human description of a predicate/validator without having a concrete value to run it

      override def validationErrors(value: V, refinedErrorMessage: String): List[ValidationError[_]] =
        List(ValidationError[V](validator.copy(message = refinedErrorMessage), value))
    }
} 
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: types.scala    From laserdisc   with MIT License 5 votes vote down vote up
package laserdisc

final case class ControlChar()
object ControlChar {
  import eu.timepit.refined.api.Validate

  implicit final val controlCharValidate: Validate.Plain[Char, ControlChar] =
    Validate.fromPredicate(_.isControl, t => s"isControl('$t')", ControlChar())
}

final case class KV[A](key: Key, value: A)
final case class ScanKV(cursor: NonNegLong, maybeValues: Option[Seq[KV[String]]])
final case class Scan[A](cursor: NonNegLong, values: Option[Seq[A]])
final case class Time(timestamp: NonNegLong, elapsedMicroseconds: NonNegLong)

sealed trait Direction
object Direction {
  final object asc  extends Direction
  final object desc extends Direction

  implicit val directionShow: Show[Direction] = Show.instance {
    case `asc`  => "ASC"
    case `desc` => "DESC"
  }
} 
Example 6
Source File: NumericCodecs.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.refined.codec

import eu.timepit.refined.boolean.And
import eu.timepit.refined.api.Validate
import skunk.Codec
import skunk.data.Type
import eu.timepit.refined._
import eu.timepit.refined.api.Refined

trait Scale[N]
trait Precision[N]

trait NumericCodecs {

  def validateScale[N <: Int](n: Int): Validate.Plain[BigDecimal, Scale[N]] =
    Validate.fromPredicate[BigDecimal, Scale[N]](
      _.scale <= n, d => s"($d has scale ≤ $n)", new Scale[N] {})

  def validatePrecision[N <: Int](n: Int): Validate.Plain[BigDecimal, Precision[N]] =
    Validate.fromPredicate[BigDecimal, Precision[N]](
      _.precision <= n, d => s"($d has precision ≤ $n)", new Precision[N] {})

  implicit class NumericOps(num: Codec[BigDecimal]) {
    def apply[S <: Int, P <: Int](precision: P, scale: S): Codec[BigDecimal Refined (Precision[P] And Scale[S])] = {
      implicit val __s: Validate.Plain[BigDecimal, Scale[S]] = validateScale(scale)
      implicit val __p: Validate.Plain[BigDecimal, Precision[P]] = validatePrecision(precision)
      Codec.simple(
        bd => bd.toString,
        st => refineV[Precision[P] And Scale[S]](BigDecimal(st)),
        Type.numeric
      )
    }
  }

  skunk.codec.numeric.numeric(3, 4)

}

object numeric extends NumericCodecs 
Example 7
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 8
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 9
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 10
Source File: Issue231.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.issues

import eu.timepit.refined.TestUtils._
import eu.timepit.refined.api.Validate
import eu.timepit.refined.auto._
import org.scalacheck.Properties
import shapeless.tag.@@
import shapeless.test.illTyped

final case class CrashOnTypeTag[A]()

object CrashOnTypeTag {
  implicit def crashValidate[A: reflect.runtime.universe.TypeTag]
      : Validate.Plain[String, CrashOnTypeTag[A]] =
    Validate.fromPredicate(_ => true, _ => "check failed", CrashOnTypeTag[A]())
}

class Issue231 extends Properties("issue/231") {

  property("CrashOnTypeTag[String]") = wellTyped {
    illTyped(
      """ val crash: String @@ CrashOnTypeTag[String] = "function" """,
      ".*java.lang.ClassNotFoundException.*"
    )
  }

  property("CrashOnTypeTag[Int => String]") = wellTyped {
    illTyped(
      """ val crash: String @@ CrashOnTypeTag[Int => String] = "function" """,
      ".*java.lang.ClassNotFoundException.*"
    )
  }
} 
Example 11
Source File: ImplicitScopeSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.{Inference, Validate}
import org.scalacheck.Properties


class ImplicitScopeSpec extends Properties("implicit scope") {

  property("Validate[Char, LetterOrDigit]") = wellTyped {
    Validate[Char, char.LetterOrDigit]
  }

  property("Validate[Int, Positive]") = wellTyped {
    Validate[Int, numeric.Positive]
  }

  property("Validate[Int, NonPositive]") = wellTyped {
    Validate[Int, numeric.NonPositive]
  }

  property("Validate[Int, Interval.Closed[0, 10]]") = wellTyped {
    Validate[Int, numeric.Interval.Closed[W.`0`.T, W.`10`.T]]
  }

  property("Inference[And[UpperCase, Letter], And[Letter, UpperCase]]") = wellTyped {
    Inference[boolean.And[char.UpperCase, char.Letter], boolean.And[char.Letter, char.UpperCase]]
  }

  property("Inference[Greater[1], Greater[0]]") = wellTyped {
    Inference[numeric.Greater[W.`1`.T], numeric.Greater[W.`0`.T]]
  }
} 
Example 12
Source File: TestUtils.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Validate
import org.scalacheck.Prop

object TestUtils {

  def isValid[P]: IsValidPartiallyApplied[P] = new IsValidPartiallyApplied

  class IsValidPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): Boolean = v.isValid(t)
  }

  def notValid[P]: NotValidPartiallyApplied[P] = new NotValidPartiallyApplied

  class NotValidPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): Boolean = v.notValid(t)
  }

  def validate[P]: ValidatePartiallyApplied[P] = new ValidatePartiallyApplied

  class ValidatePartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): v.Res = v.validate(t)
  }

  def showExpr[P]: ShowExprPartiallyApplied[P] = new ShowExprPartiallyApplied

  class ShowExprPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): String = v.showExpr(t)
  }

  def showResult[P]: ShowResultPartiallyApplied[P] = new ShowResultPartiallyApplied

  class ShowResultPartiallyApplied[P] {
    def apply[T](t: T)(implicit v: Validate[T, P]): String = v.showResult(t, v.validate(t))
  }

  def wellTyped[A](body: => A): Prop = Prop.secure {
    body
    true
  }

  def getClassFile[C](c: C): String =
    c.getClass.getCanonicalName.replace('.', '/') + ".class"

  def getClassFilePath[C](c: C): java.net.URL =
    getClass.getClassLoader.getResource(getClassFile(c))

  def javapOutput[C](c: C, opts: String = ""): String =
    scala.sys.process
      .Process(s"javap $opts ${getClassFilePath(c)}")
      .!!
      .trim
      .replaceAll("""(?m)\s+$""", "")
} 
Example 13
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 14
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 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: 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 17
Source File: byteVector.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined.scodec

import eu.timepit.refined.api.Validate
import eu.timepit.refined.collection.Size
import eu.timepit.refined.internal.Resources
import scodec.bits.ByteVector


object byteVector extends ByteVectorValidate

private[refined] trait ByteVectorValidate {
  implicit def byteVectorSizeValidate[P, RP](
      implicit v: Validate.Aux[Long, P, RP]
  ): Validate.Aux[ByteVector, Size[P], Size[v.Res]] =
    new Validate[ByteVector, Size[P]] {
      override type R = Size[v.Res]

      override def validate(t: ByteVector): Res = {
        val r = v.validate(t.size)
        r.as(Size(r))
      }

      override def showExpr(t: ByteVector): String =
        v.showExpr(t.size)

      override def showResult(t: ByteVector, r: Res): String = {
        val size = t.size
        val nested = v.showResult(size, r.detail.p)
        Resources.predicateTakingResultDetail(s"size($t) = $size", r, nested)
      }
    }
} 
Example 18
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 19
Source File: EvalValidateSpec.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.TestUtils.wellTyped
import eu.timepit.refined.api.Validate
import eu.timepit.refined.eval.Eval
import org.scalacheck.Prop._
import org.scalacheck.Properties
import scala.tools.reflect.ToolBoxError
import shapeless.test.illTyped

class EvalValidateSpec extends Properties("EvalValidate") {

  type IsEven = Eval[W.`"(x: Int) => x % 2 == 0"`.T]

  property("Eval.isValid") = {
    val v = Validate[Int, IsEven]
    forAll((i: Int) => v.isValid(i) ?= (i % 2 == 0))
  }

  property("Eval.showExpr") = secure {
    Validate[Int, IsEven].showExpr(0) ?= "(x: Int) => x % 2 == 0"
  }

  property("Eval.refineMV") = wellTyped {
    refineMV[IsEven](2)
    illTyped("refineMV[IsEven](3)", "Predicate.*fail.*")
  }

  property("Eval.refineV.no parameter type") = {
    val v = Validate[List[Int], Eval[W.`"_.headOption.fold(false)(_ > 0)"`.T]]
    forAll((l: List[Int]) => v.isValid(l) ?= l.headOption.fold(false)(_ > 0))
  }

  property("Eval.refineMV.scope") = wellTyped {
    val two = 2
    illTyped(
      """refineMV[Eval[W.`"(x: Int) => x >= two"`.T]](2)""",
      "exception during macro expansion.*"
    )
  }

  property("Eval.refineV.scope") = secure {
    val two = 2
    throws(classOf[ToolBoxError])(refineV[Eval[W.`"(x: Int) => x >= two"`.T]](two))
  }
} 
Example 20
Source File: eval.scala    From refined   with MIT License 5 votes vote down vote up
package eu.timepit.refined

import eu.timepit.refined.api.Validate
import scala.reflect.runtime.currentMirror
import scala.tools.reflect.ToolBox
import shapeless.Witness

object eval {

  
  final case class Eval[S](s: S)

  object Eval {
    // Cache ToolBox for Eval Validate instances
    private lazy val toolBox = currentMirror.mkToolBox()

    implicit def evalValidate[T, S <: String](
        implicit mt: Manifest[T],
        ws: Witness.Aux[S]
    ): Validate.Plain[T, Eval[S]] = {
      // The ascription (T => Boolean) allows to omit the parameter
      // type in ws.value (i.e. "x => ..." instead of "(x: T) => ...").
      val tree = toolBox.parse(s"(${ws.value}): ($mt => Boolean)")

      val predicate = toolBox.eval(tree).asInstanceOf[T => Boolean]
      Validate.fromPredicate(predicate, _ => ws.value, Eval(ws.value))
    }
  }
} 
Example 21
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 22
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 23
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)
      }
    }
}