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 com.google.dart.compiler.backend.js.ast.metadata.MetadataProperties; 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 MetadataProperties.setSynthetic(vars, true); 062 currentBlock.getStatements().add(vars); 063 } 064 065 JsName temporaryName = currentScope.declareTemporary(); 066 JsVar var = new JsVar(temporaryName, null); 067 MetadataProperties.setSynthetic(var, true); 068 vars.add(var); 069 return TemporaryVariable.create(temporaryName, initExpression); 070 } 071 072 void moveVarsFrom(@NotNull DynamicContext dynamicContext) { 073 if (dynamicContext.vars != null) { 074 if (vars == null) { 075 vars = dynamicContext.vars; 076 currentBlock.getStatements().add(vars); 077 } else { 078 vars.addAll(dynamicContext.vars); 079 } 080 dynamicContext.currentBlock.getStatements().remove(dynamicContext.vars); 081 dynamicContext.vars = null; 082 } 083 } 084 085 @NotNull 086 public JsScope getScope() { 087 return currentScope; 088 } 089 090 @NotNull 091 public JsBlock jsBlock() { 092 return currentBlock; 093 } 094 }