Skip to content

Commit 9e8c5af

Browse files
committed
Show inlined positions with source code
This gives more context to the users on what happen and where the code came from.
1 parent 59a3d9c commit 9e8c5af

27 files changed

+416
-107
lines changed

compiler/src/dotty/tools/dotc/reporting/MessageRendering.scala

+132-47
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import scala.annotation.switch
1616
import scala.collection.mutable
1717

1818
trait MessageRendering {
19+
import Highlight.*
20+
import Offsets.*
1921

2022
/** Remove ANSI coloring from `str`, useful for getting real length of
2123
* strings
@@ -25,31 +27,25 @@ trait MessageRendering {
2527
def stripColor(str: String): String =
2628
str.replaceAll("\u001b\\[.*?m", "")
2729

28-
/** When inlining a method call, if there's an error we'd like to get the
29-
* outer context and the `pos` at which the call was inlined.
30-
*
31-
* @return a list of strings with inline locations
32-
*/
33-
def outer(pos: SourcePosition, prefix: String)(using Context): List[String] =
34-
if (pos.outer.exists)
35-
i"$prefix| This location contains code that was inlined from $pos" ::
36-
outer(pos.outer, prefix)
30+
/** List of all the inline calls that surround the position */
31+
def inlinePosStack(pos: SourcePosition): List[SourcePosition] =
32+
if pos.outer != null && pos.outer.exists then pos :: inlinePosStack(pos.outer)
3733
else Nil
3834

3935
/** Get the sourcelines before and after the position, as well as the offset
4036
* for rendering line numbers
4137
*
4238
* @return (lines before error, lines after error, line numbers offset)
4339
*/
44-
def sourceLines(pos: SourcePosition, diagnosticLevel: String)(using Context): (List[String], List[String], Int) = {
40+
private def sourceLines(pos: SourcePosition)(using Context, Level, Offset): (List[String], List[String], Int) = {
4541
assert(pos.exists && pos.source.file.exists)
4642
var maxLen = Int.MinValue
4743
def render(offsetAndLine: (Int, String)): String = {
48-
val (offset, line) = offsetAndLine
49-
val lineNbr = pos.source.offsetToLine(offset)
50-
val prefix = s"${lineNbr + 1} |"
44+
val (offset1, line) = offsetAndLine
45+
val lineNbr = (pos.source.offsetToLine(offset1) + 1).toString
46+
val prefix = String.format(s"%${offset - 2}s |", lineNbr)
5147
maxLen = math.max(maxLen, prefix.length)
52-
val lnum = hl(diagnosticLevel)(" " * math.max(0, maxLen - prefix.length) + prefix)
48+
val lnum = hl(" " * math.max(0, maxLen - prefix.length - 1) + prefix)
5349
lnum + line.stripLineEnd
5450
}
5551

@@ -77,23 +73,76 @@ trait MessageRendering {
7773
)
7874
}
7975

80-
/** The column markers aligned under the error */
81-
def columnMarker(pos: SourcePosition, offset: Int, diagnosticLevel: String)(using Context): String = {
76+
/** Generate box containing the report title
77+
*
78+
* ```
79+
* -- Error: source.scala ---------------------
80+
* ```
81+
*/
82+
private def boxTitle(title: String)(using Context, Level, Offset): String =
83+
val pageWidth = ctx.settings.pageWidth.value
84+
val line = "-" * (pageWidth - title.length - 4)
85+
hl(s"-- $title $line")
86+
87+
/** The column markers aligned under the error
88+
*
89+
* ```
90+
* | ^^^^^
91+
* ```
92+
*/
93+
private def columnMarker(pos: SourcePosition)(using Context, Level, Offset): String = {
8294
val prefix = " " * (offset - 1)
8395
val padding = pos.startColumnPadding
84-
val carets = hl(diagnosticLevel) {
96+
val carets =
8597
if (pos.startLine == pos.endLine)
8698
"^" * math.max(1, pos.endColumn - pos.startColumn)
8799
else "^"
88-
}
89-
s"$prefix|$padding$carets"
100+
hl(s"$prefix|$padding$carets")
90101
}
91102

103+
/** The horizontal line with the given offset
104+
*
105+
* ```
106+
* |
107+
* ```
108+
*/
109+
private def offsetBox(using Context, Level, Offset): String =
110+
val prefix = " " * (offset - 1)
111+
hl(s"$prefix|")
112+
113+
/** The end of a box section
114+
*
115+
* ```
116+
* |---------------
117+
* ```
118+
* Or if there `soft` is true,
119+
* ```
120+
* |···············
121+
* ```
122+
*/
123+
private def newBox(soft: Boolean = false)(using Context, Level, Offset): String =
124+
val pageWidth = ctx.settings.pageWidth.value
125+
val prefix = " " * (offset - 1)
126+
val line = (if soft then "·" else "-") * (pageWidth - offset)
127+
hl(s"$prefix|$line")
128+
129+
/** The end of a box section
130+
*
131+
* ```
132+
* ·----------------
133+
* ```
134+
*/
135+
private def endBox(using Context, Level, Offset): String =
136+
val pageWidth = ctx.settings.pageWidth.value
137+
val prefix = " " * (offset - 1)
138+
val line = "-" * (pageWidth - offset)
139+
hl(s"$prefix·$line")
140+
92141
/** The error message (`msg`) aligned under `pos`
93142
*
94143
* @return aligned error message
95144
*/
96-
def errorMsg(pos: SourcePosition, msg: String, offset: Int)(using Context): String = {
145+
private def errorMsg(pos: SourcePosition, msg: String)(using Context, Level, Offset): String = {
97146
val padding = msg.linesIterator.foldLeft(pos.startColumnPadding) { (pad, line) =>
98147
val lineLength = stripColor(line).length
99148
val maxPad = math.max(0, ctx.settings.pageWidth.value - offset - lineLength) - offset
@@ -103,35 +152,32 @@ trait MessageRendering {
103152
}
104153

105154
msg.linesIterator
106-
.map { line => " " * (offset - 1) + "|" + (if line.isEmpty then "" else padding + line) }
155+
.map { line => offsetBox + (if line.isEmpty then "" else padding + line) }
107156
.mkString(EOL)
108157
}
109158

110159
/** The source file path, line and column numbers from the given SourcePosition */
111-
def posFileStr(pos: SourcePosition): String =
160+
protected def posFileStr(pos: SourcePosition): String =
112161
val path = pos.source.file.path
113162
if pos.exists then s"$path:${pos.line + 1}:${pos.column}" else path
114163

115164
/** The separator between errors containing the source file and error type
116165
*
117166
* @return separator containing error location and kind
118167
*/
119-
def posStr(pos: SourcePosition, diagnosticLevel: String, message: Message)(using Context): String =
120-
if (pos.source != NoSourcePosition.source) hl(diagnosticLevel)({
121-
val fileAndPos = posFileStr(pos.nonInlined)
122-
val file = if fileAndPos.isEmpty || fileAndPos.endsWith(" ") then fileAndPos else s"$fileAndPos "
168+
private def posStr(pos: SourcePosition, message: Message, diagnosticString: String)(using Context, Level, Offset): String =
169+
if (pos.source != NoSourcePosition.source) hl({
170+
val realPos = pos.nonInlined
171+
val fileAndPos = posFileStr(realPos)
123172
val errId =
124173
if (message.errorId ne ErrorMessageID.NoExplanationID) {
125174
val errorNumber = message.errorId.errorNumber
126175
s"[E${"0" * (3 - errorNumber.toString.length) + errorNumber}] "
127176
} else ""
128177
val kind =
129-
if (message.kind == "") diagnosticLevel
130-
else s"${message.kind} $diagnosticLevel"
131-
val prefix = s"-- ${errId}${kind}: $file"
132-
133-
prefix +
134-
("-" * math.max(ctx.settings.pageWidth.value - stripColor(prefix).length, 0))
178+
if (message.kind == "") diagnosticString
179+
else s"${message.kind} $diagnosticString"
180+
boxTitle(s"$errId$kind: $fileAndPos")
135181
}) else ""
136182

137183
/** Explanation rendered under "Explanation" header */
@@ -146,7 +192,7 @@ trait MessageRendering {
146192
sb.toString
147193
}
148194

149-
def appendFilterHelp(dia: Diagnostic, sb: mutable.StringBuilder): Unit =
195+
private def appendFilterHelp(dia: Diagnostic, sb: mutable.StringBuilder): Unit =
150196
import dia._
151197
val hasId = msg.errorId.errorNumber >= 0
152198
val category = dia match {
@@ -166,17 +212,34 @@ trait MessageRendering {
166212
/** The whole message rendered from `msg` */
167213
def messageAndPos(dia: Diagnostic)(using Context): String = {
168214
import dia._
169-
val levelString = diagnosticLevel(dia)
215+
val pos1 = pos.nonInlined
216+
val inlineStack = inlinePosStack(pos).filter(_ != pos1)
217+
val maxLineNumber =
218+
if pos.exists then (pos1 :: inlineStack).map(_.endLine).max + 1
219+
else 0
220+
given Level = Level(level)
221+
given Offset = Offset(maxLineNumber.toString.length + 2)
170222
val sb = mutable.StringBuilder()
171-
val posString = posStr(pos, levelString, msg)
223+
val posString = posStr(pos, msg, diagnosticLevel(dia))
172224
if (posString.nonEmpty) sb.append(posString).append(EOL)
173225
if (pos.exists) {
174226
val pos1 = pos.nonInlined
175227
if (pos1.exists && pos1.source.file.exists) {
176-
val (srcBefore, srcAfter, offset) = sourceLines(pos1, levelString)
177-
val marker = columnMarker(pos1, offset, levelString)
178-
val err = errorMsg(pos1, msg.message, offset)
179-
sb.append((srcBefore ::: marker :: err :: outer(pos, " " * (offset - 1)) ::: srcAfter).mkString(EOL))
228+
val (srcBefore, srcAfter, offset) = sourceLines(pos1)
229+
val marker = columnMarker(pos1)
230+
val err = errorMsg(pos1, msg.message)
231+
sb.append((srcBefore ::: marker :: err :: srcAfter).mkString(EOL))
232+
233+
if inlineStack.nonEmpty then
234+
sb.append(EOL).append(newBox())
235+
sb.append(EOL).append(offsetBox).append(i"Inline stack trace")
236+
for inlinedPos <- inlineStack if inlinedPos != pos1 do
237+
val (srcBefore, srcAfter, offset) = sourceLines(inlinedPos)
238+
val marker = columnMarker(inlinedPos)
239+
sb.append(EOL).append(newBox(soft = true))
240+
sb.append(EOL).append(offsetBox).append(i"This location contains code that was inlined from $pos")
241+
sb.append(EOL).append((srcBefore ::: marker :: srcAfter).mkString(EOL))
242+
sb.append(EOL).append(endBox)
180243
}
181244
else sb.append(msg.message)
182245
}
@@ -186,15 +249,13 @@ trait MessageRendering {
186249
sb.toString
187250
}
188251

189-
def hl(diagnosticLevel: String)(str: String)(using Context): String = diagnosticLevel match {
190-
case "Info" => Blue(str).show
191-
case "Error" => Red(str).show
192-
case _ =>
193-
assert(diagnosticLevel.contains("Warning"))
194-
Yellow(str).show
195-
}
252+
private def hl(str: String)(using Context, Level): String =
253+
summon[Level].value match
254+
case interfaces.Diagnostic.ERROR => Red(str).show
255+
case interfaces.Diagnostic.WARNING => Yellow(str).show
256+
case interfaces.Diagnostic.INFO => Blue(str).show
196257

197-
def diagnosticLevel(dia: Diagnostic): String =
258+
private def diagnosticLevel(dia: Diagnostic): String =
198259
dia match {
199260
case dia: FeatureWarning => "Feature Warning"
200261
case dia: DeprecationWarning => "Deprecation Warning"
@@ -205,4 +266,28 @@ trait MessageRendering {
205266
case interfaces.Diagnostic.WARNING => "Warning"
206267
case interfaces.Diagnostic.INFO => "Info"
207268
}
269+
270+
}
271+
272+
private object Highlight {
273+
opaque type Level = Int
274+
extension (level: Level) def value: Int = level
275+
object Level:
276+
def apply(level: Int): Level = level
277+
}
278+
279+
/** Size of the left offset added by the box
280+
*
281+
* ```
282+
* -- Error: ... ------------
283+
* 4 | foo
284+
* | ^^^
285+
* ^^^ // size of this offset
286+
* ```
287+
*/
288+
private object Offsets {
289+
opaque type Offset = Int
290+
def offset(using o: Offset): Int = o
291+
object Offset:
292+
def apply(level: Int): Offset = level
208293
}

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

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ object Splicer {
4949
val oldContextClassLoader = Thread.currentThread().getContextClassLoader
5050
Thread.currentThread().setContextClassLoader(classLoader)
5151
try {
52-
val interpreter = new Interpreter(spliceExpansionPos, classLoader)
52+
val interpreter = new Interpreter(splicePos, classLoader)
5353

5454
// Some parts of the macro are evaluated during the unpickling performed in quotedExprToTree
5555
val interpretedExpr = interpreter.interpret[Quotes => scala.quoted.Expr[Any]](tree)

compiler/src/dotty/tools/dotc/typer/Inliner.scala

+1-1
Original file line numberDiff line numberDiff line change
@@ -853,7 +853,7 @@ class Inliner(call: tpd.Tree, rhsToInline: tpd.Tree)(using Context) {
853853
evidence.tpe match
854854
case fail: Implicits.SearchFailureType =>
855855
val msg = evTyper.missingArgMsg(evidence, tpt.tpe, "")
856-
errorTree(tpt, em"$msg")
856+
errorTree(call, em"$msg")
857857
case _ =>
858858
evidence
859859
return searchImplicit(callTypeArgs.head)

compiler/test-resources/repl/i9227

-1
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,4 @@ scala> import scala.quoted._; inline def myMacro[T]: Unit = ${ myMacroImpl[T] };
33
1 | import scala.quoted._; inline def myMacro[T]: Unit = ${ myMacroImpl[T] }; def myMacroImpl[T](using Quotes): Expr[Unit] = '{}; println(myMacro[Int])
44
| ^^^^^^^^^^^^
55
| Cannot call macro method myMacroImpl defined in the same source file
6-
| This location contains code that was inlined from rs$line$1:1
76
1 error found

tests/neg-macros/delegate-match-1.check

-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,3 @@
44
| ^
55
| AmbiguousImplicits
66
| both value a1 in class Test1 and value a2 in class Test1 match type A
7-
| This location contains code that was inlined from Test_2.scala:6

tests/neg-macros/delegate-match-2.check

-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,3 @@
44
| ^
55
| DivergingImplicit
66
| method a1 in class Test produces a diverging implicit search when trying to match type A
7-
| This location contains code that was inlined from Test_2.scala:5

tests/neg-macros/delegate-match-3.check

-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,3 @@
44
| ^
55
| NoMatchingImplicits
66
| no implicit values were found that match type A
7-
| This location contains code that was inlined from Test_2.scala:3

tests/neg-macros/i11386.check

+14-4
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,21 @@
33
6 | dummy(0) // error
44
| ^
55
| test
6-
| This location contains code that was inlined from Test_2.scala:6
7-
| This location contains code that was inlined from Macro_1.scala:7
6+
|---------------------------------------------------------------------------------------------------------------------
7+
|Inline stack trace
8+
|·····················································································································
9+
|This location contains code that was inlined from Test_2.scala:6
10+
7 | notNull(i)
11+
| ^^^^^^^^^^
12+
·---------------------------------------------------------------------------------------------------------------------
813
-- Error: tests/neg-macros/i11386/Test_2.scala:8:20 --------------------------------------------------------------------
914
8 | dummy(int2String(0)) // error
1015
| ^^^^^^^^^^^^^
1116
| test
12-
| This location contains code that was inlined from Test_2.scala:8
13-
| This location contains code that was inlined from Macro_1.scala:7
17+
|---------------------------------------------------------------------------------------------------------------------
18+
|Inline stack trace
19+
|·····················································································································
20+
|This location contains code that was inlined from Test_2.scala:8
21+
7 | notNull(i)
22+
| ^^^^^^^^^^
23+
·---------------------------------------------------------------------------------------------------------------------

tests/neg-macros/i13991.check

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
-- Error: tests/neg-macros/i13991/Test_2.scala:6:5 ---------------------------------------------------------------------
3+
6 | v2 // error
4+
| ^^
5+
| Error
6+
|---------------------------------------------------------------------------------------------------------------------
7+
|Inline stack trace
8+
|·····················································································································
9+
|This location contains code that was inlined from Test_2.scala:3
10+
3 | inline def v2 = InlineMac.sample("foo")
11+
| ^^^^^
12+
|·····················································································································
13+
|This location contains code that was inlined from Test_2.scala:3
14+
3 | inline def v2 = InlineMac.sample("foo")
15+
| ^^^^^^^^^^^^^^^^^^^^^^^
16+
·---------------------------------------------------------------------------------------------------------------------

tests/neg-macros/i13991/Macro_1.scala

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import scala.quoted.*
2+
3+
object InlineMac:
4+
5+
inline def sample(inline expr: String): Int =
6+
${ sampleImpl('expr) }
7+
8+
def sampleImpl(expr: Expr[String])(using Quotes): Expr[Int] =
9+
import quotes.reflect.*
10+
report.errorAndAbort("Error", expr)

tests/neg-macros/i13991/Test_2.scala

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
object Main:
2+
def main(args: Array[String]): Unit =
3+
inline def v2 = InlineMac.sample("foo")
4+
inline def v1 = v2
5+
6+
v2 // error

tests/neg-macros/i6432.check

-3
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,11 @@
33
4 | foo"abc${"123"}xyz${"456"}fgh" // error // error // error
44
| ^^^
55
| abc
6-
| This location contains code that was inlined from Test_2.scala:4
76
-- Error: tests/neg-macros/i6432/Test_2.scala:4:17 ---------------------------------------------------------------------
87
4 | foo"abc${"123"}xyz${"456"}fgh" // error // error // error
98
| ^^^
109
| xyz
11-
| This location contains code that was inlined from Test_2.scala:4
1210
-- Error: tests/neg-macros/i6432/Test_2.scala:4:28 ---------------------------------------------------------------------
1311
4 | foo"abc${"123"}xyz${"456"}fgh" // error // error // error
1412
| ^^^
1513
| fgh
16-
| This location contains code that was inlined from Test_2.scala:4

0 commit comments

Comments
 (0)