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.jet.codegen.intrinsics;
018    
019    import com.google.common.collect.ImmutableList;
020    import org.jetbrains.annotations.NotNull;
021    import org.jetbrains.annotations.Nullable;
022    import org.jetbrains.jet.codegen.RangeCodegenUtil;
023    import org.jetbrains.jet.lang.descriptors.CallableMemberDescriptor;
024    import org.jetbrains.jet.lang.descriptors.SimpleFunctionDescriptor;
025    import org.jetbrains.jet.lang.resolve.CompileTimeConstantUtils;
026    import org.jetbrains.jet.lang.resolve.java.JvmPrimitiveType;
027    import org.jetbrains.jet.lang.resolve.name.FqName;
028    import org.jetbrains.jet.lang.resolve.name.FqNameUnsafe;
029    import org.jetbrains.jet.lang.resolve.name.Name;
030    import org.jetbrains.jet.lang.resolve.name.SpecialNames;
031    import org.jetbrains.jet.lang.types.expressions.OperatorConventions;
032    import org.jetbrains.jet.lang.types.lang.KotlinBuiltIns;
033    import org.jetbrains.jet.lang.types.lang.PrimitiveType;
034    
035    import javax.annotation.PostConstruct;
036    import java.util.HashMap;
037    import java.util.Map;
038    
039    import static org.jetbrains.asm4.Opcodes.*;
040    import static org.jetbrains.jet.lang.resolve.DescriptorUtils.*;
041    import static org.jetbrains.jet.lang.types.lang.KotlinBuiltIns.BUILT_INS_PACKAGE_FQ_NAME;
042    
043    public class IntrinsicMethods {
044        private static final IntrinsicMethod UNARY_MINUS = new UnaryMinus();
045        private static final IntrinsicMethod UNARY_PLUS = new UnaryPlus();
046        private static final IntrinsicMethod NUMBER_CAST = new NumberCast();
047        private static final IntrinsicMethod INV = new Inv();
048        private static final IntrinsicMethod RANGE_TO = new RangeTo();
049        private static final IntrinsicMethod INC = new Increment(1);
050        private static final IntrinsicMethod DEC = new Increment(-1);
051        private static final IntrinsicMethod HASH_CODE = new HashCode();
052    
053        private static final IntrinsicMethod ARRAY_SIZE = new ArraySize();
054        private static final IntrinsicMethod ARRAY_INDICES = new ArrayIndices();
055        private static final Equals EQUALS = new Equals();
056        private static final IdentityEquals IDENTITY_EQUALS = new IdentityEquals();
057        private static final IteratorNext ITERATOR_NEXT = new IteratorNext();
058        private static final ArraySet ARRAY_SET = new ArraySet();
059        private static final ArrayGet ARRAY_GET = new ArrayGet();
060        private static final StringPlus STRING_PLUS = new StringPlus();
061        public static final String KOTLIN_JAVA_CLASS_FUNCTION = "kotlin.javaClass.function";
062        private static final String KOTLIN_JAVA_CLASS_PROPERTY = "kotlin.javaClass.property";
063        public static final String KOTLIN_ARRAYS_ARRAY = "kotlin.arrays.array";
064        public static final String KOTLIN_COPY_TO_ARRAY = "kotlin.collections.copyToArray";
065        private static final String KOTLIN_TO_STRING = "kotlin.toString";
066        private static final String KOTLIN_HASH_CODE = "kotlin.hashCode";
067        private static final EnumValues ENUM_VALUES = new EnumValues();
068        private static final EnumValueOf ENUM_VALUE_OF = new EnumValueOf();
069        private static final ToString TO_STRING = new ToString();
070    
071        private final Map<String, IntrinsicMethod> namedMethods = new HashMap<String, IntrinsicMethod>();
072        private static final IntrinsicMethod ARRAY_ITERATOR = new ArrayIterator();
073        private final IntrinsicsMap intrinsicsMap = new IntrinsicsMap();
074    
075    
076        @PostConstruct
077        public void init() {
078            namedMethods.put(KOTLIN_JAVA_CLASS_FUNCTION, new JavaClassFunction());
079            namedMethods.put(KOTLIN_JAVA_CLASS_PROPERTY, new JavaClassProperty());
080            namedMethods.put(KOTLIN_ARRAYS_ARRAY, new JavaClassArray());
081            namedMethods.put(KOTLIN_COPY_TO_ARRAY, new CopyToArray());
082            namedMethods.put(KOTLIN_HASH_CODE, HASH_CODE);
083            namedMethods.put(KOTLIN_TO_STRING, TO_STRING);
084    
085            ImmutableList<Name> primitiveCastMethods = OperatorConventions.NUMBER_CONVERSIONS.asList();
086            for (Name method : primitiveCastMethods) {
087                declareIntrinsicFunction(Name.identifier("Number"), method, 0, NUMBER_CAST);
088                for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
089                    declareIntrinsicFunction(type.getTypeName(), method, 0, NUMBER_CAST);
090                }
091            }
092    
093            for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
094                Name typeName = type.getTypeName();
095                declareIntrinsicFunction(typeName, Name.identifier("plus"), 0, UNARY_PLUS);
096                declareIntrinsicFunction(typeName, Name.identifier("minus"), 0, UNARY_MINUS);
097                declareIntrinsicFunction(typeName, Name.identifier("inv"), 0, INV);
098                declareIntrinsicFunction(typeName, Name.identifier("rangeTo"), 1, RANGE_TO);
099                declareIntrinsicFunction(typeName, Name.identifier("inc"), 0, INC);
100                declareIntrinsicFunction(typeName, Name.identifier("dec"), 0, DEC);
101                declareIntrinsicFunction(typeName, Name.identifier("hashCode"), 0, HASH_CODE);
102                declareIntrinsicFunction(typeName, Name.identifier("equals"), 1, EQUALS);
103            }
104    
105            declareBinaryOp(Name.identifier("plus"), IADD);
106            declareBinaryOp(Name.identifier("minus"), ISUB);
107            declareBinaryOp(Name.identifier("times"), IMUL);
108            declareBinaryOp(Name.identifier("div"), IDIV);
109            declareBinaryOp(Name.identifier("mod"), IREM);
110            declareBinaryOp(Name.identifier("shl"), ISHL);
111            declareBinaryOp(Name.identifier("shr"), ISHR);
112            declareBinaryOp(Name.identifier("ushr"), IUSHR);
113            declareBinaryOp(Name.identifier("and"), IAND);
114            declareBinaryOp(Name.identifier("or"), IOR);
115            declareBinaryOp(Name.identifier("xor"), IXOR);
116    
117            declareIntrinsicFunction(Name.identifier("Boolean"), Name.identifier("not"), 0, new Not());
118            declareIntrinsicFunction(Name.identifier("Boolean"), Name.identifier("equals"), 1, EQUALS);
119    
120            declareIntrinsicFunction(Name.identifier("String"), Name.identifier("plus"), 1, new Concat());
121            declareIntrinsicFunction(Name.identifier("CharSequence"), Name.identifier("get"), 1, new StringGetChar());
122            declareIntrinsicFunction(Name.identifier("String"), Name.identifier("get"), 1, new StringGetChar());
123    
124            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("toString"), 0, TO_STRING);
125            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("equals"), 1, EQUALS);
126            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("identityEquals"), 1, IDENTITY_EQUALS);
127            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("plus"), 1, STRING_PLUS);
128            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("arrayOfNulls"), 1, new NewArray());
129            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("synchronized"), 2, new StupidSync());
130            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, Name.identifier("iterator"), 0, new IteratorIterator());
131    
132            for (PrimitiveType type : PrimitiveType.values()) {
133                declareIntrinsicFunction(type.getTypeName(), Name.identifier("compareTo"), 1, new CompareTo());
134                declareIntrinsicFunction(Name.identifier(type.getTypeName() + "Iterator"), Name.identifier("next"), 0, ITERATOR_NEXT);
135            }
136    
137            declareIntrinsicProperty(Name.identifier("CharSequence"), Name.identifier("length"), new StringLength());
138            declareIntrinsicProperty(Name.identifier("String"), Name.identifier("length"), new StringLength());
139    
140            registerStaticField(getFqNameSafe(KotlinBuiltIns.getInstance().getUnit()), Name.identifier("VALUE"));
141    
142            for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
143                FqName rangeClassFqName = RangeCodegenUtil.getRangeClassFqName(type);
144                FqName progressionClassFqName = RangeCodegenUtil.getProgressionClassFqName(type);
145    
146                registerStaticField(rangeClassFqName, Name.identifier("EMPTY"));
147    
148                registerRangeOrProgressionProperty(rangeClassFqName, Name.identifier("start"));
149                registerRangeOrProgressionProperty(rangeClassFqName, Name.identifier("end"));
150    
151                registerRangeOrProgressionProperty(progressionClassFqName, Name.identifier("start"));
152                registerRangeOrProgressionProperty(progressionClassFqName, Name.identifier("end"));
153                registerRangeOrProgressionProperty(progressionClassFqName, Name.identifier("increment"));
154            }
155    
156            declareArrayMethods();
157        }
158    
159        private void registerStaticField(@NotNull FqName classFqName, @NotNull Name propertyName) {
160            FqNameUnsafe classObjectFqName = classFqName.toUnsafe().child(SpecialNames.getClassObjectName(classFqName.shortName()));
161            intrinsicsMap.registerIntrinsic(classObjectFqName, propertyName, -1, new StaticField(classFqName, propertyName));
162        }
163    
164        private void registerRangeOrProgressionProperty(@NotNull FqName ownerClass, @NotNull Name propertyName) {
165            intrinsicsMap.registerIntrinsic(ownerClass, propertyName, -1, new PropertyOfProgressionOrRange(ownerClass, propertyName));
166        }
167    
168        private void declareArrayMethods() {
169    
170            for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
171                declareArrayMethodsForPrimitive(jvmPrimitiveType);
172            }
173    
174            declareIntrinsicProperty(Name.identifier("Array"), Name.identifier("size"), ARRAY_SIZE);
175            declareIntrinsicProperty(Name.identifier("Array"), Name.identifier("indices"), ARRAY_INDICES);
176            declareIntrinsicFunction(Name.identifier("Array"), Name.identifier("set"), 2, ARRAY_SET);
177            declareIntrinsicFunction(Name.identifier("Array"), Name.identifier("get"), 1, ARRAY_GET);
178            declareIterator(Name.identifier("Array"));
179        }
180    
181        private void declareArrayMethodsForPrimitive(JvmPrimitiveType jvmPrimitiveType) {
182            PrimitiveType primitiveType = jvmPrimitiveType.getPrimitiveType();
183            declareIntrinsicProperty(primitiveType.getArrayTypeName(), Name.identifier("size"), ARRAY_SIZE);
184            declareIntrinsicProperty(primitiveType.getArrayTypeName(), Name.identifier("indices"), ARRAY_INDICES);
185            declareIntrinsicFunction(primitiveType.getArrayTypeName(), Name.identifier("set"), 2, ARRAY_SET);
186            declareIntrinsicFunction(primitiveType.getArrayTypeName(), Name.identifier("get"), 1, ARRAY_GET);
187            declareIterator(primitiveType.getArrayTypeName());
188        }
189    
190        private void declareIterator(@NotNull Name arrayClassName) {
191            declareIntrinsicFunction(arrayClassName, Name.identifier("iterator"), 0, ARRAY_ITERATOR);
192        }
193    
194        private void declareBinaryOp(Name methodName, int opcode) {
195            BinaryOp op = new BinaryOp(opcode);
196            for (PrimitiveType type : PrimitiveType.values()) {
197                declareIntrinsicFunction(type.getTypeName(), methodName, 1, op);
198            }
199        }
200    
201        private void declareIntrinsicProperty(Name className, Name methodName, IntrinsicMethod implementation) {
202            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME.child(className), methodName, -1, implementation);
203        }
204    
205        private void declareIntrinsicFunction(Name className, Name functionName, int arity, IntrinsicMethod implementation) {
206            intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME.child(className), functionName, arity, implementation);
207        }
208    
209        @Nullable
210        public IntrinsicMethod getIntrinsic(@NotNull CallableMemberDescriptor descriptor) {
211            IntrinsicMethod intrinsicMethod = intrinsicsMap.getIntrinsic(descriptor);
212            if (intrinsicMethod != null) {
213                return intrinsicMethod;
214            }
215    
216            if (descriptor instanceof SimpleFunctionDescriptor) {
217                SimpleFunctionDescriptor functionDescriptor = (SimpleFunctionDescriptor) descriptor;
218    
219                if (isEnumClassObject(functionDescriptor.getContainingDeclaration())) {
220                    if (isEnumValuesMethod(functionDescriptor)) {
221                        return ENUM_VALUES;
222                    }
223    
224                    if (isEnumValueOfMethod(functionDescriptor)) {
225                        return ENUM_VALUE_OF;
226                    }
227                }
228            }
229    
230            String value = CompileTimeConstantUtils.getIntrinsicAnnotationArgument(descriptor);
231            if (value == null) return null;
232    
233            return namedMethods.get(value);
234        }
235    }