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.reference;
018    
019    import com.google.common.collect.Lists;
020    import com.google.dart.compiler.backend.js.ast.JsExpression;
021    import org.jetbrains.annotations.NotNull;
022    import org.jetbrains.jet.lang.psi.JetArrayAccessExpression;
023    import org.jetbrains.k2js.translate.context.TemporaryVariable;
024    import org.jetbrains.k2js.translate.context.TranslationContext;
025    
026    import java.util.List;
027    
028    import static org.jetbrains.k2js.translate.utils.TemporariesUtils.fromExpressionList;
029    import static org.jetbrains.k2js.translate.utils.TemporariesUtils.toExpressionList;
030    
031    public final class CachedArrayAccessTranslator extends ArrayAccessTranslator implements CachedAccessTranslator {
032    
033        @NotNull
034        private final TemporaryVariable arrayExpression;
035        @NotNull
036        private final List<TemporaryVariable> indexExpressions;
037    
038        /*package*/ CachedArrayAccessTranslator(@NotNull JetArrayAccessExpression expression,
039                                                @NotNull TranslationContext context) {
040            super(expression, context);
041            arrayExpression = context.declareTemporary(translateArrayExpression());
042            indexExpressions = fromExpressionList(translateIndexExpressions(), context);
043        }
044    
045        @NotNull
046        @Override
047        public JsExpression translateAsGet() {
048            return translateAsGet(arrayExpression.reference(), toExpressionList(indexExpressions));
049        }
050    
051        @NotNull
052        @Override
053        public JsExpression translateAsSet(@NotNull JsExpression setTo) {
054            return translateAsSet(arrayExpression.reference(), toExpressionList(indexExpressions), setTo);
055        }
056    
057        @NotNull
058        @Override
059        public List<TemporaryVariable> declaredTemporaries() {
060            List<TemporaryVariable> result = Lists.newArrayList();
061            result.add(arrayExpression);
062            result.addAll(indexExpressions);
063            return result;
064        }
065    }