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