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.JetType;
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 = KotlinBuiltIns.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            for (ClassDescriptor descriptor : CompanionObjectMapping.allClassesWithIntrinsicCompanions()) {
073                ClassDescriptor companion = descriptor.getCompanionObjectDescriptor();
074                assert companion != null : "No companion object found for " + descriptor;
075                add(ClassId.topLevel(new FqName("kotlin.jvm.internal." + descriptor.getName().asString() + "CompanionObject")), companion);
076            }
077    
078            // TODO: support also functions with >= 23 parameters
079            for (int i = 0; i < 23; i++) {
080                add(ClassId.topLevel(new FqName("kotlin.jvm.functions.Function" + i)), builtIns.getFunction(i));
081    
082                FunctionClassDescriptor.Kind kFunction = FunctionClassDescriptor.Kind.KFunction;
083                String kFun = kFunction.getPackageFqName() + "." + kFunction.getClassNamePrefix();
084                addKotlinToJava(new FqNameUnsafe(kFun + i), ClassId.topLevel(new FqName(kFun)));
085            }
086    
087            addKotlinToJava(builtIns.getNothing(), classId(Void.class));
088        }
089    
090        /**
091         * E.g.
092         * java.lang.String -> kotlin.String
093         * java.lang.Integer -> kotlin.Int
094         * kotlin.jvm.internal.IntCompanionObject -> kotlin.Int.Companion
095         * java.util.List -> kotlin.List
096         * java.util.Map.Entry -> kotlin.Map.Entry
097         * java.lang.Void -> null
098         * kotlin.jvm.functions.Function3 -> kotlin.Function3
099         */
100        @Nullable
101        public ClassDescriptor mapJavaToKotlin(@NotNull FqName fqName) {
102            return javaToKotlin.get(fqName);
103        }
104    
105        /**
106         * E.g.
107         * kotlin.Throwable -> java.lang.Throwable
108         * kotlin.Int -> java.lang.Integer
109         * kotlin.Int.Companion -> kotlin.jvm.internal.IntCompanionObject
110         * kotlin.Nothing -> java.lang.Void
111         * kotlin.IntArray -> null
112         * kotlin.Function3 -> kotlin.jvm.functions.Function3
113         * kotlin.reflect.KFunction3 -> kotlin.reflect.KFunction
114         */
115        @Nullable
116        public ClassId mapKotlinToJava(@NotNull FqNameUnsafe kotlinFqName) {
117            return kotlinToJava.get(kotlinFqName);
118        }
119    
120        private void add(
121                @NotNull Class<?> javaClass,
122                @NotNull ClassDescriptor kotlinDescriptor,
123                @NotNull ClassDescriptor kotlinMutableDescriptor
124        ) {
125            ClassId javaClassId = classId(javaClass);
126    
127            add(javaClassId, kotlinDescriptor);
128            addKotlinToJava(kotlinMutableDescriptor, javaClassId);
129    
130            mutableToReadOnly.put(kotlinMutableDescriptor, kotlinDescriptor);
131            readOnlyToMutable.put(kotlinDescriptor, kotlinMutableDescriptor);
132        }
133    
134        private void add(@NotNull ClassId javaClassId, @NotNull ClassDescriptor kotlinDescriptor) {
135            addJavaToKotlin(javaClassId, kotlinDescriptor);
136            addKotlinToJava(kotlinDescriptor, javaClassId);
137        }
138    
139        private void add(@NotNull Class<?> javaClass, @NotNull ClassDescriptor kotlinDescriptor) {
140            add(classId(javaClass), kotlinDescriptor);
141        }
142    
143        private void addJavaToKotlin(@NotNull ClassId javaClassId, @NotNull ClassDescriptor kotlinDescriptor) {
144            javaToKotlin.put(javaClassId.asSingleFqName(), kotlinDescriptor);
145        }
146    
147        private void addKotlinToJava(@NotNull ClassDescriptor kotlinDescriptor, @NotNull ClassId javaClassId) {
148            addKotlinToJava(DescriptorUtils.getFqName(kotlinDescriptor), javaClassId);
149        }
150    
151        private void addKotlinToJava(@NotNull FqNameUnsafe kotlinFqName, @NotNull ClassId javaClassId) {
152            kotlinToJava.put(kotlinFqName, javaClassId);
153        }
154    
155        @NotNull
156        private static ClassId classId(@NotNull Class<?> clazz) {
157            assert !clazz.isPrimitive() && !clazz.isArray() : "Invalid class: " + clazz;
158            Class<?> outer = clazz.getDeclaringClass();
159            return outer == null
160                   ? ClassId.topLevel(new FqName(clazz.getCanonicalName()))
161                   : classId(outer).createNestedClassId(Name.identifier(clazz.getSimpleName()));
162        }
163    
164        @NotNull
165        public Collection<ClassDescriptor> mapPlatformClass(@NotNull FqName fqName) {
166            ClassDescriptor kotlinAnalog = mapJavaToKotlin(fqName);
167            if (kotlinAnalog == null) return Collections.emptySet();
168    
169            ClassDescriptor kotlinMutableAnalog = readOnlyToMutable.get(kotlinAnalog);
170            if (kotlinMutableAnalog == null) return Collections.singleton(kotlinAnalog);
171    
172            return Arrays.asList(kotlinAnalog, kotlinMutableAnalog);
173        }
174    
175        @Override
176        @NotNull
177        public Collection<ClassDescriptor> mapPlatformClass(@NotNull ClassDescriptor classDescriptor) {
178            FqNameUnsafe className = DescriptorUtils.getFqName(classDescriptor);
179            return className.isSafe() ? mapPlatformClass(className.toSafe()) : Collections.<ClassDescriptor>emptySet();
180        }
181    
182        public boolean isMutable(@NotNull ClassDescriptor mutable) {
183            return mutableToReadOnly.containsKey(mutable);
184        }
185    
186        public boolean isMutable(@NotNull JetType type) {
187            ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type);
188            return classDescriptor != null && isMutable(classDescriptor);
189        }
190    
191        public boolean isReadOnly(@NotNull ClassDescriptor readOnly) {
192            return readOnlyToMutable.containsKey(readOnly);
193        }
194    
195        public boolean isReadOnly(@NotNull JetType type) {
196            ClassDescriptor classDescriptor = TypeUtils.getClassDescriptor(type);
197            return classDescriptor != null && isReadOnly(classDescriptor);
198        }
199    
200        @NotNull
201        public ClassDescriptor convertMutableToReadOnly(@NotNull ClassDescriptor mutable) {
202            ClassDescriptor readOnly = mutableToReadOnly.get(mutable);
203            if (readOnly == null) {
204                throw new IllegalArgumentException("Given class " + mutable + " is not a mutable collection");
205            }
206            return readOnly;
207        }
208    
209        @NotNull
210        public ClassDescriptor convertReadOnlyToMutable(@NotNull ClassDescriptor readOnly) {
211            ClassDescriptor mutable = readOnlyToMutable.get(readOnly);
212            if (mutable == null) {
213                throw new IllegalArgumentException("Given class " + readOnly + " is not a read-only collection");
214            }
215            return mutable;
216        }
217    }