我將 Scala 3 的編譯器稱為庫,它會CompilationUnit在編譯后為您提供每個源代碼。This has tpdTree,聽上去應該包含型別資訊。
我正在嘗試遍歷樹以獲取任何型別的符號:
atPhase(Phases.typerPhase.next) {
// traverse unit.tpdTree...
}
樹行走的地方是這樣的:
class ValExtractor(tpes: Set[String]) extends tpd.TreeTraverser:
def isAcceptableType(tpe: Types.Type)(using ctx: Context): Boolean =
tpe.baseClasses.exists { sym =>
tpes.contains(sym.fullName.toString)
}
override def traverse(tree: tpd.Tree)(using ctx: Context): Unit =
tree match
case tpd.ValDef(name, tpt, _) if isAcceptableType(tpt.tpe) =>
println("do something")
case t: tpd.Template => this((), t.body)
case t: tpd.PackageDef => this((), t.stats)
case t: tpd.TypeDef => this((), t.rhs)
case _ => ()
end ValExtractor
我明白了
[info] assertion failed: denotation class Int invalid in run 1. ValidFor: Period(1..55, run = 2)
[info] scala.runtime.Scala3RunTime$.assertFailed(Scala3RunTime.scala:8)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.updateValidity(Denotations.scala:719)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.bringForward(Denotations.scala:744)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.toNewRun$1(Denotations.scala:803)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.current(Denotations.scala:877)
[info] dotty.tools.dotc.core.Symbols$Symbol.recomputeDenot(Symbols.scala:122)
[info] dotty.tools.dotc.core.Symbols$Symbol.computeDenot(Symbols.scala:116)
[info] dotty.tools.dotc.core.Symbols$Symbol.denot(Symbols.scala:109)
[info] dotty.tools.dotc.core.Symbols$.toDenot(Symbols.scala:502)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.updateValidity(Denotations.scala:718)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.bringForward(Denotations.scala:744)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.toNewRun$1(Denotations.scala:803)
[info] dotty.tools.dotc.core.Denotations$SingleDenotation.current(Denotations.scala:877)
[info] dotty.tools.dotc.core.Types$NamedType.computeDenot(Types.scala:2253)
[info] dotty.tools.dotc.core.Types$NamedType.denot(Types.scala:2213)
[info] dotty.tools.dotc.core.Types$NamedType.info(Types.scala:2201)
[info] dotty.tools.dotc.core.Types$TypeRef.underlying(Types.scala:2693)
[info] dotty.tools.dotc.core.Types$Type.baseClasses(Types.scala:600)
我究竟做錯了什么?
解決
就我而言,我有(using ctx: Context)我的方法,但顯然這與運行背景關系不匹配。如下明確傳遞它修復它:
atPhase(Phases.typerPhase.next) {
(new ValExtractor(valTypes.toSet)).getVals(unit.tpdTree)
}(using run.runContext)
uj5u.com熱心網友回復:
您需要在run值與創建定義時相同的背景關系中運行查詢(或者是稍后運行,但之前的運行無效)。
您看到的錯誤訊息是您在運行 1 時詢問符號的表示,這在概念上是在運行 2 中創建之前。
有關解釋運行/階段概念的視頻,請參見https://www.youtube.com/watch?v=WxyyJyB_Ssc。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/450954.html
上一篇:Scalaschema_of_json函式在spark結構化流中失敗
下一篇:Sbt組裝插件生成一個空jar
