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.platform;
018    
019    import org.jetbrains.annotations.NotNull;
020    import org.jetbrains.annotations.Nullable;
021    import org.jetbrains.kotlin.builtins.CompanionObjectMapping;
022    import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
023    import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor;
024    import org.jetbrains.kotlin.descriptors.ClassDescriptor;
025    import org.jetbrains.kotlin.name.ClassId;
026    import org.jetbrains.kotlin.name.FqName;
027    import org.jetbrains.kotlin.name.FqNameUnsafe;
028    import org.jetbrains.kotlin.name.Name;
029    import org.jetbrains.kotlin.resolve.DescriptorUtils;
030    import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
031    import org.jetbrains.kotlin.types.KotlinType;
032    import org.jetbrains.kotlin.types.TypeUtils;
033    
034    import java.lang.annotation.Annotation;
035    import java.util.*;
036    
037    public class JavaToKotlinClassMap implements PlatformToKotlinClassMap {
038        public static final JavaToKotlinClassMap INSTANCE = new JavaToKotlinClassMap();
039    
040        private final Map<FqName, ClassDescriptor> javaToKotlin = new HashMap<FqName, ClassDescriptor>();
041        private final Map<FqNameUnsafe, ClassId> kotlinToJava = new HashMap<FqNameUnsafe, ClassId>();
042    
043        private final Map<ClassDescriptor, ClassDescriptor> mutableToReadOnly = new HashMap<ClassDescriptor, ClassDescriptor>();
044        private final Map<ClassDescriptor, ClassDescriptor> readOnlyToMutable = new HashMap<ClassDescriptor, ClassDescriptor>();
045    
046        private JavaToKotlinClassMap() {
047            KotlinBuiltIns builtIns = JvmBuiltIns.getInstance();
048    
049            add(Object.class, builtIns.getAny());
050            add(String.class, builtIns.getString());
051            add(CharSequence.class, builtIns.getCharSequence());
052            add(Throwable.class, builtIns.getThrowable());
053            add(Cloneable.class, builtIns.getCloneable());
054            add(Number.class, builtIns.getNumber());
055            add(Comparable.class, builtIns.getComparable());
056            add(Enum.class, builtIns.getEnum());
057            add(Annotation.class, builtIns.getAnnotation());
058    
059            add(Iterable.class, builtIns.getIterable(), builtIns.getMutableIterable());
060            add(Iterator.class, builtIns.getIterator(), builtIns.getMutableIterator());
061            add(Collection.class, builtIns.getCollection(), builtIns.getMutableCollection());
062            add(List.class, builtIns.getList(), builtIns.getMutableList());
063            add(Set.class, builtIns.getSet(), builtIns.getMutableSet());
064            add(Map.class, builtIns.getMap(), builtIns.getMutableMap());
065            add(Map.Entry.class, builtIns.getMapEntry(), builtIns.getMutableMapEntry());
066            add(ListIterator.class, builtIns.getListIterator(), builtIns.getMutableListIterator());
067    
068            for (JvmPrimitiveType jvmType : JvmPrimitiveType.values()) {
069                add(ClassId.topLevel(jvmType.getWrapperFqName()), builtIns.getPrimitiveClassDescriptor(jvmType.getPrimitiveType()));
070            }
071    
072            CompanionObjectMapping companionObjectMapping = new CompanionObjectMapping(builtIns);
073            for (ClassDescriptor descriptor : companionObjectMapping.allClassesWithIntrinsicCompanions()) {
074                ClassDescriptor companion = descriptor.getCompanionObjectDescriptor();
075                assert companion != null : "No companion object found for " + descriptor;
076                add(ClassId.topLevel(new FqName("kotlin.jvm.internal." + descriptor.getName().asString() + "CompanionObject")), companion);
077            }
078    
079            // TODO: support also functions with >= 23 parameters
080            for (int i = 0; i < 23; i++) {
081                add(ClassId.topLevel(new FqName("kotlin.jvm.functions.Function" + i)), builtIns.getFunction(i));
082    
083                FunctionClassDescriptor.Kind kFunction = FunctionClassDescriptor.Kind.KFunction;
084                String kFun = kFunction.getPackageFqName() + "." + kFunction.getClassNamePrefix();
085                addKotlinToJava(new FqNameUnsafe(kFun + i), ClassId.topLevel(new FqName(kFun)));
086            }
087    
088            addKotlinToJava(builtIns.getNothing(), classId(Void.class));
089        }
090    
091        /**
092         * E.g.
093         * java.lang.String -> kotlin.String
094         * java.lang.Integer -> kotlin.Int
095         * kotlin.jvm.internal.IntCompanionObject -> kotlin.Int.Companion
096         * java.util.List -> kotlin.List
097         * java.util.Map.Entry -> kotlin.Map.Entry
098         * java.lang.Void -> null
099         * kotlin.jvm.functions.Function3 -> kotlin.Function3
100         */
101        @Nullable
102        public ClassDescriptor mapJavaToKotlin(@NotNull FqName fqName) {
103            return javaToKotlin.get(fqName);
104        }
105    
106        /**
107         * E.g.
108         * kotlin.Throwable -> java.lang.Throwable
109         * kotlin.Int -> java.lang.Integer
110         * kotlin.Int.Companion -> kotlin.jvm.internal.IntCompanionObject
111         * kotlin.Nothing -> java.lang.Void
112         * kotlin.IntArray -> null
113         * kotlin.Function3 -> kotlin.jvm.functions.Function3
114         * kotlin.reflect.KFunction3 -> kotlin.reflect.KFunction
115         */
116        @Nullable
117        public ClassId mapKotlinToJava(@NotNull FqNameUnsafe kotlinFqName) {
118            return kotlinToJava.get(kotlinFqName);
119        }
120    
121        private void add(
122                @NotNull Class<?> javaClass,
123                @NotNull ClassDescriptor kotlinDescriptor,
124                @NotNull ClassDescriptor kotlinMutableDescriptor
125        ) {
126            ClassId javaClassId = classId(javaClass);
127    
128            add(javaClassId, kotlinDescriptor);
129            addKotlinToJava(kotlinMutableDescriptor, javaClassId);
130    
131            mutableToReadOnly.put(kotlinMutableDescriptor, kotlinDescriptor);
132            readOnlyToMutable.put(kotlinDescriptor, kotlinMutableDescriptor);
133        }
134    
135        private void add(@NotNull ClassId javaClassId, @NotNull ClassDescriptor kotlinDescriptor) {
136            addJavaToKotlin(javaClassId, kotlinDescriptor);
137            addKotlinToJava(kotlinDescriptor, javaClassId);
138        }
139    
140        private void add(@NotNull Class<?> javaClass, @NotNull ClassDescriptor kotlinDescriptor) {
141            add(classId(javaClass), kotlinDescriptor);
142        }
143    
144        private void addJavaToKotlin(@NotNull ClassId javaClassId, @NotNull ClassDescriptor kotlinDescriptor) {
145            javaToKotlin.put(javaClassId.asSingleFqName(), kotlinDescriptor);
146        }
147    
148        private void addKotlinToJava(@NotNull ClassDescriptor kotlinDescriptor, @NotNull ClassId javaClassId) {
149            addKotlinToJava(DescriptorUtils.getFqName(kotlinDescriptor), javaClassId);
150        }
151    
152        private void addKotlinToJava(@NotNull FqNameUnsafe kotlinFqName, @NotNull ClassId javaClassId) {
153            kotlinToJava.put(kotlinFqName, javaClassId);
154        }
155    
156        @NotNull
157        private static ClassId classId(@NotNull Class<?> clazz) {
158            assert !clazz.isPrimitive() && !clazz.isArray() : "Invalid class: " + clazz;
159            Class<?> outer = clazz.getDeclaringClass();
160            return outer == null
161                   ? ClassId.topLevel(new FqName(clazz.getCanonicalName()))
162                   : classId(outer).createNestedClassId(Name.identifier(clazz.getSimpleName()));
163        }
164    
165        @NotNull
166        public Collection<ClassDescriptor> mapPlatformClass(@NotNull FqName fqName) {
167            ClassDescriptor kotlinAnalog = mapJavaToKotlin(fqName);
168            if (kotlinAnalog == null) return Collections.emptySet();
169    
170            ClassDescriptor kotlinMutableAnalog = readOnlyToMutable.get(kotlinAnalog);
171            if (kotlinMutableAnalog == null) return Collections.singleton(kotlinAnalog);
172    
173            return Arrays.asList(kotlinAnalog, kotlinMutableAnalog);
174        }
175    
176        @Override
177        @NotNull
178        public Collection<ClassDescriptor> mapPlatformClass(@NotNull ClassDescriptor classDescriptor) {
179            FqNameUnsafe className = DescriptorUtils.getFqName(classDescriptor);
180            return className.isSafe() ? mapPlatformClass(className.toSafe()) : Collections.<ClassDescriptor>emptySet();
181        }
182    
183        public boolean isMutable(@NotNull ClassDescriptor mutable) {
184            return mutableToReadOnly.containsKey(mutable);
185        }
186    
187        public boolean isMutable(@NotNull KotlinType type) {
188            ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type);
189            return classDescriptor != null && isMutable(classDescriptor);
190        }
191    
192        public boolean isReadOnly(@NotNull ClassDescriptor readOnly) {
193            return readOnlyToMutable.containsKey(readOnly);
194        }
195    
196        public boolean isReadOnly(@NotNull KotlinType type) {
197            ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type);
198            return classDescriptor != null && isReadOnly(classDescriptor);
199        }
200    
201        @NotNull
202        public ClassDescriptor convertMutableToReadOnly(@NotNull ClassDescriptor mutable) {
203            ClassDescriptor readOnly = mutableToReadOnly.get(mutable);
204            if (readOnly == null) {
205                throw new IllegalArgumentException("Given class " + mutable + " is not a mutable collection");
206            }
207            return readOnly;
208        }
209    
210        @NotNull
211        public ClassDescriptor convertReadOnlyToMutable(@NotNull ClassDescriptor readOnly) {
212            ClassDescriptor mutable = readOnlyToMutable.get(readOnly);
213            if (mutable == null) {
214                throw new IllegalArgumentException("Given class " + readOnly + " is not a read-only collection");
215            }
216            return mutable;
217        }
218    }