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.codegen.when; 018 019 import org.jetbrains.annotations.NotNull; 020 import org.jetbrains.kotlin.descriptors.ClassDescriptor; 021 import org.jetbrains.kotlin.resolve.constants.EnumValue; 022 023 import java.util.LinkedHashMap; 024 import java.util.Map; 025 026 public class WhenByEnumsMapping { 027 private static final String MAPPING_ARRAY_FIELD_PREFIX = "$EnumSwitchMapping$"; 028 private static final String MAPPINGS_CLASS_NAME_POSTFIX = "$WhenMappings"; 029 030 private final Map<EnumValue, Integer> map = new LinkedHashMap<EnumValue, Integer>(); 031 private final ClassDescriptor enumClassDescriptor; 032 private final String outerClassInternalNameForExpression; 033 private final String mappingsClassInternalName; 034 private final int fieldNumber; 035 036 public WhenByEnumsMapping( 037 @NotNull ClassDescriptor enumClassDescriptor, 038 @NotNull String outerClassInternalNameForExpression, 039 int fieldNumber 040 ) { 041 this.enumClassDescriptor = enumClassDescriptor; 042 this.outerClassInternalNameForExpression = outerClassInternalNameForExpression; 043 this.mappingsClassInternalName = outerClassInternalNameForExpression + MAPPINGS_CLASS_NAME_POSTFIX; 044 this.fieldNumber = fieldNumber; 045 } 046 047 public int getIndexByEntry(@NotNull EnumValue value) { 048 Integer result = map.get(value); 049 assert result != null : "entry " + value + " has no mapping"; 050 return result; 051 } 052 053 public void putFirstTime(@NotNull EnumValue value, int index) { 054 if (!map.containsKey(value)) { 055 map.put(value, index); 056 } 057 } 058 059 public int size() { 060 return map.size(); 061 } 062 063 @NotNull 064 public String getFieldName() { 065 return MAPPING_ARRAY_FIELD_PREFIX + fieldNumber; 066 } 067 068 @NotNull 069 public ClassDescriptor getEnumClassDescriptor() { 070 return enumClassDescriptor; 071 } 072 073 @NotNull 074 public String getOuterClassInternalNameForExpression() { 075 return outerClassInternalNameForExpression; 076 } 077 078 @NotNull 079 public String getMappingsClassInternalName() { 080 return mappingsClassInternalName; 081 } 082 083 @NotNull 084 public Iterable<Map.Entry<EnumValue, Integer>> enumValuesToIntMapping() { 085 return map.entrySet(); 086 } 087 }