# Improve forward reference handling?

**URL:** <https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616>\
**Category:** Language Design\
**Created:** [August 13, 2019, 9:00am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616 "2019-08-13T09:00:54Z")\
**Posts on this page:** 10\
**Page:** 1

<div class="post-metadata">

**Author:** ![cluelessjoe](https://contributors.scala-lang.org/letter_avatar_proxy/v4/letter/c/ce7236/32.png) [@cluelessjoe](https://contributors.scala-lang.org/u/cluelessjoe)\
**Post date:** [August 13, 2019, 9:00am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/1 "2019-08-13T09:00:54Z")

</div>

Hello

Currently, in Scala 2 and Dotty, forward references are handled in such a way that the code can compile yet break at runtime, cf [this example of wrong vals init in an object.](https://scastie.scala-lang.org/NDkpx6msSEKLnB7mfWNCeQ)

Being bitten by this behavior is often a big disappointment: a typesafe language compiling should run properly, not return unexpected nulls and NullPointerException. It can also appear when someone reformat the code (and I’m not speaking of big refactoring, just changing the fields declaration order), and thus suddenly introduce some regressions seen only at runtime. This is really annoying and a trust killer.

I’ve read about the rational behind the current behavior, [due to trait instantiation](https://docs.scala-lang.org/tutorials/FAQ/initialization-order.html).

The current solution, -Xcheckinit, comes with so much performance warnings that I guess not one is willing to really use it:

> It is inadvisable to use this flag outside of testing. It adds significantly to the code size by putting a wrapper around all potentially uninitialized field accesses: the wrapper will throw an exception rather than allow a null (or 0/false in the case of primitive types) to silently appear. Note also that this adds a _runtime_ check: it can only tell you anything about code paths which you exercise with it in place.

However i hope it could be improved, essentially at compilation by disallowing illegal forward references in objects (just like Java does with the “Illegal forward reference” compiler error) and maybe even in classes (or maybe provide a warning there).

I guess it could also help when implicit resolution compiles but breaks at runtime due, again, to ordering issue, which also shows up at runtime, often rather lately, through NPE/null during Json conversions…

Tackling it a better would really enhance onboarding new developers (scala compiling but breaking at runtime isn’t exactly convincing to new comers…) as well as reduce wariness when fiddling with fields’ ordering, which should come for free in a typesafe language.

What’s your pick on the matter?

Thanks in advance

---

<div class="post-metadata">

**Author:** ![julienrf](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/julienrf/32/4_2.png) [@julienrf](https://contributors.scala-lang.org/u/julienrf)\
**Post date:** [August 13, 2019, 10:02am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/2 "2019-08-13T10:02:21Z")

</div>

Unfortunately, this is a hard problem. I remember [some work](https://github.com/lampepfl/dotty/pull/4543) in this direction. Maybe @liufengyun or @biboudis can give us more details?

---

<div class="post-metadata">

**Author:** ![liufengyun](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/liufengyun/32/1169_2.png) [@liufengyun](https://contributors.scala-lang.org/u/liufengyun)\
**Post date:** [August 13, 2019, 3:24pm UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/3 "2019-08-13T15:24:48Z")

</div>

Thanks for raising the issue @cluelessjoe .

The short answer: we have an attack for exactly the problem you mentioned, and we are working on a compiler plugin implementation to make it available.

With our solution, the compiler will report an error when `bar` is used:

```auto
object ForwardReferenceGotcha {
  val foo = Foo(bar) // error
  val bar = Bar()

  case class Bar(i: Int = 0)
  case class Foo(bar: Bar)

  def main(args: Array[String]): Unit = {
    println(foo)
  }
}

```

It handles inheritance:

```auto
abstract class AbstractFile {
   def name: String
   val extension: String = Path.extension(name) // error
}

class RemoteFile(url: String) extends AbstractFile {
   val localFile: String = url.hashCode + ".tmp"
   def name: String = localFile
}

```

and linearization:

```auto
trait TA {
  val x = "world"
}
trait TB {
 def x: String
 val m = "hello" + x
}
class Foo extends TA with TB // OK
class Bar extends TB with TA // error

```

and inner classes:

```auto
object Trees {
  class ValDef { counter += 1 } // error
  class EmptyValDef extends ValDef
  val theEmptyValDef = new EmptyValDef // error
  private var counter = 0
}

```

and functions:

```auto
abstract class Parent {
  val f: () => String = () => this.message
  def message: String
}
class Child extends Parent {
  val a = f() // error
  val b = "hello"
  def message: String = b
}

```

```auto
class Foo {
  val even: Int => Boolean = (n: Int) => n == 0 || odd(n - 1)
  val flag1: Int = even(3) // error
  val odd: Int => Boolean = (n: Int) => n == 1 || even(n - 1)
  val flag2: Boolean = odd(6)
}

```

For all the features above, no annotation is required. However, to support leaking of `this` , an annotation like `@cold` is required:

```auto
class Parent { val child = new Child(this) }
class Child(parent: Parent @cold) {
  println(parent.child) // error
}

```

The analysis will reject some anti-patterns of initializaiton, e.g., assigning `this` to an already initialized object. However, it will only report warnings in such cases (it reports errors only if it’s certain that an uninitialized field is used), so we hope it will not create big usability or migration problems.

We are happy to hear more your thoughts on the problem.

---

<div class="post-metadata">

**Author:** ![Jasper-M](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/jasper-m/32/1192_2.png) [@Jasper-M](https://contributors.scala-lang.org/u/Jasper-M)\
**Post date:** [August 14, 2019, 9:11am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/4 "2019-08-14T09:11:05Z")

</div>

> [@liufengyun](#):
>
> It handles inheritance:
> 
> ```auto
> abstract class AbstractFile {
> def name: String
> val extension: String = Path.extension(name) // error
> }
> 
> class RemoteFile(url: String) extends AbstractFile {
> val localFile: String = url.hashCode + ".tmp"
> def name: String = localFile
> }
> 
> ```

Will the error be emitted on the definition of `val extension: String = Path.extension(name)`? Or on `def name: String = localFile`?

---

<div class="post-metadata">

**Author:** ![liufengyun](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/liufengyun/32/1169_2.png) [@liufengyun](https://contributors.scala-lang.org/u/liufengyun)\
**Post date:** [August 14, 2019, 11:36am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/5 "2019-08-14T11:36:44Z")

</div>

> [@Jasper-M](#):
>
> Will the error be emitted on the definition of `val extension: String = Path.extension(name)` ? Or on `def name: String = localFile` ?

The error reporting part is still under consideration. In principle, we can report a path that leads to initialization problems.

---

<div class="post-metadata">

**Author:** ![cluelessjoe](https://contributors.scala-lang.org/letter_avatar_proxy/v4/letter/c/ce7236/32.png) [@cluelessjoe](https://contributors.scala-lang.org/u/cluelessjoe)\
**Post date:** [August 15, 2019, 3:47pm UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/6 "2019-08-15T15:47:21Z")

</div>

thanks a lot for the answer.

The solution looks really neat and exhaustive (i don’t know enough to assert it is really but still it cares for more than i thought of).

Are you targeting Dotty and/or Scala2?

The sooner it can be released the better 🙂

---

<div class="post-metadata">

**Author:** ![liufengyun](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/liufengyun/32/1169_2.png) [@liufengyun](https://contributors.scala-lang.org/u/liufengyun)\
**Post date:** [August 16, 2019, 7:14am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/7 "2019-08-16T07:14:29Z")

</div>

> [@cluelessjoe](#):
>
> Are you targeting Dotty and/or Scala2?

We are targeting Dotty initially. However, nothing prevents the solution from being implemented for Scala2. We are more familiar with Dotty, so it’s an easy starting point, and some of the lessons learned & problems encountered in implementation may be re-used in Scala2 version.

> [@cluelessjoe](#):
>
> The sooner it can be released the better 🙂

Thanks for letting us know, we are working to make it happen soon to solicit more feedback.

---

<div class="post-metadata">

**Author:** ![cluelessjoe](https://contributors.scala-lang.org/letter_avatar_proxy/v4/letter/c/ce7236/32.png) [@cluelessjoe](https://contributors.scala-lang.org/u/cluelessjoe)\
**Post date:** [September 2, 2019, 9:06am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/8 "2019-09-02T09:06:05Z")

</div>

btw another issue we spoke of recently in [Better implicit search errors](https://contributors.scala-lang.org/t/better-implicit-search-errors-problematic-cases-wanted/3587/13):

```
import org.scalatest.FunSuite
import play.api.libs.json.{Format, Json}

class ImplicitOrderingTest extends FunSuite {

  implicit val BarFormat: Format[Bar] = Json.format
  implicit val FooFormat: Format[Foo] = Json.format
  test("Writing Bar - right order: compile and crash at runtime") {

    assert(BarFormat.writes(Bar(Foo(1))).toString() === """{"f":{"i":1}}""") //throws!!
  }

}

case class Foo(i: Int)

case class Bar(f: Foo)

```

This compiles but throws NPE at runtime.  
Ideally it shouldn’t compile, just like this doesn’t compile :

```
import org.scalatest.FunSuite
import play.api.libs.json.{Format, Json}

class ImplicitOrderingTest extends FunSuite {

  test("Writing Bar - right order: compile and crash at runtime") {
    implicit val BarFormat: Format[Bar] = Json.format
    implicit val FooFormat: Format[Foo] = Json.format

    assert(BarFormat.writes(Bar(Foo(1))).toString() === """{"f":{"i":1}}""")  
  }

}

case class Foo(i: Int)

case class Bar(f: Foo)  

```

The compiler error being “forward reference extends over definition of value BarFormat  
[error] implicit val BarFormat: Format[Bar] = Json.format”

Hopefully your work could also improve this 🙂

---

<div class="post-metadata">

**Author:** ![liufengyun](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/liufengyun/32/1169_2.png) [@liufengyun](https://contributors.scala-lang.org/u/liufengyun)\
**Post date:** [September 2, 2019, 10:09am UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/9 "2019-09-02T10:09:23Z")

</div>

> [@cluelessjoe](#):
>
> btw another issue we spoke of recently in [Better implicit search errors](https://contributors.scala-lang.org/t/better-implicit-search-errors-problematic-cases-wanted/3587/13):
> 
> ```auto
> import org.scalatest.FunSuite
> import play.api.libs.json.{Format, Json}
> 
> class ImplicitOrderingTest extends FunSuite {
> 
> implicit val BarFormat: Format[Bar] = Json.format
> implicit val FooFormat: Format[Foo] = Json.format
> test("Writing Bar - right order: compile and crash at runtime") {
> 
> assert(BarFormat.writes(Bar(Foo(1))).toString() === """{"f":{"i":1}}""") //throws!!
> }
> 
> }
> 
> case class Foo(i: Int)
> 
> case class Bar(f: Foo)
> 
> ```
> 
> This compiles but throws NPE at runtime.

Thanks for letting us know the case. Yes, the checker will be able to catch the bug and issue an error.

---

<div class="post-metadata">

**Author:** ![liufengyun](https://contributors.scala-lang.org/user_avatar/contributors.scala-lang.org/liufengyun/32/1169_2.png) [@liufengyun](https://contributors.scala-lang.org/u/liufengyun)\
**Post date:** [December 17, 2019, 12:22pm UTC](https://contributors.scala-lang.org/t/improve-forward-reference-handling/3616/10 "2019-12-17T12:22:25Z")

</div>

> [@liufengyun](#):
>
> Thanks for letting us know, we are working to make it happen soon to solicit more feedback.

The latest status of initialization check:

> <https://github.com/lampepfl/dotty/pull/7789>
>
> This PR implements experimental safe initialization check for Scala, which can b…e enabled by the compiler option \`-Ycheck-init\`. 
> 
> \## A Quick Glance
> 
> \### Parent-Child Interaction
> 
> Given the following code snippet:
> 
> \`\`\` Scala
> abstract class AbstractFile {
> def name: String
> val extension: String = Path.extension(name)
> }
> 
> class RemoteFile(url: String) extends AbstractFile {
> val localFile: String = url.hashCode + ".tmp" // error: usge of \`localFile\` before it's initialized
> def name: String = localFile
> }
> \`\`\`
> 
> The checker will report:
> 
> \`\`\` scala
> \-- Warning: tests/init/neg/AbstractFile.scala:7:4 ------------------------------
> 7 |	val localFile: String = url.hashCode + ".tmp" // error
> | ^
> | Access non-initialized field value localFile. Calling trace:
> | -\> val extension: String = name.substring(4)	\[AbstractFile.scala:3 \]
> | -\> def name: String = localFile	\[AbstractFile.scala:8 \]
> \`\`\`
> 
> \### Inner-Outer Interaction
> 
> Given the code below:
> 
> \`\`\` scala
> object Trees {
> class ValDef { counter += 1 }
> class EmptyValDef extends ValDef
> val theEmptyValDef = new EmptyValDef
> private var counter = 0 // error
> }
> \`\`\`
> 
> The checker will report:
> 
> \`\`\` scala
> \-- Warning: tests/init/neg/trees.scala:5:14 ------------------------------------
> 5 | private var counter = 0 // error
> | ^
> | Access non-initialized field variable counter. Calling trace:
> | -\> val theEmptyValDef = new EmptyValDef	\[trees.scala:4 \]
> | -\> class EmptyValDef extends ValDef	\[trees.scala:3 \]
> | -\> class ValDef { counter += 1 }	\[trees.scala:2 \]
> \`\`\`
> 
> \### Functions
> 
> Given the code below:
> 
> \`\`\` scala
> abstract class Parent {
> val f: () =\> String = () =\> this.message
> def message: String
> }
> class Child extends Parent {
> val a = f()
> val b = "hello" // error
> def message: String = b
> }
> \`\`\`
> 
> The checker reports:
> 
> \`\`\` scala
> \-- Warning: tests/init/neg/features-high-order.scala:7:6 -----------------------
> 7 | val b = "hello" // error
> | ^
> |Access non-initialized field value b. Calling trace:
> | -\> val a = f()	\[features-high-order.scala:6 \]
> | -\> val f: () =\> String = () =\> this.message	\[features-high-order.scala:2 \]
> | -\> def message: String = b	\[features-high-order.scala:8 \]
> \`\`\`
> 
> More details about the design can be found in the document or \[gist\](https://gist.github.com/liufengyun/6cfa8a5273a6663e6bff897205e7e6fd).
> 
> This PR is based on a series of joint work with Ondřej Lhoták (@olhotak), Aggelos Biboudis (@biboudis) and Paolo G. Giarrusso (@Blaisorblade).

We will continue to improve based on feedback of usage.
