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.resolve.jvm.kotlinSignature; 018 019 import com.google.common.collect.ImmutableBiMap; 020 import org.jetbrains.annotations.NotNull; 021 import org.jetbrains.kotlin.descriptors.ClassDescriptor; 022 import org.jetbrains.kotlin.platform.JavaToKotlinClassMapBuilder; 023 024 public class CollectionClassMapping extends JavaToKotlinClassMapBuilder { 025 private static CollectionClassMapping instance = null; 026 027 @NotNull 028 public static CollectionClassMapping getInstance() { 029 if (instance == null) { 030 instance = new CollectionClassMapping(); 031 } 032 return instance; 033 } 034 035 private ImmutableBiMap.Builder<ClassDescriptor, ClassDescriptor> mapBuilder = ImmutableBiMap.builder(); 036 private final ImmutableBiMap<ClassDescriptor, ClassDescriptor> mutableToReadOnlyMap; 037 038 private CollectionClassMapping() { 039 init(); 040 mutableToReadOnlyMap = mapBuilder.build(); 041 mapBuilder = null; 042 } 043 044 @Override 045 protected void register(@NotNull Class<?> javaClass, @NotNull ClassDescriptor kotlinDescriptor, @NotNull Direction direction) { 046 // do nothing 047 } 048 049 @Override 050 protected void register( 051 @NotNull Class<?> javaClass, 052 @NotNull ClassDescriptor kotlinDescriptor, 053 @NotNull ClassDescriptor kotlinMutableDescriptor 054 ) { 055 mapBuilder.put(kotlinMutableDescriptor, kotlinDescriptor); 056 } 057 058 public boolean isMutableCollection(@NotNull ClassDescriptor mutable) { 059 return mutableToReadOnlyMap.containsKey(mutable); 060 } 061 062 public boolean isReadOnlyCollection(@NotNull ClassDescriptor immutable) { 063 return mutableToReadOnlyMap.containsValue(immutable); 064 } 065 066 @NotNull 067 public ClassDescriptor convertMutableToReadOnly(@NotNull ClassDescriptor mutable) { 068 ClassDescriptor readOnly = mutableToReadOnlyMap.get(mutable); 069 if (readOnly == null) { 070 throw new IllegalArgumentException("Given class " + mutable + " is not a mutable collection"); 071 } 072 return readOnly; 073 } 074 075 @NotNull 076 public ClassDescriptor convertReadOnlyToMutable(@NotNull ClassDescriptor readOnly) { 077 ClassDescriptor mutable = mutableToReadOnlyMap.inverse().get(readOnly); 078 if (mutable == null) { 079 throw new IllegalArgumentException("Given class " + readOnly + " is not a read-only collection"); 080 } 081 return mutable; 082 } 083 }