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

Load docstrings lazily from TASTy #20148

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/Driver.scala
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class Driver {
Positioned.init(using ictx)

inContext(ictx) {
if !ctx.settings.YdropComments.value || ctx.settings.YreadComments.value then
if !ctx.settings.YdropComments.value then
ictx.setProperty(ContextDoc, new ContextDocstrings)
val fileNamesOrNone = command.checkUsage(summary, sourcesRequired)(using ctx.settings)(using ctx.settingsState)
fileNamesOrNone.map { fileNames =>
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/config/ScalaSettings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ private sealed trait YSettings:
val YcheckReentrant: Setting[Boolean] = BooleanSetting(ForkSetting, "Ycheck-reentrant", "Check that compiled program does not contain vars that can be accessed from a global root.")
val YdropComments: Setting[Boolean] = BooleanSetting(ForkSetting, "Ydrop-docs", "Drop documentation when scanning source files.", aliases = List("-Ydrop-comments"))
val YcookComments: Setting[Boolean] = BooleanSetting(ForkSetting, "Ycook-docs", "Cook the documentation (type check `@usecase`, etc.)", aliases = List("-Ycook-comments"))
val YreadComments: Setting[Boolean] = BooleanSetting(ForkSetting, "Yread-docs", "Read documentation from tasty.")
val YreadDocsEagerly: Setting[Boolean] = BooleanSetting(ForkSetting, "Yread-docs", "Read documentation eagerly from TASTy")
val YforceSbtPhases: Setting[Boolean] = BooleanSetting(ForkSetting, "Yforce-sbt-phases", "Run the phases used by sbt for incremental compilation (ExtractDependencies and ExtractAPI) even if the compiler is ran outside of sbt, for debugging.")
val YdumpSbtInc: Setting[Boolean] = BooleanSetting(ForkSetting, "Ydump-sbt-inc", "For every compiled foo.scala, output the API representation and dependencies used for sbt incremental compilation in foo.inc, implies -Yforce-sbt-phases.")
val YcheckAllPatmat: Setting[Boolean] = BooleanSetting(ForkSetting, "Ycheck-all-patmat", "Check exhaustivity and redundancy of all pattern matching (used for testing the algorithm).")
Expand Down
23 changes: 18 additions & 5 deletions compiler/src/dotty/tools/dotc/core/Comments.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,18 +24,31 @@ object Comments {
*/
class ContextDocstrings {

private val _docstrings: MutableSymbolMap[Comment] = MutableSymbolMap[Comment](512) // FIXME: 2nd [Comment] needed or "not a class type"
private val docstrings: MutableSymbolMap[Comment | CommentLoader] = MutableSymbolMap[Comment | CommentLoader](512) // FIXME: 2nd [Comment] needed or "not a class type"

private class CommentLoader(val load: () => Option[Comment])

val templateExpander: CommentExpander = new CommentExpander

def docstrings: ReadOnlyMap[Symbol, Comment] = _docstrings
def docstring(sym: Symbol): Option[Comment] =
docstrings.get(sym).flatMap {
case comment: Comment => Some(comment)
case commentLoader: CommentLoader =>
val commentOpt = commentLoader.load()
commentOpt match
case Some(comment) => docstrings.update(sym, comment)
case None => docstrings.remove(sym)
commentOpt
}

def docstring(sym: Symbol): Option[Comment] = _docstrings.get(sym)
def registerLoader(sym: Symbol, loader: () => Option[Comment]): Unit =
docstrings.update(sym, CommentLoader(loader))

def addDocstring(sym: Symbol, doc: Option[Comment]): Unit =
doc.foreach(d => _docstrings.update(sym, d))
def addDocstring(sym: Symbol, doc: Comment): Unit =
docstrings.update(sym, doc)
}


/**
* A `Comment` contains the unformatted docstring, it's position and potentially more
* information that is populated when the comment is "cooked".
Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/core/Definitions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2169,7 +2169,7 @@ class Definitions {
@tu lazy val LazyValsControlState = requiredClass(s"$LazyValsModuleName.LazyValControlState")

def addSyntheticSymbolsComments(using Context): Unit =
def add(sym: Symbol, doc: String) = ctx.docCtx.foreach(_.addDocstring(sym, Some(Comment(NoSpan, doc))))
def add(sym: Symbol, doc: String) = ctx.docCtx.foreach(_.addDocstring(sym, Comment(NoSpan, doc)))

add(AnyClass,
"""/** Class `Any` is the root of the Scala class hierarchy. Every class in a Scala
Expand Down
7 changes: 4 additions & 3 deletions compiler/src/dotty/tools/dotc/core/tasty/TreePickler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -366,9 +366,10 @@ class TreePickler(pickler: TastyPickler, attributes: Attributes) {
if sym.is(Method) && sym.owner.isClass then
profile.recordMethodSize(sym, (currentAddr.index - addr.index) max 1, mdef.span)
for docCtx <- ctx.docCtx do
val comment = docCtx.docstrings.lookup(sym)
if comment != null then
docStrings(mdef) = comment
docCtx.docstring(sym) match
case Some(comment) =>
docStrings(mdef) = comment
case _ =>
}

def pickleParam(tree: Tree)(using Context): Unit = {
Expand Down
13 changes: 6 additions & 7 deletions compiler/src/dotty/tools/dotc/core/tasty/TreeUnpickler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -981,13 +981,12 @@ class TreeUnpickler(reader: TastyReader,
if !sym.isType && !sym.is(ParamAccessor) then
sym.info = ta.avoidPrivateLeaks(sym)

if (ctx.settings.YreadComments.value) {
assert(ctx.docCtx.isDefined, "`-Yread-docs` enabled, but no `docCtx` is set.")
commentUnpicklerOpt.foreach { commentUnpickler =>
val comment = commentUnpickler.commentAt(start)
ctx.docCtx.get.addDocstring(tree.symbol, comment)
tree.setComment(comment)
}
commentUnpicklerOpt.foreach { commentUnpickler =>
def loadComment() = commentUnpickler.commentAt(start)
if ctx.settings.YreadDocsEagerly.value then
loadComment().foreach(doc => ctx.docCtx.get.addDocstring(tree.symbol, doc))
else
ctx.docCtx.get.registerLoader(tree.symbol, loadComment)
}

tree.setDefTree
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class IDEDecompilerDriver(val settings: List[String]) extends dotc.Driver {

private val myInitCtx: Context = {
val rootCtx = initCtx.fresh.addMode(Mode.Interactive | Mode.ReadPositions)
rootCtx.setSetting(rootCtx.settings.YreadComments, true)
rootCtx.setSetting(rootCtx.settings.YretainTrees, true)
rootCtx.setSetting(rootCtx.settings.fromTasty, true)
val ctx = setup(settings.toArray :+ "dummy.scala", rootCtx).get._2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ class InteractiveDriver(val settings: List[String]) extends Driver {
val rootCtx = initCtx.fresh.addMode(Mode.ReadPositions).addMode(Mode.Interactive)
rootCtx.setSetting(rootCtx.settings.YretainTrees, true)
rootCtx.setSetting(rootCtx.settings.YcookComments, true)
rootCtx.setSetting(rootCtx.settings.YreadComments, true)
val ctx = setup(settings.toArray, rootCtx) match
case Some((_, ctx)) => ctx
case None => rootCtx
Expand Down
1 change: 0 additions & 1 deletion compiler/src/dotty/tools/dotc/transform/Pickler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,6 @@ class Pickler extends Phase {
super.runOn(units)
if ctx.settings.YtestPickler.value then
val ctx2 = ctx.fresh
.setSetting(ctx.settings.YreadComments, true)
.setSetting(ctx.settings.YshowPrintErrors, true)
testUnpickler(
using ctx2
Expand Down
4 changes: 2 additions & 2 deletions compiler/src/dotty/tools/dotc/typer/Docstrings.scala
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ object Docstrings {
}

val commentWithUsecases = expanded.copy(usecases = typedUsecases)
docCtx.addDocstring(sym, Some(commentWithUsecases))
docCtx.addDocstring(sym, commentWithUsecases)
commentWithUsecases
}
}
Expand All @@ -52,7 +52,7 @@ object Docstrings {
val tplExp = docCtx.templateExpander
tplExp.defineVariables(sym)
val newComment = comment.expand(tplExp.expandedDocComment(sym, owner, _))
docCtx.addDocstring(sym, Some(newComment))
docCtx.addDocstring(sym, newComment)
newComment
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/src/dotty/tools/dotc/typer/Namer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ class Namer { typer: Typer =>

def setDocstring(sym: Symbol, tree: Tree)(using Context): Unit = tree match {
case t: MemberDef if t.rawComment.isDefined =>
ctx.docCtx.foreach(_.addDocstring(sym, t.rawComment))
ctx.docCtx.foreach(_.addDocstring(sym, t.rawComment.get))
case t: ExtMethods =>
for meth <- t.methods.find(_.span.point == sym.span.point) do
setDocstring(sym, meth)
Expand Down
1 change: 0 additions & 1 deletion compiler/src/dotty/tools/repl/ReplDriver.scala
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ class ReplDriver(settings: Array[String],
private def initialCtx(settings: List[String]) = {
val rootCtx = initCtx.fresh.addMode(Mode.ReadPositions | Mode.Interactive)
rootCtx.setSetting(rootCtx.settings.YcookComments, true)
rootCtx.setSetting(rootCtx.settings.YreadComments, true)
setupRootCtx(this.settings ++ settings, rootCtx)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,6 @@ class CommentPicklingTest {
}

private class UnpicklingDriver extends Driver {
override def initCtx =
val ctx = super.initCtx.fresh
ctx.setSetting(ctx.settings.YreadComments, true)
ctx

def unpickle[T](args: Array[String], files: List[File])(fn: (List[tpd.Tree], Context) => T): T = {
implicit val ctx: Context = setup(args, initCtx).map(_._2).getOrElse(initCtx)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class SnippetCompiler(
rootCtx.setSetting(rootCtx.settings.experimental, true)
rootCtx.setSetting(rootCtx.settings.YretainTrees, true)
rootCtx.setSetting(rootCtx.settings.YcookComments, true)
rootCtx.setSetting(rootCtx.settings.YreadComments, true)
rootCtx.setSetting(rootCtx.settings.YreadDocsEagerly, true)
Copy link
Contributor

Choose a reason for hiding this comment

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

What is a usage scenario where I might want readDocsEargerly?

Copy link
Contributor Author

@nicolasstucki nicolasstucki Apr 16, 2024

Choose a reason for hiding this comment

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

None. I just kept to be able to benchmark the difference in performance.

rootCtx.setSetting(rootCtx.settings.color, "never")
rootCtx.setSetting(rootCtx.settings.XimportSuggestionTimeout, 0)

Expand Down
2 changes: 1 addition & 1 deletion scaladoc/src/scala/tasty/inspector/TastyInspector.scala
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ object TastyInspector:
reset()
val ctx2 = ctx.fresh
.addMode(Mode.ReadPositions)
.setSetting(ctx.settings.YreadComments, true)
.setSetting(ctx.settings.YreadDocsEagerly, true)
new TASTYRun(this, ctx2)

new InspectorDriver
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ object TastyInspector:
reset()
val ctx2 = ctx.fresh
.addMode(Mode.ReadPositions)
.setSetting(ctx.settings.YreadComments, true)
new TASTYRun(this, ctx2)

new InspectorDriver
Expand Down
16 changes: 16 additions & 0 deletions tests/run-macros/i20106.check
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
docs from same compilation run:
Some(/**
* my doc string for Main
*
* @param tracks track listing
* */)
docs loaded from tasty:
Some(/**
* my doc string for Main
*
* @param tracks track listing
* */)
docs from same compilation run:
Some(/**
* Doc of Test
* */)
12 changes: 12 additions & 0 deletions tests/run-macros/i20106/Macro_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import scala.quoted.*

object Doc {
inline def of[A]: Option[String] = ${ ofImpl[A] }

def ofImpl[A: Type](using Quotes): Expr[Option[String]] = {
import quotes.reflect.*

val symbol = TypeRepr.of[A].typeSymbol
Expr(symbol.docstring)
}
}
14 changes: 14 additions & 0 deletions tests/run-macros/i20106/Main_1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* my doc string for Main
*
* @param tracks track listing
* */

class Main(tracks: String)

object Main {
def printdoc(): Unit = {
val docString = Doc.of[Main]
println(docString)
}
}
19 changes: 19 additions & 0 deletions tests/run-macros/i20106/Test_2.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* Doc of Test
* */
class Test

object Test {
def main(args: Array[String]): Unit = {
println("docs from same compilation run:")
Main.printdoc()

println("docs loaded from tasty:")
val docString = Doc.of[Main]
println(docString)

println("docs from same compilation run:")
val docStringTest = Doc.of[Test]
println(docStringTest)
}
}
Loading