Skip to content

Commit dcced58

Browse files
committed
feat: introduce a static cast to scala.compiletime
1 parent 96849c4 commit dcced58

File tree

4 files changed

+37
-0
lines changed

4 files changed

+37
-0
lines changed

library/src/scala/compiletime/package.scala

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,15 @@ def byName[T](x: => T): T = x
193193
*/
194194
extension [T](x: T)
195195
transparent inline def asMatchable: x.type & Matchable = x.asInstanceOf[x.type & Matchable]
196+
197+
extension (inline self: Any)
198+
/**
199+
* TODO: Write the scaladoc here and how it works
200+
* ???
201+
* @param self ???
202+
* @param T ???
203+
* @return ???
204+
*/
205+
transparent inline def as[T]: T = inline self match
206+
case self: T => self
207+
case _ => error("Cannot statically prove the correctness of the cast")

tests/neg/static-cast.check

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
-- Error: tests/neg/static-cast.scala:11:18 ----------------------------------------------------------------------------
2+
11 |val _ = singletons[B, (A.A1.type, A.A2.type, A.A3.type)] // error
3+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
4+
| Cannot statically prove the correctness of the cast

tests/neg/static-cast.scala

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import scala.compiletime.*
2+
3+
trait B
4+
enum A { case A1, A2, A3 }
5+
6+
private inline def singletons[T, Elem <: Tuple]: Seq[T] =
7+
inline erasedValue[Elem] match
8+
case _: EmptyTuple => Seq.empty
9+
case _: (h *: t) => valueOf[h](using summonInline).as[T] +: singletons[T, t]
10+
11+
val _ = singletons[B, (A.A1.type, A.A2.type, A.A3.type)] // error

tests/pos/static-cast.scala

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import scala.compiletime.*
2+
3+
enum A { case A1, A2, A3 }
4+
5+
private inline def singletons[T, Elem <: Tuple]: Seq[T] =
6+
inline erasedValue[Elem] match
7+
case _: EmptyTuple => Seq.empty
8+
case _: (h *: t) => valueOf[h](using summonInline).as[T] +: singletons[T, t]
9+
10+
val x = singletons[A, (A.A1.type, A.A2.type, A.A3.type)]

0 commit comments

Comments
 (0)