JS backend: fix dangling else issue in generated code for JsToStringGenerationVisitor

JS backend: fix KT-5253: when with if inside

 #KT-5253 Fixed
This commit is contained in:
Michael Nedzelsky
2014-08-19 19:14:50 +04:00
parent bfa8fea5b8
commit 629d9a275b
3 changed files with 35 additions and 1 deletions
@@ -558,10 +558,13 @@ public class JsToStringGenerationVisitor extends JsVisitor {
accept(x.getIfExpression());
rightParen();
JsStatement thenStmt = x.getThenStatement();
JsStatement elseStatement = x.getElseStatement();
if (elseStatement != null && thenStmt instanceof JsIf && ((JsIf)thenStmt).getElseStatement() == null) {
thenStmt = new JsBlock(thenStmt);
}
nestedPush(thenStmt);
accept(thenStmt);
nestedPop(thenStmt);
JsStatement elseStatement = x.getElseStatement();
if (elseStatement != null) {
if (needSemi) {
semi();
@@ -108,4 +108,8 @@ public final class WhenTest extends AbstractExpressionTest {
public void testWhenWithOneStmWhen() throws Exception {
fooBoxTest();
}
public void testIfInWhenDanglingElseIssue() throws Exception {
checkFooBoxIsOk();
}
}
@@ -0,0 +1,27 @@
// http://youtrack.jetbrains.com/issue/KT-5253
// JS: generated wrong code when use `if` inside `when`
package foo
fun test(caseId: Int, value: Int, expected: Int) {
var actual: Int = 0
when (caseId) {
2 -> if (value < 0) actual = -value
3 -> actual = if (value < 0) {-value} else value
else -> throw Exception("Unexpected case: $caseId")
}
if (expected != actual) throw Exception("expected = $expected, actual = $actual")
}
fun box(): String {
test(2, 33, 0)
test(2, -1, 1)
test(3, 23, 23)
test(3, -3, 3)
return "OK"
}