001 /*
002 * Copyright 2010-2013 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.k2js.translate.utils.dangerous;
018
019 import org.jetbrains.annotations.NotNull;
020 import org.jetbrains.jet.lang.psi.*;
021 import org.jetbrains.k2js.translate.context.TranslationContext;
022 import org.jetbrains.k2js.translate.reference.InlinedCallExpressionTranslator;
023
024 import static org.jetbrains.k2js.translate.utils.BindingUtils.isStatement;
025
026 public final class FindDangerousVisitor extends JetTreeVisitor<DangerousData> {
027
028 @NotNull
029 private final TranslationContext context;
030
031 public FindDangerousVisitor(@NotNull TranslationContext context) {
032 this.context = context;
033 }
034
035 @Override
036 public Void visitDeclaration(JetDeclaration dcl, DangerousData data) {
037 return null;
038 }
039
040 @Override
041 public Void visitJetElement(JetElement element, DangerousData data) {
042 if (data.exists()) {
043 return null;
044 }
045 return super.visitJetElement(element, data);
046 }
047
048 @Override
049 public Void visitWhenExpression(JetWhenExpression expression, DangerousData data) {
050 if (expressionFound(expression, data)) {
051 return null;
052 }
053 return super.visitWhenExpression(expression, data);
054 }
055
056 @Override
057 public Void visitIfExpression(JetIfExpression expression, DangerousData data) {
058 if (expressionFound(expression, data)) {
059 return null;
060 }
061 return super.visitIfExpression(expression, data);
062 }
063
064 @Override
065 public Void visitBlockExpression(JetBlockExpression expression, DangerousData data) {
066 if (isStatement(context.bindingContext(), expression)) {
067 return null;
068 }
069 else {
070 return super.visitBlockExpression(expression, data);
071 }
072 }
073
074 @Override
075 public Void visitCallExpression(JetCallExpression expression, DangerousData data) {
076 if (InlinedCallExpressionTranslator.shouldBeInlined(expression, context)) {
077 if (expressionFound(expression, data)) {
078 return null;
079 }
080 }
081 return super.visitCallExpression(expression, data);
082 }
083
084 private boolean expressionFound(@NotNull JetExpression expression, @NotNull DangerousData data) {
085 if (data.exists()) {
086 return true;
087 }
088 if (!isStatement(context.bindingContext(), expression)) {
089 data.setDangerousNode(expression);
090 return true;
091 }
092 return false;
093 }
094 }