Skip to content

Commit 56c8e7b

Browse files
Merge pull request scala#9516 from szeiger/wip/macro-classloader
Provide a context ClassLoader to macros
2 parents 9ef5859 + 487163f commit 56c8e7b

File tree

3 files changed

+31
-7
lines changed

3 files changed

+31
-7
lines changed

compiler/src/dotty/tools/dotc/transform/Splicer.scala

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,19 @@ object Splicer {
4444
val macroOwner = newSymbol(ctx.owner, nme.MACROkw, Macro | Synthetic, defn.AnyType, coord = tree.span)
4545
try
4646
inContext(ctx.withOwner(macroOwner)) {
47-
val interpreter = new Interpreter(pos, classLoader)
48-
49-
// Some parts of the macro are evaluated during the unpickling performed in quotedExprToTree
50-
val interpretedExpr = interpreter.interpret[scala.quoted.QuoteContext => scala.quoted.Expr[Any]](tree)
51-
val interpretedTree = interpretedExpr.fold(tree)(macroClosure => PickledQuotes.quotedExprToTree(macroClosure(QuoteContext())))
52-
53-
checkEscapedVariables(interpretedTree, macroOwner)
47+
val oldContextClassLoader = Thread.currentThread().getContextClassLoader
48+
Thread.currentThread().setContextClassLoader(classLoader)
49+
try {
50+
val interpreter = new Interpreter(pos, classLoader)
51+
52+
// Some parts of the macro are evaluated during the unpickling performed in quotedExprToTree
53+
val interpretedExpr = interpreter.interpret[scala.quoted.QuoteContext => scala.quoted.Expr[Any]](tree)
54+
val interpretedTree = interpretedExpr.fold(tree)(macroClosure => PickledQuotes.quotedExprToTree(macroClosure(QuoteContext())))
55+
56+
checkEscapedVariables(interpretedTree, macroOwner)
57+
} finally {
58+
Thread.currentThread().setContextClassLoader(oldContextClassLoader)
59+
}
5460
}.changeOwner(macroOwner, ctx.owner)
5561
catch {
5662
case ex: CompilationUnit.SuspendException =>
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
object Caller {
2+
Macro.f
3+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import java.net.URLClassLoader
2+
3+
import scala.quoted._
4+
5+
object Macro { self =>
6+
inline def f: Any = ${ impl }
7+
8+
def impl(using QuoteContext): Expr[Any] = {
9+
//println("======== "+self.getClass.getClassLoader.asInstanceOf[URLClassLoader].getURLs.mkString("; "))
10+
//println(" ====== "+Thread.currentThread().getContextClassLoader.asInstanceOf[URLClassLoader].getURLs.mkString("; "))
11+
assert(getClass.getClassLoader eq Thread.currentThread().getContextClassLoader,
12+
"Macro ClassLoader should be available as context ClassLoader")
13+
'{""}
14+
}
15+
}

0 commit comments

Comments
 (0)