1 /* 2 * Copyright (C) 2014 Google, Inc. 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 package dagger.internal.codegen; 17 18 import com.google.common.base.Ascii; 19 import com.google.common.base.Function; 20 import dagger.Lazy; 21 import javax.inject.Provider; 22 23 /** 24 * Picks a reasonable name for what we think is being provided from the variable name associated 25 * with the {@link DependencyRequest}. I.e. strips out words like "lazy" and "provider" if we 26 * believe that those refer to {@link Lazy} and {@link Provider} rather than the type being 27 * provided. 28 * 29 * @author Gregory Kick 30 * @since 2.0 31 */ 32 //TODO(gak): develop the heuristics to get better names 33 final class DependencyVariableNamer implements Function<DependencyRequest, String> { 34 @Override apply(DependencyRequest dependency)35 public String apply(DependencyRequest dependency) { 36 if (dependency.overriddenVariableName().isPresent()) { 37 return dependency.overriddenVariableName().get(); 38 } 39 String variableName = dependency.requestElement().getSimpleName().toString(); 40 switch (dependency.kind()) { 41 case INSTANCE: 42 return variableName; 43 case LAZY: 44 return variableName.startsWith("lazy") && !variableName.equals("lazy") 45 ? Ascii.toLowerCase(variableName.charAt(4)) + variableName.substring(5) 46 : variableName; 47 case PROVIDER: 48 return variableName.endsWith("Provider") && !variableName.equals("Provider") 49 ? variableName.substring(0, variableName.length() - 8) 50 : variableName; 51 case MEMBERS_INJECTOR: 52 return variableName.endsWith("MembersInjector") && !variableName.equals("MembersInjector") 53 ? variableName.substring(0, variableName.length() - 15) 54 : variableName; 55 case PRODUCED: 56 return variableName.startsWith("produced") && !variableName.equals("produced") 57 ? Ascii.toLowerCase(variableName.charAt(8)) + variableName.substring(9) 58 : variableName; 59 case PRODUCER: 60 return variableName.endsWith("Producer") && !variableName.equals("Producer") 61 ? variableName.substring(0, variableName.length() - 8) 62 : variableName; 63 default: 64 throw new AssertionError(); 65 } 66 } 67 } 68