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

Parents Manipulation Example #20

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions build.sc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ object outOfScopeTypeParam extends DottyModule
object outOfScopeClassConstructor extends DottyModule
object buildingCustomASTs extends DottyModule
object contextParamResolution extends DottyModule
object newWith extends DottyModule

object test extends Module {
def all = List(
Expand Down
Empty file added newWith/README.md
Empty file.
15 changes: 15 additions & 0 deletions newWith/src/Test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
class Base:
def say() = println(value)
def value = "World"

trait Foo:
this: Base =>
override def value = "Me"

trait Bar:
this: Base =>
override def value = "Stuff"

@main def Test =
val instance = mcr[Bar]
instance.say()
32 changes: 32 additions & 0 deletions newWith/src/macro.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import scala.quoted.*

inline def mcr[T]: Base = ${ mcrImpl[T] }
def mcrImpl[T: Type](using Quotes): Expr[Base] =
import quotes.reflect.*

class MyTreeMap extends TreeMap:
override def transformStatement(tree: Statement)(owner: Symbol): Statement =
println(s"Traversing tree ${tree.getClass}")
tree match
case t@ClassDef(name, constr, parents, selfOpt, body) =>
ClassDef.copy(t)(name, constr, parents :+ TypeTree.of[T], selfOpt, body)
case _ =>
super.transformStatement(tree)(owner)

override def transformTerm(tree: Term)(owner: Symbol): Term =
tree match
case Typed(expr, tpt) =>
val newTpe = tpt.tpe match
case t@AndType(base, foo) => AndType(t, TypeTree.of[T].tpe)
val newTpt = Inferred(newTpe)
Typed(expr, newTpt)
case _ =>
super.transformTerm(tree)(owner)
end MyTreeMap

val expr = '{new Base with Foo}
val newTree = new MyTreeMap().transformTree(expr.asTerm)(Symbol.spliceOwner)
val newExpr = newTree.asExpr
println(newExpr.show)
println(newTree.show(using Printer.TreeStructure))
newExpr.asExprOf[Base]