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
017package org.jetbrains.k2js.translate.reference;
018
019import com.google.dart.compiler.backend.js.ast.JsExpression;
020import com.google.dart.compiler.backend.js.ast.JsNameRef;
021import org.jetbrains.annotations.NotNull;
022import org.jetbrains.annotations.Nullable;
023import org.jetbrains.k2js.translate.context.TemporaryVariable;
024import org.jetbrains.k2js.translate.context.TranslationContext;
025
026import java.util.Collections;
027import java.util.List;
028
029import static java.util.Collections.singletonList;
030
031public final class CachedPropertyAccessTranslator implements CachedAccessTranslator {
032
033    @NotNull
034    private final PropertyAccessTranslator baseTranslator;
035    @Nullable
036    private final TemporaryVariable cachedReceiver;
037
038    /*package*/ CachedPropertyAccessTranslator(@Nullable JsExpression receiverExpression,
039                                               @NotNull PropertyAccessTranslator baseTranslator,
040                                               @NotNull TranslationContext context) {
041        this.cachedReceiver = receiverExpression != null ? context.declareTemporary(receiverExpression) : null;
042        this.baseTranslator = baseTranslator;
043    }
044
045    @NotNull
046    @Override
047    public JsExpression translateAsGet() {
048        return baseTranslator.translateAsGet(receiverOrNull());
049    }
050
051    @NotNull
052    @Override
053    public JsExpression translateAsSet(@NotNull JsExpression toSetTo) {
054        return baseTranslator.translateAsSet(receiverOrNull(), toSetTo);
055    }
056
057    @Nullable
058    private JsNameRef receiverOrNull() {
059        return cachedReceiver != null ? cachedReceiver.reference() : null;
060    }
061
062    @NotNull
063    @Override
064    public CachedAccessTranslator getCached() {
065        return this;
066    }
067
068    @NotNull
069    @Override
070    public List<TemporaryVariable> declaredTemporaries() {
071        return cachedReceiver != null ? singletonList(cachedReceiver) : Collections.<TemporaryVariable>emptyList();
072    }
073}