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.intrinsic.functions.factories;
018    
019    import com.google.dart.compiler.backend.js.ast.*;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.annotations.Nullable;
022    import org.jetbrains.kotlin.builtins.PrimitiveType;
023    import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
024    import org.jetbrains.kotlin.descriptors.PropertyDescriptor;
025    import org.jetbrains.kotlin.js.descriptorUtils.DescriptorUtilsKt;
026    import org.jetbrains.kotlin.js.patterns.DescriptorPredicate;
027    import org.jetbrains.kotlin.js.patterns.NamePredicate;
028    import org.jetbrains.kotlin.js.resolve.JsPlatform;
029    import org.jetbrains.kotlin.js.translate.callTranslator.CallInfo;
030    import org.jetbrains.kotlin.js.translate.context.TranslationContext;
031    import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic;
032    import org.jetbrains.kotlin.js.translate.utils.AnnotationsUtils;
033    import org.jetbrains.kotlin.js.translate.utils.BindingUtils;
034    import org.jetbrains.kotlin.name.Name;
035    import org.jetbrains.kotlin.psi.KtExpression;
036    import org.jetbrains.kotlin.psi.KtQualifiedExpression;
037    import org.jetbrains.kotlin.psi.KtReferenceExpression;
038    import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall;
039    import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver;
040    import org.jetbrains.kotlin.resolve.scopes.receivers.Receiver;
041    import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue;
042    import org.jetbrains.kotlin.types.KotlinType;
043    
044    import java.util.List;
045    
046    import static org.jetbrains.kotlin.js.patterns.PatternBuilder.pattern;
047    import static org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsic.CallParametersAwareFunctionIntrinsic;
048    import static org.jetbrains.kotlin.js.translate.utils.ManglingUtils.getStableMangledNameForDescriptor;
049    
050    public final class TopLevelFIF extends CompositeFIF {
051        public static final DescriptorPredicate EQUALS_IN_ANY = pattern("kotlin", "Any", "equals");
052        @NotNull
053        public static final KotlinFunctionIntrinsic KOTLIN_EQUALS = new KotlinFunctionIntrinsic("equals");
054        @NotNull
055        public static final FunctionIntrinsic IDENTITY_EQUALS = new FunctionIntrinsic() {
056            @NotNull
057            @Override
058            public JsExpression apply(
059                    @Nullable JsExpression receiver, @NotNull List<JsExpression> arguments, @NotNull TranslationContext context
060            ) {
061                assert arguments.size() == 1 : "Unexpected argument size for kotlin.identityEquals: " + arguments.size();
062                return new JsBinaryOperation(JsBinaryOperator.REF_EQ, receiver, arguments.get(0));
063            }
064        };
065    
066        @NotNull
067        public static final DescriptorPredicate HASH_CODE_IN_ANY = pattern("kotlin", "Any", "hashCode");
068        @NotNull
069        public static final KotlinFunctionIntrinsic KOTLIN_HASH_CODE = new KotlinFunctionIntrinsic("hashCode");
070    
071        @NotNull
072        private static final FunctionIntrinsic RETURN_RECEIVER_INTRINSIC = new FunctionIntrinsic() {
073            @NotNull
074            @Override
075            public JsExpression apply(
076                    @Nullable JsExpression receiver,
077                    @NotNull List<JsExpression> arguments,
078                    @NotNull TranslationContext context
079            ) {
080                assert receiver != null;
081                return receiver;
082            }
083        };
084    
085        private static final FunctionIntrinsic NATIVE_MAP_GET = new NativeMapGetSet() {
086            @NotNull
087            @Override
088            protected String operationName() {
089                return "get";
090            }
091    
092            @Nullable
093            @Override
094            protected ExpressionReceiver getExpressionReceiver(@NotNull ResolvedCall<?> resolvedCall) {
095                ReceiverValue result = resolvedCall.getDispatchReceiver();
096                return result instanceof ExpressionReceiver ? (ExpressionReceiver) result : null;
097            }
098    
099            @Override
100            protected JsExpression asArrayAccess(
101                    @NotNull JsExpression receiver,
102                    @NotNull List<JsExpression> arguments,
103                    @NotNull TranslationContext context
104            ) {
105                return ArrayFIF.GET_INTRINSIC.apply(receiver, arguments, context);
106            }
107        };
108    
109        private static final FunctionIntrinsic NATIVE_MAP_SET = new NativeMapGetSet() {
110            @NotNull
111            @Override
112            protected String operationName() {
113                return "put";
114            }
115    
116            @Nullable
117            @Override
118            protected ExpressionReceiver getExpressionReceiver(@NotNull ResolvedCall<?> resolvedCall) {
119                Receiver result = resolvedCall.getExtensionReceiver();
120                return result instanceof ExpressionReceiver ? (ExpressionReceiver) result : null;
121            }
122    
123            @Override
124            protected JsExpression asArrayAccess(
125                    @NotNull JsExpression receiver,
126                    @NotNull List<JsExpression> arguments,
127                    @NotNull TranslationContext context
128            ) {
129                return ArrayFIF.SET_INTRINSIC.apply(receiver, arguments, context);
130            }
131        };
132    
133        @NotNull
134        public static final KotlinFunctionIntrinsic TO_STRING = new KotlinFunctionIntrinsic("toString");
135    
136        @NotNull
137        public static final FunctionIntrinsicFactory INSTANCE = new TopLevelFIF();
138    
139        private TopLevelFIF() {
140            add(EQUALS_IN_ANY, KOTLIN_EQUALS);
141            add(pattern("kotlin", "toString").isExtensionOf("kotlin.Any"), TO_STRING);
142            add(pattern("kotlin", "equals").isExtensionOf("kotlin.Any"), KOTLIN_EQUALS);
143            add(pattern("kotlin", "identityEquals").isExtensionOf("kotlin.Any"), IDENTITY_EQUALS);
144            add(HASH_CODE_IN_ANY, KOTLIN_HASH_CODE);
145            add(pattern(NamePredicate.PRIMITIVE_NUMBERS, "equals"), KOTLIN_EQUALS);
146            add(pattern("String|Boolean|Char|Number.equals"), KOTLIN_EQUALS);
147            add(pattern("kotlin", "arrayOfNulls"), new KotlinFunctionIntrinsic("nullArray"));
148            add(pattern("kotlin", "iterator").isExtensionOf("kotlin.Iterator"), RETURN_RECEIVER_INTRINSIC);
149    
150            add(pattern("kotlin", "Map", "get").checkOverridden(), NATIVE_MAP_GET);
151            add(pattern("kotlin.js", "set").isExtensionOf("kotlin.MutableMap"), NATIVE_MAP_SET);
152    
153            add(pattern("java.util", "HashMap", "<init>"), new MapSelectImplementationIntrinsic(false));
154            add(pattern("java.util", "HashSet", "<init>"), new MapSelectImplementationIntrinsic(true));
155    
156            add(pattern("kotlin.js", "Json", "get"), ArrayFIF.GET_INTRINSIC);
157            add(pattern("kotlin.js", "Json", "set"), ArrayFIF.SET_INTRINSIC);
158    
159            add(pattern("kotlin", "Throwable", "getMessage"), MESSAGE_PROPERTY_INTRINSIC);
160        }
161    
162        private abstract static class NativeMapGetSet extends CallParametersAwareFunctionIntrinsic {
163            @NotNull
164            protected abstract String operationName();
165    
166            @Nullable
167            protected abstract ExpressionReceiver getExpressionReceiver(@NotNull ResolvedCall<?> resolvedCall);
168    
169            protected abstract JsExpression asArrayAccess(
170                    @NotNull JsExpression receiver,
171                    @NotNull List<JsExpression> arguments,
172                    @NotNull TranslationContext context
173            );
174    
175            @NotNull
176            @Override
177            public JsExpression apply(@NotNull CallInfo callInfo, @NotNull List<JsExpression> arguments, @NotNull TranslationContext context) {
178                ExpressionReceiver expressionReceiver = getExpressionReceiver(callInfo.getResolvedCall());
179                JsExpression thisOrReceiver = getThisOrReceiverOrNull(callInfo);
180                assert thisOrReceiver != null;
181                if (expressionReceiver != null) {
182                    KtExpression expression = expressionReceiver.getExpression();
183                    KtReferenceExpression referenceExpression = null;
184                    if (expression instanceof KtReferenceExpression) {
185                        referenceExpression = (KtReferenceExpression) expression;
186                    }
187                    else if (expression instanceof KtQualifiedExpression) {
188                        KtExpression candidate = ((KtQualifiedExpression) expression).getReceiverExpression();
189                        if (candidate instanceof KtReferenceExpression) {
190                            referenceExpression = (KtReferenceExpression) candidate;
191                        }
192                    }
193    
194                    if (referenceExpression != null) {
195                        DeclarationDescriptor candidate = BindingUtils.getDescriptorForReferenceExpression(context.bindingContext(),
196                                                                                                           referenceExpression);
197                        if (candidate instanceof PropertyDescriptor && AnnotationsUtils.isNativeObject(candidate)) {
198                            return asArrayAccess(thisOrReceiver, arguments, context);
199                        }
200                    }
201                }
202    
203                String mangledName = getStableMangledNameForDescriptor(JsPlatform.INSTANCE$.getBuiltIns().getMutableMap(), operationName());
204    
205                return new JsInvocation(new JsNameRef(mangledName, thisOrReceiver), arguments);
206            }
207        }
208    
209        private static class MapSelectImplementationIntrinsic extends CallParametersAwareFunctionIntrinsic {
210            private final boolean isSet;
211    
212            private MapSelectImplementationIntrinsic(boolean isSet) {
213                this.isSet = isSet;
214            }
215    
216            @NotNull
217            @Override
218            public JsExpression apply(
219                    @NotNull CallInfo callInfo,
220                    @NotNull List<JsExpression> arguments,
221                    @NotNull TranslationContext context
222            ) {
223                KotlinType keyType = callInfo.getResolvedCall().getTypeArguments().values().iterator().next();
224                Name keyTypeName = DescriptorUtilsKt.getNameIfStandardType(keyType);
225                String collectionClassName = null;
226                if (keyTypeName != null) {
227                    if (NamePredicate.PRIMITIVE_NUMBERS.apply(keyTypeName)) {
228                        collectionClassName = isSet ? "PrimitiveNumberHashSet" : "PrimitiveNumberHashMap";
229                    }
230                    else if (PrimitiveType.BOOLEAN.getTypeName().equals(keyTypeName)) {
231                        collectionClassName = isSet ? "PrimitiveBooleanHashSet" : "PrimitiveBooleanHashMap";
232                    }
233                    else if (keyTypeName.asString().equals("String")) {
234                        collectionClassName = isSet ? "DefaultPrimitiveHashSet" : "DefaultPrimitiveHashMap";
235                    }
236                }
237    
238                if (collectionClassName == null ) {
239                    collectionClassName = isSet ? "ComplexHashSet" : "ComplexHashMap";
240                }
241    
242                return new JsNew(context.namer().kotlin(collectionClassName), arguments);
243            }
244        }
245    }