001 /*
002 * Copyright 2010-2015 JetBrains s.r.o.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package org.jetbrains.kotlin.js.translate.utils.mutator;
018
019 import com.google.dart.compiler.backend.js.ast.*;
020 import org.jetbrains.annotations.NotNull;
021
022 import java.util.List;
023
024 import static org.jetbrains.kotlin.js.translate.utils.JsAstUtils.convertToStatement;
025
026 public final class LastExpressionMutator {
027 public static JsStatement mutateLastExpression(@NotNull JsNode node, @NotNull Mutator mutator) {
028 return convertToStatement(new LastExpressionMutator(mutator).apply(node));
029 }
030
031 @NotNull
032 private final Mutator mutator;
033
034 private LastExpressionMutator(@NotNull Mutator mutator) {
035 this.mutator = mutator;
036 }
037
038 //TODO: visitor?
039 //TODO: when expression?
040 @NotNull
041 private JsNode apply(@NotNull JsNode node) {
042 if (node instanceof JsBlock) {
043 return applyToBlock((JsBlock) node);
044 }
045 if (node instanceof JsIf) {
046 return applyToIf((JsIf) node);
047 }
048 if (node instanceof JsTry) {
049 return applyToTry((JsTry) node);
050 }
051 if (node instanceof JsExpressionStatement) {
052 return applyToStatement((JsExpressionStatement) node);
053 }
054 return mutator.mutate(node);
055 }
056
057 @NotNull
058 private JsNode applyToStatement(@NotNull JsExpressionStatement node) {
059 return convertToStatement(apply(node.getExpression()));
060 }
061
062 @NotNull
063 private JsNode applyToIf(@NotNull JsIf node) {
064 node.setThenStatement(convertToStatement(apply(node.getThenStatement())));
065 JsStatement elseStmt = node.getElseStatement();
066 if (elseStmt != null) {
067 node.setElseStatement(convertToStatement(apply(elseStmt)));
068 }
069 return node;
070 }
071
072 @NotNull
073 private JsNode applyToTry(@NotNull JsTry node) {
074 applyToBlock(node.getTryBlock());
075 for(JsCatch jsCatch: node.getCatches()) {
076 applyToBlock(jsCatch.getBody());
077 }
078 return node;
079 }
080
081 @NotNull
082 private JsNode applyToBlock(@NotNull JsBlock node) {
083 List<JsStatement> statements = node.getStatements();
084
085 if (statements.isEmpty()) return node;
086
087 int size = statements.size();
088 statements.set(size - 1, convertToStatement(apply(statements.get(size - 1))));
089 return node;
090 }
091 }