Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cyclic initialization compiles with -Yexplicit-nulls and -Ysafe-init #11262

Closed
crater2150 opened this issue Jan 31, 2021 · 1 comment
Closed

Comments

@crater2150
Copy link

crater2150 commented Jan 31, 2021

Compiler version

3.0.0-M3-bin-20201216-c8fb1fa-NIGHTLY-git-c8fb1fa

Minimized code

object A { val x: String = B.y }
object B { val y: String = A.x }

Output

Compiled with both -Yexplicit-nulls and -Ysafe-init, both fields are null:

A.x == null
B.y == null

Expectation

I expected this not to compile. I'm not sure if detecting such cycles is in scope for -Ycheck-init, but the documentation for explicit nulls suggests that -Ycheck-init catches the unsoundness caused by null in initialization.

@liufengyun liufengyun self-assigned this Jan 31, 2021
@liufengyun liufengyun linked a pull request Jan 31, 2021 that will close this issue
liufengyun added a commit that referenced this issue Jun 16, 2023
The problem is illustrated by the example below:

``` Scala
class Foo(val opposite: Foo)
case object A extends Foo(B)     // A -> B
case object B extends Foo(A)     // B -> A
```
The check aims to be simple for programmers to understand, expressive,
fast, and sound.

The check is centered around two design ideas: (1) initialization-time
irrelevance; (2) partial ordering.

The check enforces the principle of _initialization-time irrelevance_,
which means that the time when a static object is initialized should not
change program semantics. For that purpose, it enforces the following
rule:

> **The initialization of a static object should not directly or
indirectly read or write mutable state owned by another static object**.

This principle not only puts the initialization of static objects on a
solid foundation but also avoids whole-program analysis.

Partial ordering means that the initialization dependencies of static
objects form a directed-acyclic graph (DAG). No cycles with length
bigger than 1 allowed --- which might lead to deadlocks in the presence
of concurrency and strong coupling & subtle contracts between objects.

Related Issues:

#16152
#9176
#11262
scala/bug#9312
scala/bug#9115
scala/bug#9261
scala/bug#5366
scala/bug#9360
@liufengyun
Copy link
Contributor

This can now be checked with the experimental option: -Ysafe-init-global.

@liufengyun liufengyun changed the title Cyclic initialization compiles with -Yexplicit-nulls and -Ycheck-init Cyclic initialization compiles with -Yexplicit-nulls and -Ysafe-init Jul 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants