Skip to content

Commit d4e68ce

Browse files
committed
Interactive suggestion on fields precedence added
1 parent 613cbd7 commit d4e68ce

File tree

2 files changed

+12
-8
lines changed

2 files changed

+12
-8
lines changed

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

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1936,20 +1936,24 @@ object messages {
19361936
hl"${"@static"} members are only allowed inside objects."
19371937
}
19381938

1939-
case class StaticFieldsShouldPrecedeNonStatic(member: Symbol)(implicit ctx: Context) extends Message(StaticFieldsShouldPrecedeNonStaticID) {
1939+
case class StaticFieldsShouldPrecedeNonStatic(member: Symbol, defns: List[tpd.Tree])(implicit ctx: Context) extends Message(StaticFieldsShouldPrecedeNonStaticID) {
19401940
val msg: String = hl"${"@static"} $member in ${member.owner} must be defined before non-static fields."
19411941
val kind: String = "Syntax"
1942+
19421943
val explanation: String = {
1943-
val codeExample = """object Foo {
1944-
| @static val foo = 1
1945-
| val bar = 2
1944+
val nonStatics = defns.takeWhile(_.symbol != member).take(3).filter(_.isInstanceOf[tpd.ValDef])
1945+
val codeExample = s"""object ${member.owner.name.firstPart} {
1946+
| @static ${member} = ...
1947+
| ${nonStatics.map(m => s"${m.symbol} = ...").mkString("\n ")}
1948+
| ...
19461949
|}"""
1947-
hl"""The fields annotated with @static should precede any non-@static fields.
1950+
hl"""The fields annotated with @static should precede any non @static fields.
19481951
|This ensures that we do not introduce surprises for users in initialization order of this class.
1949-
|$codeExample
1950-
|
19511952
|Static field are initialized when class loading the code of Foo.
19521953
|Non static fields are only initialized the first time that Foo is accessed.
1954+
|
1955+
|The definition of ${member.name} should have been before the non ${"@static val"}s:
1956+
|$codeExample
19531957
|"""
19541958
}
19551959
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ class CheckStatic extends MiniPhase {
3737
}
3838

3939
if (defn.isInstanceOf[ValDef] && hadNonStaticField) {
40-
ctx.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol), defn.pos)
40+
ctx.error(StaticFieldsShouldPrecedeNonStatic(defn.symbol, defns), defn.pos)
4141
}
4242

4343
val companion = ctx.owner.companionClass

0 commit comments

Comments
 (0)