Skip to content
Merged
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions library/src-3.x/scala/quoted/Expr.scala
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ package quoted {
tg.untupled(args => new FunctionAppliedTo[R](f, args.toArray.map(_.asInstanceOf[Expr[_]])))
}

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

Copy link
Contributor

Choose a reason for hiding this comment

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

It seems this can be done using toExprList and then use quote and splices?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Functionally it can but it would not solve the recursion issue. But actually I could use this one to improve toExprOfList

Copy link
Contributor Author

Choose a reason for hiding this comment

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

By improve I mean not have a recursive implementation that nests all the trees creating an extremely deep tree.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I hit a bug trying to implement it. I will leave it for another PR.

}

}
Expand Down
10 changes: 10 additions & 0 deletions tests/run-macros/quoted-expr-block/quoted_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import scala.quoted._

inline def replicate(inline times: Int, code: => Any) = ${replicateImpl(times, 'code)}

private def replicateImpl(times: Int, code: Expr[Any]) given tasty.Reflection = {
@annotation.tailrec def loop(n: Int, accum: List[Expr[Any]]): List[Expr[Any]] =
if (n > 0) loop(n - 1, code :: accum) else accum
Expr.block(loop(times, Nil), '{})

}
8 changes: 8 additions & 0 deletions tests/run-macros/quoted-expr-block/quoted_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

object Test {
def main(args: Array[String]): Unit = {
var a = 0
replicate(500, a += 1)
assert(a == 500, a)
}
}