Skip to content

Commit ee74a94

Browse files
committed
Allow nested Quotes with a different owners
This makes it possible to create `Expr`s with different owners to avoid a call to `changeOwner`. Closes #13922
1 parent 2ef89b2 commit ee74a94

File tree

9 files changed

+174
-3
lines changed

9 files changed

+174
-3
lines changed

compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2619,6 +2619,8 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
26192619

26202620
def show(using printer: Printer[Symbol]): String = printer.show(self)
26212621

2622+
def asQuotes: Nested = new QuotesImpl(using ctx.withOwner(self))
2623+
26222624
end extension
26232625

26242626
private def appliedTypeRef(sym: Symbol): TypeRepr =
@@ -2909,6 +2911,10 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler
29092911
|which has the AST representation
29102912
|${Printer.TreeStructure.show(tree)}
29112913
|
2914+
|
2915+
|
2916+
|Tip: The owner of a tree can be changed using method `Tree.changeOwner`.
2917+
|Tip: The default owner of definitions created in quotes can be changed using method `Symbol.asQuotes`.
29122918
|""".stripMargin)
29132919
case _ => traverseChildren(t)
29142920
}.traverse(tree)

library/src/scala/quoted/Quotes.scala

Lines changed: 77 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -598,14 +598,45 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
598598
def copy(original: Tree)(name: String, tpt: TypeTree, rhs: Option[Term]): ValDef
599599
def unapply(vdef: ValDef): (String, TypeTree, Option[Term])
600600

601-
/** Creates a block `{ val <name> = <rhs: Term>; <body(x): Term> }` */
601+
/** Creates a block `{ val <name> = <rhs: Term>; <body(x): Term> }`
602+
*
603+
* Usage:
604+
* ```
605+
* ValDef.let(owner, "x", rhs1) { x =>
606+
* ValDef.let(x.symbol.owner, "y", rhs2) { y =>
607+
* // use `x` and `y`
608+
* }
609+
* }
610+
* ```
611+
* @syntax markdown
612+
*/
602613
def let(owner: Symbol, name: String, rhs: Term)(body: Ref => Term): Term
603614

604-
/** Creates a block `{ val x = <rhs: Term>; <body(x): Term> }` */
615+
/** Creates a block `{ val x = <rhs: Term>; <body(x): Term> }`
616+
*
617+
* Usage:
618+
* ```
619+
* ValDef.let(owner, rhs1) { x =>
620+
* ValDef.let(owner, rhs2) { y =>
621+
* // use `x` and `y`
622+
* }
623+
* }
624+
* ```
625+
* @syntax markdown
626+
*/
605627
def let(owner: Symbol, rhs: Term)(body: Ref => Term): Term =
606628
let(owner, "x", rhs)(body)
607629

608-
/** Creates a block `{ val x1 = <terms(0): Term>; ...; val xn = <terms(n-1): Term>; <body(List(x1, ..., xn)): Term> }` */
630+
/** Creates a block `{ val x1 = <terms(0): Term>; ...; val xn = <terms(n-1): Term>; <body(List(x1, ..., xn)): Term> }`
631+
*
632+
* Usage:
633+
* ```
634+
* ValDef.let(owner, rhsList) { xs =>
635+
* ...
636+
* }
637+
* ```
638+
* @syntax markdown
639+
*/
609640
def let(owner: Symbol, terms: List[Term])(body: List[Ref] => Term): Term
610641
}
611642

@@ -1318,6 +1349,28 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
13181349
* ```scala sc:nocompile
13191350
* Block((DefDef(_, _, params :: Nil, _, Some(rhsFn(meth, paramRefs)))) :: Nil, Closure(meth, _))
13201351
* ```
1352+
*
1353+
* Usage:
1354+
* ```
1355+
* val mtpe = MethodType(List("arg1"))(_ => List(TypeRepr.of[Int]), _ => TypeRepr.of[Int])
1356+
* Lambda(owner, mtpe, {
1357+
* case (methSym, List(arg1: Term)) =>
1358+
* ValDef.let(methSym, f(arg1)) { ... }
1359+
* }
1360+
* )
1361+
* ```
1362+
*
1363+
* Usage with quotes:
1364+
* ```
1365+
* val mtpe = MethodType(List("arg1"))(_ => List(TypeRepr.of[Int]), _ => TypeRepr.of[Int])
1366+
* Lambda(owner, mtpe, {
1367+
* case (methSym, List(arg1: Term)) =>
1368+
* given Quotes = methSym.asQuotes
1369+
* '{ ... }
1370+
* }
1371+
* )
1372+
* ```
1373+
*
13211374
* @param owner: owner of the generated `meth` symbol
13221375
* @param tpe: Type of the definition
13231376
* @param rhsFn: Function that receives the `meth` symbol and the a list of references to the `params`
@@ -3780,6 +3833,27 @@ trait Quotes { self: runtime.QuoteUnpickler & runtime.QuoteMatching =>
37803833

37813834
/** Case class or case object children of a sealed trait or cases of an `enum`. */
37823835
def children: List[Symbol]
3836+
3837+
/** Returns a nested quote with this symbol as splice owner (`Symbol.spliceOwner`).
3838+
*
3839+
* Changes the owner under which the definition in a quote are created.
3840+
*
3841+
* Usage:
3842+
* ```scala
3843+
* new TreeMap:
3844+
* override def transformTerm(tree: Term)(owner: Symbol): Term =
3845+
* tree match
3846+
* case tree: Ident =>
3847+
* given Quotes = owner.asQuotes
3848+
* // Definitions contained in the quote will be owned by `owner`.
3849+
* // No need to use `changeOwner` in this case.
3850+
* '{ val x = ???; x }.asTerm
3851+
* ```
3852+
* @syntax markdown
3853+
*/
3854+
@experimental
3855+
def asQuotes: Nested
3856+
37833857
end extension
37843858
}
37853859

project/MiMaFilters.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ object MiMaFilters {
99
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.runtime.Tuples.append"),
1010
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#TypeReprMethods.substituteTypes"),
1111
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#TypeReprMethods.substituteTypes"),
12+
ProblemFilters.exclude[ReversedMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.asQuotes"),
13+
ProblemFilters.exclude[DirectMissingMethodProblem]("scala.quoted.Quotes#reflectModule#SymbolMethods.asQuotes"),
1214

1315
// Should have been added in 3.1.0
1416
// These are only allowed on imports and therefore should not be present in binaries emitted before

tests/pos-macros/i13571/Macro_1.scala

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import scala.quoted.*
2+
3+
inline def checked2[A](inline n: A): A =
4+
${ checkedImpl2[A]('{n}) }
5+
6+
private def checkedImpl2[A](n: Expr[A])(using Quotes, Type[A]): Expr[A] =
7+
import quotes.reflect.*
8+
val tree: Term = n.asTerm
9+
val acc = new TreeMap:
10+
override def transformTerm(tree: Term)(owner: Symbol): Term =
11+
tree match
12+
case Apply(Select(x, "*"), List(y)) =>
13+
given Quotes = owner.asQuotes
14+
'{
15+
val xt = ${x.asExprOf[Long]}
16+
xt
17+
}.asTerm
18+
case _ =>
19+
super.transformTerm(tree)(owner)
20+
acc.transformTerm(tree)(Symbol.spliceOwner).asExprOf[A]

tests/pos-macros/i13571/Test_2.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def test = {
2+
val u = 3L
3+
checked2(List(1L, 2L).map { k =>
4+
u * 2L
5+
})
6+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import scala.quoted.*
2+
3+
inline def checked2[A](inline n: A): A =
4+
${ checkedImpl2[A]('{n}) }
5+
6+
private def checkedImpl2[A](n: Expr[A])(using Quotes, Type[A]): Expr[A] =
7+
import quotes.reflect.*
8+
val tree: Term = n.asTerm
9+
val acc = new TreeMap:
10+
override def transformTerm(tree: Term)(owner: Symbol): Term =
11+
tree match
12+
case Apply(Select(x, "*"), List(y)) =>
13+
bindLong(x.asExprOf[Long])(using owner.asQuotes).asTerm
14+
case _ =>
15+
super.transformTerm(tree)(owner)
16+
acc.transformTerm(tree)(Symbol.spliceOwner).asExprOf[A]
17+
18+
def bindLong(expr: Expr[Long])(using Quotes): Expr[Long] =
19+
'{
20+
val xt = $expr
21+
xt
22+
}

tests/pos-macros/i13571b/Test_2.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def test = {
2+
val u = 3L
3+
checked2(List(1L, 2L).map { k =>
4+
u * 2L
5+
})
6+
}

tests/pos-macros/i13922/Macro_1.scala

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import scala.quoted.*
2+
3+
inline def optPrettyPrinter[T]: Option[T] => Option[T] =
4+
${ optPrettyPrinterImpl[T] }
5+
6+
private def optPrettyPrinterImpl[T: Type](using Quotes): Expr[Option[T] => Option[T]] = {
7+
import quotes.reflect.*
8+
9+
val tpe = TypeRepr.of[T]
10+
11+
val fn = Lambda(
12+
Symbol.spliceOwner,
13+
MethodType(List("macroVal"))(
14+
_ => List(tpe),
15+
_ => tpe
16+
),
17+
{
18+
case (m, List(arg: Term)) =>
19+
given Quotes = m.asQuotes
20+
ValDef.let(m, "v", arg) { v =>
21+
'{
22+
val vv = ${ v.asExprOf[T] }
23+
println("v=" + vv.toString())
24+
vv
25+
}.asTerm
26+
}
27+
28+
case _ =>
29+
report.errorAndAbort("Fails compile")
30+
}
31+
).asExprOf[T => T]
32+
33+
'{ (_: Option[T]).map(${ fn }) }
34+
}

tests/pos-macros/i13922/Test_2.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
def test = optPrettyPrinter(Some("foo"))

0 commit comments

Comments
 (0)