Skip to content

Fix #4451: Set flag in the correct order #4817

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

Merged
merged 1 commit into from
Jul 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions compiler/src/dotty/tools/dotc/transform/LazyVals.scala
Original file line number Diff line number Diff line change
Expand Up @@ -218,11 +218,10 @@ class LazyVals extends MiniPhase with IdentityDenotTransformer {
* ```
*/
def mkNonThreadSafeDef(target: Tree, flag: Tree, rhs: Tree, nullables: List[Symbol])(implicit ctx: Context) = {
val setFlag = flag.becomes(Literal(Constants.Constant(true)))
val setNullables = nullOut(nullables)
val setTargetAndNullable = if (isWildcardArg(rhs)) setNullables else target.becomes(rhs) :: setNullables
val init = Block(setFlag :: setTargetAndNullable, target.ensureApplied)
If(flag.ensureApplied, target.ensureApplied, init)
val stats = new mutable.ListBuffer[Tree]
if (!isWildcardArg(rhs)) stats += target.becomes(rhs)
stats += flag.becomes(Literal(Constants.Constant(true))) ++= nullOut(nullables)
If(flag.ensureApplied, target.ensureApplied, Block(stats.toList, target.ensureApplied))
}

/** Create non-threadsafe lazy accessor for not-nullable types equivalent to such code
Expand Down
55 changes: 55 additions & 0 deletions tests/run/i4451.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
class InitError extends Exception

class Lazy(x: Int) {
private[this] var init = false
lazy val value = {
if (!init) {
init = true
throw new InitError
}
x
}
}

class LazyVolatile(x: Int) {
private[this] var init = false
@volatile lazy val value = {
if (!init) {
init = true
throw new InitError
}
x
}
}

object Test {

def tryTwice(x: => Int): Int =
try {
x; assert(false); 0
} catch {
case _: InitError => x
}

def lazyInMethod(x: Int) = {
var init = false
lazy val value = {
if (!init) {
init = true
throw new InitError
}
x
}
tryTwice(value)
}

def main(args: Array[String]) = {
val v = 42

val l0 = new Lazy(v)
val l1 = new LazyVolatile(v)
assert(tryTwice(l0.value) == v)
assert(tryTwice(l1.value) == v)
assert(lazyInMethod(v) == v)
}
}