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 017package org.jetbrains.jet.lang.resolve.java; 018 019import com.google.common.collect.ImmutableBiMap; 020import org.jetbrains.annotations.NotNull; 021import org.jetbrains.jet.lang.descriptors.ClassDescriptor; 022 023public class CollectionClassMapping extends JavaToKotlinClassMapBuilder { 024 private static CollectionClassMapping instance = null; 025 026 @NotNull 027 public static CollectionClassMapping getInstance() { 028 if (instance == null) { 029 instance = new CollectionClassMapping(); 030 } 031 return instance; 032 } 033 034 private ImmutableBiMap.Builder<ClassDescriptor, ClassDescriptor> mapBuilder = ImmutableBiMap.builder(); 035 private final ImmutableBiMap<ClassDescriptor, ClassDescriptor> mutableToReadOnlyMap; 036 037 private CollectionClassMapping() { 038 init(); 039 mutableToReadOnlyMap = mapBuilder.build(); 040 mapBuilder = null; 041 } 042 043 @Override 044 protected void register(@NotNull Class<?> javaClass, @NotNull ClassDescriptor kotlinDescriptor, @NotNull Direction direction) { 045 // do nothing 046 } 047 048 @Override 049 protected void register( 050 @NotNull Class<?> javaClass, 051 @NotNull ClassDescriptor kotlinDescriptor, 052 @NotNull ClassDescriptor kotlinMutableDescriptor, 053 @NotNull Direction direction 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}