Skip to content

Commit 9784cdb

Browse files
committed
WIP: migrate printlns to reporting
1 parent 1573236 commit 9784cdb

17 files changed

+97
-49
lines changed

scala3doc/src/dotty/dokka/DocContext.scala

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,47 @@ import java.io.File
77
import collection.JavaConverters._
88
import dotty.dokka.site.StaticSiteContext
99
import dotty.tools.dotc.core.Contexts._
10+
import java.io.ByteArrayOutputStream
11+
import java.io.PrintStream
1012

11-
given compilerContext(using docContext: DocContext) as Context =
13+
type CompilerContext = dotty.tools.dotc.core.Contexts.Context
14+
15+
given compilerContext(using docContext: DocContext) as CompilerContext =
1216
docContext.compilerContext
1317

1418
given docContextFromDokka(using dokkaContext: DokkaContext) as DocContext =
1519
dokkaContext.getConfiguration.asInstanceOf[DocContext]
1620

17-
case class DocContext(args: Scala3doc.Args, compilerContext: Context)
21+
val report = dotty.tools.dotc.report
22+
23+
def throwableToString(t: Throwable)(using CompilerContext): String =
24+
if ctx.settings.verbose.value then
25+
val os = new ByteArrayOutputStream
26+
t.printStackTrace(new PrintStream(os))
27+
os.toString()
28+
else s"${t.getClass.getName}: ${t.getMessage}"
29+
30+
// TODO (https://github.com/lampepfl/scala3doc/issues/238): provide proper error handling
31+
private def createMessage(
32+
msg: String, file: File, e: Throwable | Null)(using CompilerContext): String =
33+
val localizedMessage = s"$file: $msg"
34+
e match
35+
case null => localizedMessage
36+
case throwable: Throwable =>
37+
s"$localizedMessage \ncaused by: ${throwableToString(throwable)}"
38+
39+
extension (r: report.type):
40+
def error(m: String, f: File, e: Throwable | Null = null)(using CompilerContext): Unit =
41+
r.error(createMessage(m, f, e))
42+
43+
def warn(m: String, f: File, e: Throwable)(using CompilerContext): Unit =
44+
r.warning(createMessage(m, f, e))
45+
46+
def warn(m: String, f: File)(using CompilerContext): Unit =
47+
r.warning(createMessage(m, f, null))
48+
49+
50+
case class DocContext(args: Scala3doc.Args, compilerContext: CompilerContext)
1851
extends DokkaConfiguration:
1952
override def getOutputDir: File = args.output
2053
override def getCacheRoot: File = null
@@ -26,7 +59,7 @@ case class DocContext(args: Scala3doc.Args, compilerContext: Context)
2659
override def getModuleName(): String = "ModuleName"
2760
override def getModuleVersion(): String = ""
2861

29-
lazy val sourceLinks: SourceLinks = SourceLinks.load(args)
62+
lazy val sourceLinks: SourceLinks = SourceLinks.load(using this)
3063

3164
lazy val displaySourceSets = getSourceSets.toDisplaySourceSet
3265

@@ -37,7 +70,7 @@ case class DocContext(args: Scala3doc.Args, compilerContext: Context)
3770
Set(mkSourceSet.asInstanceOf[SourceSetWrapper]),
3871
args,
3972
sourceLinks
40-
))
73+
)(using compilerContext))
4174

4275
override def getPluginsConfiguration: JList[DokkaConfiguration.PluginConfiguration] =
4376
JList()

scala3doc/src/dotty/dokka/Main.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import java.nio.file.Files
1313

1414
import dotty.tools.dotc.config.Settings._
1515
import dotty.tools.dotc.config.CommonScalaSettings
16-
import dotty.tools.dotc.report
1716
import dotty.tools.dotc.core.Contexts._
1817

1918
/** Main class for the doctool.

scala3doc/src/dotty/dokka/Scala3doc.scala

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,12 @@ import collection.immutable.ArraySeq
1111

1212
import java.nio.file.Files
1313

14-
import dotty.tools.dotc.core.Contexts._
1514
import dotty.tools.dotc.config.Settings._
1615
import dotty.tools.dotc.config.CommonScalaSettings
17-
import dotty.tools.dotc.report
1816
import dotty.tools.dotc.reporting.Reporter
1917

2018

21-
class Scala3DocDokkaLogger(using Context) extends DokkaLogger:
19+
class Scala3DocDokkaLogger(using CompilerContext) extends DokkaLogger:
2220
def debug(msg: String): Unit = report.debuglog(msg)
2321

2422
// We do not want errors from dokka (that are) not critical to fail our runs
@@ -69,7 +67,7 @@ object Scala3doc:
6967
revision: Option[String] = None
7068
)
7169

72-
def run(args: Array[String])(using ctx: Context): Reporter =
70+
def run(args: Array[String])(using ctx: CompilerContext): Reporter =
7371
val parsedArgs = Scala3docArgs.extract(args.toList)
7472

7573
def listTastyFiles(f: File): Seq[File] =
@@ -90,7 +88,7 @@ object Scala3doc:
9088
ctx.reporter
9189

9290

93-
private [dokka] def run(args: Args)(using ctx: Context) =
91+
private [dokka] def run(args: Args)(using ctx: CompilerContext) =
9492
val docContext = new DocContext(args, ctx)
9593
new DokkaGenerator(docContext, docContext.logger).generate()
9694

scala3doc/src/dotty/dokka/Scala3docArgs.scala

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ import java.nio.file.Files
1313

1414
import dotty.tools.dotc.config.Settings._
1515
import dotty.tools.dotc.config.CommonScalaSettings
16-
import dotty.tools.dotc.report
17-
import dotty.tools.dotc.core.Contexts._
1816
import dotty.dokka.Scala3doc._
1917

2018
class Scala3docArgs extends SettingGroup with CommonScalaSettings:
@@ -37,7 +35,7 @@ class Scala3docArgs extends SettingGroup with CommonScalaSettings:
3735
StringSetting("-revision", "revision", "Revision (branch or ref) used to build project project", "")
3836

3937
object Scala3docArgs:
40-
def extract(args: List[String])(using Context) =
38+
def extract(args: List[String])(using CompilerContext) =
4139
val inst = new Scala3docArgs
4240
import inst._
4341
val initialSummary =

scala3doc/src/dotty/dokka/ScalaModuleCreator.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import org.jetbrains.dokka.model._
1313
import org.jetbrains.dokka.base.parsers.MarkdownParser
1414
import collection.JavaConverters._
1515
import kotlin.coroutines.Continuation
16-
import dotty.tools.dotc.core.Contexts._
1716

1817
class ScalaModuleProvider(using ctx: DocContext) extends SourceToDocumentableTranslator:
1918
override def invoke(sourceSet: DokkaSourceSet, cxt: DokkaContext, unused: Continuation[? >: DModule]) =

scala3doc/src/dotty/dokka/SourceLinks.scala

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import java.nio.file.Path
44
import java.nio.file.Paths
55
import liqp.Template
66
import dotty.dokka.model.api._
7+
import dotty.tools.dotc.core.Contexts.Context
78

89
case class SourceLink(val path: Option[Path], val urlTemplate: Template)
910

@@ -113,7 +114,11 @@ object SourceLinks:
113114
|
114115
|Template can defined only by subset of sources defined by path prefix represented by `<sub-path>`""".stripMargin
115116

116-
def load(configs: Seq[String], revision: Option[String], projectRoot: Path): SourceLinks =
117+
def load(
118+
configs: Seq[String],
119+
revision: Option[String],
120+
projectRoot: Path)(
121+
using Context): SourceLinks =
117122
// TODO ...
118123
val mappings = configs.map(str => str -> SourceLink.parse(str, revision))
119124

@@ -122,7 +127,7 @@ object SourceLinks:
122127
s"'$template': $message"
123128
}.mkString("\n")
124129

125-
if errors.nonEmpty then println(
130+
if errors.nonEmpty then report.warning(
126131
s"""Following templates has invalid format:
127132
|$errors
128133
|
@@ -132,10 +137,10 @@ object SourceLinks:
132137

133138
SourceLinks(mappings.collect {case (_, Right(link)) => link}, projectRoot)
134139

135-
def load(args: Scala3doc.Args): SourceLinks =
140+
def load(using ctx: DocContext): SourceLinks =
136141
load(
137-
args.sourceLinks,
138-
args.revision,
142+
ctx.args.sourceLinks,
143+
ctx.args.revision,
139144
// TODO (https://github.com/lampepfl/scala3doc/issues/240): configure source root
140145
Paths.get("").toAbsolutePath
141146
)

scala3doc/src/dotty/dokka/site/LoadedTemplate.scala

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,17 +17,19 @@ case class LazyEntry(getKey: String, value: () => String) extends JMapEntry[Stri
1717
lazy val getValue: Object = value()
1818
def setValue(x$0: Object): Object = ???
1919

20-
case class LoadedTemplate(templateFile: TemplateFile, children: List[LoadedTemplate], file: File):
20+
case class LoadedTemplate(
21+
templateFile: TemplateFile,
22+
children: List[LoadedTemplate],
23+
file: File):
2124

2225
private def brief(ctx: StaticSiteContext): String =
2326
try
2427
val code = Jsoup.parse(resolveToHtml(ctx).code)
2528
Option(code.select("p").first()).fold("...")(_.outerHtml())
2629
catch
2730
case e: Throwable =>
28-
// TODO (https://github.com/lampepfl/scala3doc/issues/238): provide proper error handling
29-
println(s"[ERROR] Unable to process brief for ${templateFile.file}")
30-
e.printStackTrace()
31+
val msg = s"[ERROR] Unable to process brief for ${templateFile.file}"
32+
report.error(msg, templateFile.file, e)(using ctx.outerCtx)
3133
"..."
3234

3335
def lazyTemplateProperties(ctx: StaticSiteContext): JMap[String, Object] = new java.util.AbstractMap[String, Object]():

scala3doc/src/dotty/dokka/site/SitePagesCreator.scala

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,10 @@ class SitePagesCreator(using ctx: DocContext) extends BaseStaticSiteProcessor:
3939
val apiRoot = mkRootPage(input, contentPage)
4040
val (indexes, children) = ctx.allPages.partition(f =>
4141
f.template.isIndexPage() && f.template.file.toPath.getParent() == ctx.docsPath )
42-
// TODO (https://github.com/lampepfl/scala3doc/issues/238): provide proper error handling
43-
if (indexes.size > 1) println(s"ERROR: Multiple index pages found ${indexes.map(_.template.file)}")
42+
43+
if (indexes.size > 1)
44+
val msg = s"ERROR: Multiple index pages for doc found ${indexes.map(_.template.file)}"
45+
report.error(msg)
4446

4547
def emptyContent = ctx.asContent(Text(), mkDRI(extra = "root_content")).get(0)
4648

scala3doc/src/dotty/dokka/site/StaticSiteContext.scala

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,20 @@ import util.Try
2020

2121
import scala.collection.JavaConverters._
2222

23-
class StaticSiteContext(val root: File, sourceSets: Set[SourceSetWrapper], val args: Scala3doc.Args, val sourceLinks: SourceLinks):
23+
class StaticSiteContext(
24+
val root: File,
25+
sourceSets: Set[SourceSetWrapper],
26+
val args: Scala3doc.Args, val sourceLinks: SourceLinks)(using val outerCtx: CompilerContext):
2427

2528
var memberLinkResolver: String => Option[DRI] = _ => None
2629

27-
def indexPage():Option[StaticPageNode] =
30+
def indexPage(): Option[StaticPageNode] =
2831
val files = List(new File(root, "index.html"), new File(root, "index.md")).filter { _.exists() }
29-
// TODO (https://github.com/lampepfl/scala3doc/issues/238): provide proper error handling
30-
if (files.size > 1) println(s"ERROR: Multiple root index pages found: ${files.map(_.getAbsolutePath)}")
32+
33+
if files.size > 1 then
34+
val msg = s"ERROR: Multiple root index pages found: ${files.map(_.getAbsolutePath)}"
35+
report.error(msg)
36+
3137
files.flatMap(loadTemplate(_, isBlog = false)).headOption.map(templateToPage)
3238

3339
lazy val layouts: Map[String, TemplateFile] =
@@ -102,8 +108,9 @@ class StaticSiteContext(val root: File, sourceSets: Set[SourceSetWrapper], val a
102108

103109
val processedTemplate = // Set provided name as arg in page for `docs`
104110
if from.getParentFile.toPath == docsPath && templateFile.isIndexPage() then
105-
// TODO (https://github.com/lampepfl/scala3doc/issues/238): provide proper error handling
106-
if templateFile.title != "index" then println(s"[WARN] title in $from will be overriden")
111+
if templateFile.title != "index" then
112+
report.warn("Property `title` will be overriden by project name", from)
113+
107114
templateFile.copy(title = args.name)
108115
else templateFile
109116

scala3doc/src/dotty/dokka/site/StaticSiteLocationProvider.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ class StaticSiteLocationProvider(pageNode: RootPageNode)(using ctx: DokkaContext
4242
case regex(year, month, day, name) =>
4343
rawFilePath.getParent.resolveSibling(Paths.get(year, month, day, name))
4444
case _ =>
45-
println(s"Blog file at path: $rawFilePath doesn't match desired format.")
45+
val msg = s"Relative path for blog: $rawFilePath doesn't match `yyy-mm-dd-name.md` format."
46+
report.warn(msg, page.template.file)
4647
rawFilePath.resolveSibling(pageName.substring(0, dotIndex))
4748
}
4849
blogPostPath.iterator.asScala.map(_.toString).toList.asJava

scala3doc/src/dotty/dokka/tasty/ScalaDocSupport.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@ trait ScaladocSupport { self: TastyParser =>
3535
preparsed.syntax.headOption match {
3636
case Some(commentSetting) =>
3737
CommentSyntax.parse(commentSetting).getOrElse {
38-
println(s"WARN: not a valid comment syntax: $commentSetting")
39-
println(s"WARN: Defaulting to Markdown syntax.")
38+
val msg = s"not a valid comment syntax: $commentSetting, defaulting to Markdown syntax."
39+
// we should update pos with span from documentation
40+
report.warning(msg, tree.pos)
4041
CommentSyntax.default
4142
}
4243
case None => ctx.args.defaultSyntax

scala3doc/src/dotty/dokka/tasty/TastyParser.scala

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -105,15 +105,21 @@ case class TastyParser(qctx: Quotes, inspector: DokkaTastyInspector)(using val c
105105
extends ScaladocSupport with BasicSupport with TypesSupport with ClassLikeSupport with SyntheticsSupport with PackageSupport with NameNormalizer:
106106
import qctx.reflect._
107107

108-
def processTree[T](tree: Tree)(op: => T): Option[T] = try Option(op) catch case e: Throwable => errorMsg(tree, tree.symbol.show, e)
109-
def processTreeOpt[T](tree: Tree)(op: => Option[T]): Option[T] = try op catch case e: Throwable => errorMsg(tree, tree.symbol.show, e)
110-
def processSymbol[T](sym: Symbol)(op: => T): Option[T] = try Option(op) catch case e: Throwable => errorMsg(sym, sym.show, e)
111-
112-
private def errorMsg[T](a: Any, m: => String, e: Throwable): Option[T] =
113-
val msg = try m catch case e: Throwable => a.toString
114-
println(s"ERROR: tree is faling: $msg")
115-
e.printStackTrace()
116-
throw e
108+
def processTree[T](tree: Tree)(op: => T): Option[T] = try Option(op) catch
109+
case e: Exception =>
110+
report.error(throwableToString(e), tree.pos)
111+
None
112+
def processTreeOpt[T](tree: Tree)(op: => Option[T]): Option[T] = try op catch
113+
case e: Exception =>
114+
report.error(throwableToString(e), tree.pos)
115+
None
116+
117+
def processSymbol[T](sym: Symbol)(op: => T): Option[T] = try Option(op) catch
118+
case t: Throwable =>
119+
try report.error(throwableToString(t), sym.tree.pos) catch
120+
case _: Throwable =>
121+
report.error(s"Failed to process ${sym.show}:\n${throwableToString(t)}")
122+
None
117123

118124
def parseRootTree(root: Tree): Seq[Documentable] =
119125
val docs = Seq.newBuilder[Documentable]

scala3doc/test/dotty/dokka/RaportingTest.scala

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,13 @@ import org.junit.Assert
88
import org.jsoup.Jsoup
99
import org.jsoup.nodes.Document
1010
import java.nio.charset.Charset
11-
import dotty.tools.dotc.core.Contexts._
1211

1312
class ReportingTest:
1413
import Scala3doc.Args
1514

1615
private def checkReportedDiagnostics(
1716
newArgs: Args => Args = identity,
18-
ctx: Context = testContext)(
17+
ctx: CompilerContext = testContext)(
1918
op: ReportedDiagnostics => Unit): Unit =
2019

2120
val dest = Files.createTempDirectory("test-doc")

scala3doc/test/dotty/dokka/ScaladocTest.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import scala.jdk.CollectionConverters.{ListHasAsScala, SeqHasAsJava}
1111
import org.junit.{Test, Rule}
1212
import org.junit.rules.{TemporaryFolder, ErrorCollector}
1313
import java.io.File
14-
import dotty.tools.dotc.core.Contexts._
1514

1615
abstract class ScaladocTest(val name: String):
1716
def assertions: Seq[Assertion]

scala3doc/test/dotty/dokka/SourceLinksTests.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ class SourceLinksTest:
6464
type Args = String | (String, Operation) | (String, Int) | (String, Int, Operation)
6565

6666
private def testLink(config: Seq[String], revision: Option[String])(cases: (Args, String | None.type)*): Unit =
67-
val links = SourceLinks.load(config, revision, projectRoot)
67+
val links = SourceLinks.load(config, revision, projectRoot)(using testContext)
6868
cases.foreach { case (args, expected) =>
6969
val res = args match
7070
case path: String => links.pathTo(projectRoot.resolve(path))

scala3doc/test/dotty/dokka/site/SiteGeneratationTest.scala

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import org.junit.Assert._
99
import org.jsoup.Jsoup
1010
import org.jsoup.nodes.Document
1111
import java.nio.charset.Charset
12-
import dotty.tools.dotc.core.Contexts._
1312

1413
class SiteGeneratationTest:
1514
val projectName = "Test Project Name"

scala3doc/test/dotty/dokka/testUtils.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ case class ReportedDiagnostics(errors: List[Diagnostic], warnings: List[Diagnost
1313
def infoMsgs = infos.map(_.msg.rawMessage)
1414

1515

16-
extension (c: Context) def reportedDiagnostics: ReportedDiagnostics =
16+
extension (c: CompilerContext) def reportedDiagnostics: ReportedDiagnostics =
1717
val t = c.reporter.asInstanceOf[TestReporter]
1818
ReportedDiagnostics(t.errors.result, t.warnings.result, t.infos.result)
1919

0 commit comments

Comments
 (0)