1 /* 2 * Copyright (C) 2022 The Dagger Authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package dagger.hilt.processor.internal.kotlin; 18 19 20 21 import androidx.room.compiler.processing.XElement; 22 import androidx.room.compiler.processing.XTypeElement; 23 import dagger.hilt.processor.internal.ClassNames; 24 import dagger.internal.codegen.xprocessing.XElements; 25 import java.util.HashMap; 26 import java.util.Map; 27 import javax.inject.Inject; 28 import javax.inject.Singleton; 29 30 /** 31 * Factory creating Kotlin metadata data objects. 32 * 33 * <p>The metadata is cache since it can be expensive to parse the information stored in a proto 34 * binary string format in the metadata annotation values. 35 */ 36 @Singleton 37 public final class KotlinMetadataFactory { 38 private final Map<XTypeElement, KotlinMetadata> metadataCache = new HashMap<>(); 39 40 @Inject KotlinMetadataFactory()41 KotlinMetadataFactory() {} 42 43 /** 44 * Parses and returns the {@link KotlinMetadata} out of a given element. 45 * 46 * @throws IllegalStateException if the element has no metadata or is not enclosed in a type 47 * element with metadata. To check if an element has metadata use {@link 48 * KotlinMetadataUtil#hasMetadata(XElement)} 49 */ create(XElement element)50 public KotlinMetadata create(XElement element) { 51 XTypeElement enclosingElement = XElements.closestEnclosingTypeElement(element); 52 if (!enclosingElement.hasAnnotation(ClassNames.KOTLIN_METADATA)) { 53 throw new IllegalStateException("Missing @Metadata for: " + enclosingElement); 54 } 55 return metadataCache.computeIfAbsent(enclosingElement, KotlinMetadata::from); 56 } 57 } 58