Skip to content

Commit e8c1db3

Browse files
committed
Move 'reassignment to val' to error case class
1 parent a391a58 commit e8c1db3

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

compiler/src/dotty/tools/dotc/reporting/diagnostic/ErrorMessageID.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ public enum ErrorMessageID {
5757
CyclicReferenceInvolvingImplicitID,
5858
SuperQualMustBeParentID,
5959
AmbiguousImportID,
60+
ReassignmentToValID,
6061
;
6162

6263
public int errorNumber() {

compiler/src/dotty/tools/dotc/reporting/diagnostic/messages.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1253,4 +1253,18 @@ object messages {
12531253
|"""
12541254
}
12551255

1256+
case class ReassignmentToVal(name: Names.Name)(implicit ctx: Context)
1257+
extends Message(ReassignmentToValID) {
1258+
val kind = "Reference"
1259+
val msg = hl"""reassignment to val `$name`"""
1260+
val explanation =
1261+
hl"""|You can not assign a new value to `$name` as values can't be changed.
1262+
|Keep in mind that every statement has a value, so you may e.g. use
1263+
| ${"val"} $name ${"= if (condition) 2 else 5"}
1264+
|In case you need a reassignable name, you can declare it as
1265+
|variable
1266+
| ${"var"} $name ${"="} ...
1267+
|""".stripMargin
1268+
}
1269+
12561270
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -558,7 +558,7 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
558558

559559
def reassignmentToVal =
560560
errorTree(cpy.Assign(tree)(lhsCore, typed(tree.rhs, lhs1.tpe.widen)),
561-
"reassignment to val")
561+
ReassignmentToVal(lhsCore.symbol.name))
562562

563563
def canAssign(sym: Symbol) =
564564
sym.is(Mutable, butNot = Accessor) ||

compiler/test/dotty/tools/dotc/reporting/ErrorMessagesTests.scala

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,4 +358,20 @@ class ErrorMessagesTests extends ErrorMessagesTest {
358358
assertEquals(namedImport, newPrec)
359359
assertEquals(namedImport, prevPrec)
360360
}
361+
362+
@Test def reassignmentToVal =
363+
checkMessagesAfter("frontend") {
364+
"""
365+
|class Context {
366+
| val value = 3
367+
| value = 4
368+
|}
369+
""".stripMargin
370+
}
371+
.expect { (ictx, messages) =>
372+
implicit val ctx: Context = ictx
373+
assertMessageCount(1, messages)
374+
val ReassignmentToVal(name) :: Nil = messages
375+
assertEquals("value", name.show)
376+
}
361377
}

0 commit comments

Comments
 (0)