Skip to content

Commit b742e83

Browse files
committed
Refactor: void passing strings to report.error/warning
Pass only messages, but have special interpolators that yield a message instead of a string
1 parent 73ed7f2 commit b742e83

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

63 files changed

+1130
-1104
lines changed

compiler/src/dotty/tools/backend/jvm/BCodeHelpers.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -832,8 +832,8 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters {
832832

833833
case tp =>
834834
report.warning(
835-
s"an unexpected type representation reached the compiler backend while compiling ${ctx.compilationUnit}: $tp. " +
836-
"If possible, please file a bug on https://github.com/lampepfl/dotty/issues")
835+
em"""an unexpected type representation reached the compiler backend while compiling ${ctx.compilationUnit}: $tp.
836+
|If possible, please file a bug on https://github.com/lampepfl/dotty/issues""")
837837

838838
tp match {
839839
case tp: ThisType if tp.cls == defn.ArrayClass => ObjectRef.asInstanceOf[ct.bTypes.ClassBType] // was introduced in 9b17332f11 to fix SI-999, but this code is not reached in its test, or any other test
@@ -922,7 +922,7 @@ trait BCodeHelpers extends BCodeIdiomatic with BytecodeWriters {
922922
}
923923

924924
def abort(msg: String): Nothing = {
925-
report.error(msg)
925+
report.error(msg.toMessage)
926926
throw new RuntimeException(msg)
927927
}
928928

compiler/src/dotty/tools/backend/jvm/BCodeIdiomatic.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import scala.annotation.switch
99
import Primitives.{NE, EQ, TestOp, ArithmeticOp}
1010
import scala.tools.asm.tree.MethodInsnNode
1111
import dotty.tools.dotc.report
12+
import dotc.core.Decorators.*
1213

1314
/*
1415
* A high-level facade to the ASM API for bytecode generation.
@@ -35,7 +36,7 @@ trait BCodeIdiomatic {
3536
case (Some(release), None) => release
3637
case (None, Some(target)) => target
3738
case (Some(release), Some(_)) =>
38-
report.warning(s"The value of ${ctx.settings.XuncheckedJavaOutputVersion.name} was overridden by ${ctx.settings.javaOutputVersion.name}")
39+
report.warning(em"The value of ${ctx.settings.XuncheckedJavaOutputVersion.name} was overridden by ${ctx.settings.javaOutputVersion.name}")
3940
release
4041
case (None, None) => "8" // least supported version by default
4142

@@ -637,7 +638,7 @@ trait BCodeIdiomatic {
637638
}
638639

639640
def abort(msg: String): Nothing = {
640-
report.error(msg)
641+
report.error(msg.toMessage)
641642
throw new RuntimeException(msg)
642643
}
643644

compiler/src/dotty/tools/backend/jvm/GenBCode.scala

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import dotty.tools.dotc.sbt.ExtractDependencies
2121
import Contexts._
2222
import Phases._
2323
import Symbols._
24+
import Decorators.em
2425

2526
import java.io.DataOutputStream
2627
import java.nio.channels.ClosedByInterruptException
@@ -80,7 +81,7 @@ class GenBCode extends Phase {
8081
if (ctx.run.nn.suspendedUnits.nonEmpty)
8182
// If we close the jar the next run will not be able to write on the jar.
8283
// But if we do not close it we cannot use it as part of the macro classpath of the suspended files.
83-
report.error("Can not suspend and output to a jar at the same time. See suspension with -Xprint-suspension.")
84+
report.error(em"Can not suspend and output to a jar at the same time. See suspension with -Xprint-suspension.")
8485

8586
jar.close()
8687
case _ =>
@@ -93,10 +94,10 @@ class GenBCode extends Phase {
9394
case List(mainClass) =>
9495
Some(mainClass)
9596
case Nil =>
96-
report.warning("No Main-Class designated or discovered.")
97+
report.warning(em"No Main-Class designated or discovered.")
9798
None
9899
case mcs =>
99-
report.warning(s"No Main-Class due to multiple entry points:\n ${mcs.mkString("\n ")}")
100+
report.warning(em"No Main-Class due to multiple entry points:\n ${mcs.mkString("\n ")}")
100101
None
101102
}
102103
mainClass.map { mc =>
@@ -308,7 +309,7 @@ class GenBCodePipeline(val int: DottyBackendInterface, val primitives: DottyPrim
308309
getFileForClassfile(outF, cls.name, ".class")
309310
} catch {
310311
case e: FileConflictException =>
311-
report.error(s"error writing ${cls.name}: ${e.getMessage}")
312+
report.error(em"error writing ${cls.name}: ${e.getMessage}")
312313
null
313314
}
314315
} else null
@@ -608,11 +609,11 @@ class GenBCodePipeline(val int: DottyBackendInterface, val primitives: DottyPrim
608609
val method =
609610
s"${e.getClassName.replaceAll("/", ".")}.${e.getMethodName}"
610611
val msg =
611-
s"Generated bytecode for method '$method' is too large. Size: ${e.getCodeSize} bytes. Limit is 64KB"
612+
em"Generated bytecode for method '$method' is too large. Size: ${e.getCodeSize} bytes. Limit is 64KB"
612613
report.error(msg)
613614
case e: ClassTooLargeException =>
614615
val msg =
615-
s"Class '${e.getClassName.replaceAll("/", ".")}' is too large. Constant pool size: ${e.getConstantPoolCount}. Limit is 64K entries"
616+
em"Class '${e.getClassName.replaceAll("/", ".")}' is too large. Constant pool size: ${e.getConstantPoolCount}. Limit is 64K entries"
616617
report.error(msg)
617618

618619
}

compiler/src/dotty/tools/backend/jvm/scalaPrimitives.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import Contexts._
88
import Names.TermName, StdNames._
99
import Types.{JavaArrayType, UnspecifiedErrorType, Type}
1010
import Symbols.{Symbol, NoSymbol}
11+
import Decorators.em
1112
import dotc.report
1213
import dotc.util.ReadOnlyMap
1314

@@ -66,7 +67,7 @@ class DottyPrimitives(ictx: Context) {
6667
case defn.ArrayOf(el) => el
6768
case JavaArrayType(el) => el
6869
case _ =>
69-
report.error(s"expected Array $tpe")
70+
report.error(em"expected Array $tpe")
7071
UnspecifiedErrorType
7172
}
7273

@@ -133,7 +134,7 @@ class DottyPrimitives(ictx: Context) {
133134
def addPrimitives(cls: Symbol, method: TermName, code: Int)(using Context): Unit = {
134135
val alts = cls.info.member(method).alternatives.map(_.symbol)
135136
if (alts.isEmpty)
136-
report.error(s"Unknown primitive method $cls.$method")
137+
report.error(em"Unknown primitive method $cls.$method")
137138
else alts foreach (s =>
138139
addPrimitive(s,
139140
s.info.paramInfoss match {

compiler/src/dotty/tools/backend/sjs/JSCodeGen.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2926,7 +2926,7 @@ class JSCodeGen()(using genCtx: Context) {
29262926
case defn.ArrayOf(el) => el
29272927
case JavaArrayType(el) => el
29282928
case tpe =>
2929-
val msg = ex"expected Array $tpe"
2929+
val msg = exm"expected Array $tpe"
29302930
report.error(msg)
29312931
ErrorType(msg)
29322932
}

compiler/src/dotty/tools/backend/sjs/JSExportsGen.scala

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,7 @@ final class JSExportsGen(jsCodeGen: JSCodeGen)(using Context) {
135135

136136
for ((info, _) <- tups.tail) {
137137
report.error(
138-
em"export overload conflicts with export of $firstSym: " +
139-
"a field may not share its exported name with another export",
138+
em"export overload conflicts with export of $firstSym: a field may not share its exported name with another export",
140139
info.pos)
141140
}
142141

@@ -264,8 +263,8 @@ final class JSExportsGen(jsCodeGen: JSCodeGen)(using Context) {
264263
.alternatives
265264

266265
assert(!alts.isEmpty,
267-
em"Ended up with no alternatives for ${classSym.fullName}::$name. " +
268-
em"Original set was ${alts} with types ${alts.map(_.info)}")
266+
em"""Ended up with no alternatives for ${classSym.fullName}::$name.
267+
|Original set was ${alts} with types ${alts.map(_.info)}""")
269268

270269
val (jsName, isProp) = exportNameInfo(name)
271270

compiler/src/dotty/tools/backend/sjs/JSPositions.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import java.net.{URI, URISyntaxException}
66

77
import dotty.tools.dotc.core._
88
import Contexts._
9+
import Decorators.em
910

1011
import dotty.tools.dotc.report
1112

@@ -22,7 +23,7 @@ class JSPositions()(using Context) {
2223
ctx.settings.scalajsMapSourceURI.value.flatMap { option =>
2324
val uris = option.split("->")
2425
if (uris.length != 1 && uris.length != 2) {
25-
report.error("-scalajs-mapSourceURI needs one or two URIs as argument (separated by '->').")
26+
report.error(em"-scalajs-mapSourceURI needs one or two URIs as argument (separated by '->').")
2627
Nil
2728
} else {
2829
try {
@@ -31,7 +32,7 @@ class JSPositions()(using Context) {
3132
URIMap(from, to) :: Nil
3233
} catch {
3334
case e: URISyntaxException =>
34-
report.error(s"${e.getInput} is not a valid URI")
35+
report.error(em"${e.getInput} is not a valid URI")
3536
Nil
3637
}
3738
}

compiler/src/dotty/tools/backend/sjs/JSPrimitives.scala

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import Names.TermName
55
import Types._
66
import Contexts._
77
import Symbols._
8+
import Decorators.em
89

910
import dotty.tools.dotc.ast.tpd._
1011
import dotty.tools.backend.jvm.DottyPrimitives
@@ -90,7 +91,7 @@ class JSPrimitives(ictx: Context) extends DottyPrimitives(ictx) {
9091
def addPrimitives(cls: Symbol, method: TermName, code: Int)(using Context): Unit = {
9192
val alts = cls.info.member(method).alternatives.map(_.symbol)
9293
if (alts.isEmpty) {
93-
report.error(s"Unknown primitive method $cls.$method")
94+
report.error(em"Unknown primitive method $cls.$method")
9495
} else {
9596
for (s <- alts)
9697
addPrimitive(s, code)

compiler/src/dotty/tools/dotc/CompilationUnit.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,11 +131,11 @@ object CompilationUnit {
131131
if (!mustExist)
132132
source
133133
else if (source.file.isDirectory) {
134-
report.error(s"expected file, received directory '${source.file.path}'")
134+
report.error(em"expected file, received directory '${source.file.path}'")
135135
NoSource
136136
}
137137
else if (!source.file.exists) {
138-
report.error(s"source file not found: ${source.file.path}")
138+
report.error(em"source file not found: ${source.file.path}")
139139
NoSource
140140
}
141141
else source

compiler/src/dotty/tools/dotc/Driver.scala

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ class Driver {
3636
finish(compiler, run)
3737
catch
3838
case ex: FatalError =>
39-
report.error(ex.getMessage.nn) // signals that we should fail compilation.
39+
report.error(ex.getMessage.nn.toMessage) // signals that we should fail compilation.
4040
case ex: TypeError =>
4141
println(s"${ex.toMessage} while compiling ${files.map(_.path).mkString(", ")}")
4242
throw ex
@@ -94,18 +94,18 @@ class Driver {
9494
val newEntries: List[String] = files
9595
.flatMap { file =>
9696
if !file.exists then
97-
report.error(s"File does not exist: ${file.path}")
97+
report.error(em"File does not exist: ${file.path}")
9898
None
9999
else file.extension match
100100
case "jar" => Some(file.path)
101101
case "tasty" =>
102102
TastyFileUtil.getClassPath(file) match
103103
case Some(classpath) => Some(classpath)
104104
case _ =>
105-
report.error(s"Could not load classname from: ${file.path}")
105+
report.error(em"Could not load classname from: ${file.path}")
106106
None
107107
case _ =>
108-
report.error(s"File extension is not `tasty` or `jar`: ${file.path}")
108+
report.error(em"File extension is not `tasty` or `jar`: ${file.path}")
109109
None
110110
}
111111
.distinct

compiler/src/dotty/tools/dotc/ast/Desugar.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1137,7 +1137,7 @@ object desugar {
11371137
def errorOnGivenBinding(bind: Bind)(using Context): Boolean =
11381138
report.error(
11391139
em"""${hl("given")} patterns are not allowed in a ${hl("val")} definition,
1140-
|please bind to an identifier and use an alias given.""".stripMargin, bind)
1140+
|please bind to an identifier and use an alias given.""", bind)
11411141
false
11421142

11431143
def isTuplePattern(arity: Int): Boolean = pat match {

compiler/src/dotty/tools/dotc/ast/tpd.scala

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -428,7 +428,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo {
428428
else
429429
val res = Select(TypeTree(pre), tp)
430430
if needLoad && !res.symbol.isStatic then
431-
throw new TypeError(em"cannot establish a reference to $res")
431+
throw new TypeError(e"cannot establish a reference to $res")
432432
res
433433

434434
def ref(sym: Symbol)(using Context): Tree =
@@ -1296,7 +1296,7 @@ object tpd extends Trees.Instance[Type] with TypedTreeInfo {
12961296
else if (tree.tpe.widen isRef numericCls)
12971297
tree
12981298
else {
1299-
report.warning(i"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.")
1299+
report.warning(em"conversion from ${tree.tpe.widen} to ${numericCls.typeRef} will always fail at runtime.")
13001300
Throw(New(defn.ClassCastExceptionClass.typeRef, Nil)).withSpan(tree.span)
13011301
}
13021302
}

compiler/src/dotty/tools/dotc/cc/CaptureSet.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,7 @@ object CaptureSet:
559559
// elements from variable sources in contra- and non-variant positions. In essence,
560560
// we approximate types resulting from such maps by returning a possible super type
561561
// from the actual type. But this is neither sound nor complete.
562-
report.warning(i"trying to add elems ${CaptureSet(newElems)} from unrecognized source $origin of mapped set $this$whereCreated")
562+
report.warning(em"trying to add elems ${CaptureSet(newElems)} from unrecognized source $origin of mapped set $this$whereCreated")
563563
CompareResult.fail(this)
564564
else
565565
CompareResult.OK

compiler/src/dotty/tools/dotc/config/CliCommand.scala

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import scala.language.unsafeNulls
55

66
import Settings._
77
import core.Contexts._
8+
import core.Decorators.toMessage
89
import printing.Highlighting
910

1011
import scala.util.chaining.given
@@ -123,10 +124,10 @@ trait CliCommand:
123124
*/
124125
def checkUsage(summary: ArgsSummary, sourcesRequired: Boolean)(using settings: ConcreteSettings)(using SettingsState, Context): Option[List[String]] =
125126
// Print all warnings encountered during arguments parsing
126-
summary.warnings.foreach(report.warning(_))
127+
summary.warnings.foreach(str => report.warning(str.toMessage))
127128

128129
if summary.errors.nonEmpty then
129-
summary.errors foreach (report.error(_))
130+
summary.errors foreach(str => report.error(str.toMessage))
130131
report.echo(ifErrorsMsg)
131132
None
132133
else if settings.version.value then

compiler/src/dotty/tools/dotc/core/Contexts.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ object Contexts {
255255
file
256256
catch
257257
case ex: InvalidPathException =>
258-
report.error(s"invalid file path: ${ex.getMessage}")
258+
report.error(em"invalid file path: ${ex.getMessage}")
259259
NoAbstractFile
260260

261261
/** AbstractFile with given path, memoized */

compiler/src/dotty/tools/dotc/core/Decorators.scala

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ object Decorators {
5959
end extension
6060

6161
extension (str: => String)
62-
def toMessage: Message = reporting.NoExplanation(str)
62+
def toMessage: Message = NoExplanation(str)
6363

6464
/** Implements a findSymbol method on iterators of Symbols that
6565
* works like find but avoids Option, replacing None with NoSymbol.
@@ -296,12 +296,22 @@ object Decorators {
296296
def i(args: Shown*)(using Context): String =
297297
new StringFormatter(sc).assemble(args)
298298

299-
/** Formatting for error messages: Like `i` but suppress follow-on
300-
* error messages after the first one if some of their arguments are "non-sensical".
299+
/** Formatting for error messages: Like `i`, with two modifications
300+
* - limit size of messages
301+
* - mark some parts of messages with <nonsensical> tags, so that
302+
* error messages after the first one are filtered out if some of
303+
* their arguments are "non-sensical".
301304
*/
302-
def em(args: Shown*)(using Context): String =
305+
def e(args: Shown*)(using Context): String =
303306
forErrorMessages(new StringFormatter(sc).assemble(args))
304307

308+
/** A NoExplanation message formatted with `e` */
309+
def em(args: Shown*)(using Context): NoExplanation =
310+
NoExplanation(e(args*))
311+
312+
def exm(args: Shown*)(using Context): NoExplanation =
313+
NoExplanation(ex(args*))
314+
305315
/** Formatting with added explanations: Like `em`, but add explanations to
306316
* give more info about type variables and to disambiguate where needed.
307317
*/

compiler/src/dotty/tools/dotc/core/Denotations.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1268,9 +1268,9 @@ object Denotations {
12681268
if sd1.exists then
12691269
if sd2.exists then
12701270
throw TypeError(
1271-
em"""Failure to disambiguate overloaded reference with
1272-
| ${denot1.symbol.showLocated}: ${denot1.info} and
1273-
| ${denot2.symbol.showLocated}: ${denot2.info}""")
1271+
e"""Failure to disambiguate overloaded reference with
1272+
| ${denot1.symbol.showLocated}: ${denot1.info} and
1273+
| ${denot2.symbol.showLocated}: ${denot2.info}""")
12741274
else sd1
12751275
else sd2
12761276
}

compiler/src/dotty/tools/dotc/core/SymDenotations.scala

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2438,10 +2438,10 @@ object SymDenotations {
24382438
val youngest = assocFiles.filter(_.lastModified == lastModDate)
24392439
val chosen = youngest.head
24402440
def ambiguousFilesMsg(f: AbstractFile) =
2441-
em"""Toplevel definition $name is defined in
2442-
| $chosen
2443-
|and also in
2444-
| $f"""
2441+
e"""Toplevel definition $name is defined in
2442+
| $chosen
2443+
|and also in
2444+
| $f"""
24452445
if youngest.size > 1 then
24462446
throw TypeError(i"""${ambiguousFilesMsg(youngest.tail.head)}
24472447
|One of these files should be removed from the classpath.""")
@@ -2454,8 +2454,8 @@ object SymDenotations {
24542454
try f.container == chosen.container catch case NonFatal(ex) => true
24552455
if !ambiguityWarningIssued then
24562456
for conflicting <- assocFiles.find(!sameContainer(_)) do
2457-
report.warning(i"""${ambiguousFilesMsg(conflicting.nn)}
2458-
|Keeping only the definition in $chosen""")
2457+
report.warning(em"""${ambiguousFilesMsg(conflicting.nn)}
2458+
|Keeping only the definition in $chosen""")
24592459
ambiguityWarningIssued = true
24602460
multi.filterWithPredicate(_.symbol.associatedFile == chosen)
24612461
end dropStale

0 commit comments

Comments
 (0)