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.context;
018
019 import com.google.dart.compiler.backend.js.ast.*;
020 import com.intellij.openapi.util.Pair;
021 import org.jetbrains.annotations.NotNull;
022 import org.jetbrains.annotations.Nullable;
023
024 import static com.google.dart.compiler.backend.js.ast.JsVars.JsVar;
025
026 //TODO: consider renaming to scoping context
027 public final class DynamicContext {
028 @NotNull
029 public static DynamicContext rootContext(@NotNull JsScope rootScope, @NotNull JsBlock globalBlock) {
030 return new DynamicContext(rootScope, globalBlock);
031 }
032
033 @NotNull
034 public static DynamicContext newContext(@NotNull JsScope scope, @NotNull JsBlock block) {
035 return new DynamicContext(scope, block);
036 }
037
038 @NotNull
039 private final JsScope currentScope;
040
041 @NotNull
042 private final JsBlock currentBlock;
043
044 @Nullable
045 private JsVars vars;
046
047 private DynamicContext(@NotNull JsScope scope, @NotNull JsBlock block) {
048 this.currentScope = scope;
049 this.currentBlock = block;
050 }
051
052 @NotNull
053 public DynamicContext innerBlock(@NotNull JsBlock block) {
054 return new DynamicContext(currentScope, block);
055 }
056
057 @NotNull
058 public TemporaryVariable declareTemporary(@Nullable JsExpression initExpression) {
059 if (vars == null) {
060 vars = new JsVars();
061 currentBlock.getStatements().add(vars);
062 }
063
064 JsName temporaryName = currentScope.declareTemporary();
065 vars.add(new JsVar(temporaryName, null));
066 return TemporaryVariable.create(temporaryName, initExpression);
067 }
068
069 //TODO: replace return type to make it more readable
070 @NotNull
071 public Pair<JsVar, JsExpression> createTemporary(@Nullable JsExpression initExpression) {
072 JsVar var = new JsVar(currentScope.declareTemporary(), initExpression);
073 return Pair.create(var, (JsExpression) new JsNameRef(var.getName()));
074 }
075
076 @NotNull
077 public JsVar createTemporaryVar(@NotNull JsExpression initExpression) {
078 return new JsVar(currentScope.declareTemporary(), initExpression);
079 }
080
081 @NotNull
082 public JsScope getScope() {
083 return currentScope;
084 }
085
086 @NotNull
087 public JsBlock jsBlock() {
088 return currentBlock;
089 }
090 }