private WhenTranslator( @NotNull KtWhenExpression expression, @NotNull TranslationContext context) { super(context); whenExpression = expression; KtExpression subject = expression.getSubjectExpression(); if (subject != null) { JsExpression subjectExpression = Translation.translateAsExpression(subject, context); if (TranslationUtils.isCacheNeeded(subjectExpression)) { TemporaryVariable subjectVar = context.declareTemporary(null); context.addStatementToCurrentBlock( JsAstUtils.assignment(subjectVar.reference(), subjectExpression).makeStmt()); subjectExpression = subjectVar.reference(); } expressionToMatch = subjectExpression; } else { expressionToMatch = null; } }
private JsStatement translate() { if (expressionToMatch != null && JsAstUtils.isEmptyExpression(expressionToMatch)) { return JsEmpty.INSTANCE; } JsIf currentIf = null; JsIf resultIf = null; for (KtWhenEntry entry : whenExpression.getEntries()) { JsBlock statementBlock = new JsBlock(); JsStatement statement = translateEntryExpression(entry, context(), statementBlock); if (resultIf == null && entry.isElse()) { context().addStatementsToCurrentBlockFrom(statementBlock); return statement; } statement = JsAstUtils.mergeStatementInBlockIfNeeded(statement, statementBlock); if (resultIf == null) { currentIf = JsAstUtils.newJsIf(translateConditions(entry, context()), statement); resultIf = currentIf; } else { if (entry.isElse()) { currentIf.setElseStatement(statement); return resultIf; } JsBlock conditionsBlock = new JsBlock(); JsIf nextIf = JsAstUtils.newJsIf( translateConditions(entry, context().innerBlock(conditionsBlock)), statement); JsStatement statementToAdd = JsAstUtils.mergeStatementInBlockIfNeeded(nextIf, conditionsBlock); currentIf.setElseStatement(statementToAdd); currentIf = nextIf; } } return resultIf; }