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 com.google.common.collect.Maps;
020 import com.google.dart.compiler.backend.js.ast.JsExpression;
021 import com.google.dart.compiler.backend.js.ast.JsName;
022 import com.google.dart.compiler.backend.js.ast.JsNode;
023 import org.jetbrains.annotations.NotNull;
024 import org.jetbrains.jet.lang.psi.JetExpression;
025 import org.jetbrains.k2js.translate.context.TemporaryVariable;
026 import org.jetbrains.k2js.translate.context.TranslationContext;
027 import org.jetbrains.k2js.translate.general.AbstractTranslator;
028 import org.jetbrains.k2js.translate.general.Translation;
029
030 import java.util.List;
031 import java.util.Map;
032
033 public final class DangerousTranslator extends AbstractTranslator {
034 @NotNull
035 private final DangerousData data;
036
037 @NotNull
038 public static JsNode translate(@NotNull DangerousData data, @NotNull TranslationContext context) {
039 assert data.exists();
040 return new DangerousTranslator(data, context).translate();
041 }
042
043 private DangerousTranslator(@NotNull DangerousData data, @NotNull TranslationContext context) {
044 super(context);
045 this.data = data;
046 }
047
048 @NotNull
049 private JsNode translate() {
050 Map<JetExpression, JsName> aliasesForExpressions =
051 translateAllExpressionsAndCreateAliasesForThem(data.getNodesToBeGeneratedBefore());
052 TranslationContext contextWithAliases = context().innerContextWithAliasesForExpressions(aliasesForExpressions);
053 return Translation.doTranslateExpression(data.getRootNode(), contextWithAliases);
054 }
055
056 @NotNull
057 private Map<JetExpression, JsName> translateAllExpressionsAndCreateAliasesForThem(@NotNull List<JetExpression> expressions) {
058 Map<JetExpression, JsName> aliasesForExpressions = Maps.newHashMap();
059 for (JetExpression expression : expressions) {
060 JsExpression translatedExpression = Translation.translateAsExpression(expression, context());
061 TemporaryVariable aliasForExpression = context().declareTemporary(translatedExpression);
062 context().addStatementToCurrentBlock(aliasForExpression.assignmentExpression().makeStmt());
063 aliasesForExpressions.put(expression, aliasForExpression.name());
064 }
065 return aliasesForExpressions;
066 }
067 }