Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Experiment: refine macro in Scala 3 #921

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,48 @@ package object refined {
*/
def refineV[P]: RefinePartiallyApplied[Refined, P] = RefType.refinedRefType.refine[P]

trait Predicate[T, P] {
inline def isValid(inline t: T): Boolean
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm giving this a try in armanbilge/lucuma-core#1. Interestingly I had to add transparent to make it work.

}

class Positive1
object Positive1 {
inline given Predicate[Int, Positive1] with
inline def isValid(inline t: Int): Boolean = t > 0
}

class Greater1[N]
object Greater1 {
inline given [N <: Int]: Predicate[Int, Greater1[N]] with
inline def isValid(inline t: Int): Boolean = t > scala.compiletime.constValue[N]
}
/*
Does not work with 3.0.0:
scala> refineMV[Int, Greater1[2]](5)
1 |refineMV[Int, Greater1[2]](5)
|^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|Cannot reduce `inline if` because its condition is not a constant value: {
| val given_Predicate_Int_Greater1_this:
| eu.timepit.refined.Greater1.given_Predicate_Int_Greater1[(2 : Int)]
| = eu.timepit.refined.Greater1.given_Predicate_Int_Greater1[(2 : Int)]
| true:Boolean
|}
| This location contains code that was inlined from package.scala:42
*/


class NonEmpty1
object NonEmpty1 {
inline given Predicate[String, NonEmpty1] with
inline def isValid(inline s: String): Boolean = !(s == "")
// If we use !s.isEmpty here, we get the following compile error:
// |Cannot reduce `inline if` because its condition is not a constant value: "hello".isEmpty().unary_! :Boolean
}

inline def refineMV[T, P](inline t: T)(using inline p: Predicate[T, P]): Refined[T, P] = {
inline if (p.isValid(t)) Refined.unsafeApply(t) else scala.compiletime.error("no")
}

/**
* Alias for `[[api.RefType.refine]][P]` with `shapeless.tag.@@` as type
* parameter for `[[api.RefType]]`.
Expand Down