1 /* 2 * Copyright (C) 2014 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.internal.codegen; 18 19 import static com.google.common.base.Verify.verify; 20 import static dagger.internal.codegen.SourceFiles.classFileName; 21 22 import com.squareup.javapoet.ClassName; 23 import com.squareup.javapoet.TypeSpec; 24 import dagger.Component; 25 import dagger.internal.codegen.langmodel.DaggerElements; 26 import java.util.Optional; 27 import javax.annotation.processing.Filer; 28 import javax.inject.Inject; 29 import javax.lang.model.SourceVersion; 30 import javax.lang.model.element.Element; 31 import javax.lang.model.element.TypeElement; 32 33 /** 34 * Generates the implementation of the abstract types annotated with {@link Component}. 35 */ 36 final class ComponentGenerator extends SourceFileGenerator<BindingGraph> { 37 private final ComponentImplementationFactory componentImplementationFactory; 38 39 @Inject ComponentGenerator( Filer filer, DaggerElements elements, SourceVersion sourceVersion, ComponentImplementationFactory componentImplementationFactory)40 ComponentGenerator( 41 Filer filer, 42 DaggerElements elements, 43 SourceVersion sourceVersion, 44 ComponentImplementationFactory componentImplementationFactory) { 45 super(filer, elements, sourceVersion); 46 this.componentImplementationFactory = componentImplementationFactory; 47 } 48 49 @Override nameGeneratedType(BindingGraph input)50 ClassName nameGeneratedType(BindingGraph input) { 51 return componentName(input.componentTypeElement()); 52 } 53 componentName(TypeElement componentDefinitionType)54 static ClassName componentName(TypeElement componentDefinitionType) { 55 ClassName componentName = ClassName.get(componentDefinitionType); 56 return ClassName.get(componentName.packageName(), "Dagger" + classFileName(componentName)); 57 } 58 59 @Override originatingElement(BindingGraph input)60 Element originatingElement(BindingGraph input) { 61 return input.componentTypeElement(); 62 } 63 64 @Override write(ClassName componentName, BindingGraph bindingGraph)65 Optional<TypeSpec.Builder> write(ClassName componentName, BindingGraph bindingGraph) { 66 ComponentImplementation componentImplementation = 67 componentImplementationFactory.createComponentImplementation(bindingGraph); 68 verify(componentImplementation.name().equals(componentName)); 69 return Optional.of(componentImplementation.generate()); 70 } 71 } 72