Skip to content

Commit 646e433

Browse files
Merge pull request #6747 from dotty-staging/add-quoted-expr-block
Add quoted.Expr.block
2 parents e2d2e28 + 62f810b commit 646e433

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

library/src-3.x/scala/quoted/Expr.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,15 @@ package quoted {
3737
tg.untupled(args => new FunctionAppliedTo[R](f, args.toArray.map(_.asInstanceOf[Expr[_]])))
3838
}
3939

40+
/** Returns A expression containing a block with the given statements and ending with the expresion
41+
* Given list of statements `s1 :: s2 :: ... :: Nil` and an expression `e` the resulting expression
42+
* will be equivalent to `'{ $s1; $s2; ...; $e }`.
43+
*/
44+
def block[T](statements: List[Expr[_]], expr: Expr[T])(implicit refl: tasty.Reflection): Expr[T] = {
45+
import refl._
46+
Block(statements.map(_.unseal), expr.unseal).seal.asInstanceOf[Expr[T]]
47+
}
48+
4049
}
4150

4251
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import scala.quoted._
2+
3+
inline def replicate(inline times: Int, code: => Any) = ${replicateImpl(times, 'code)}
4+
5+
private def replicateImpl(times: Int, code: Expr[Any]) given tasty.Reflection = {
6+
@annotation.tailrec def loop(n: Int, accum: List[Expr[Any]]): List[Expr[Any]] =
7+
if (n > 0) loop(n - 1, code :: accum) else accum
8+
Expr.block(loop(times, Nil), '{})
9+
10+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
object Test {
3+
def main(args: Array[String]): Unit = {
4+
var a = 0
5+
replicate(500, a += 1)
6+
assert(a == 500, a)
7+
}
8+
}

0 commit comments

Comments
 (0)