Search in sources :

Example 26 with ClassName

use of com.squareup.javapoet.ClassName in project tiger by google.

the class NewInjectorGenerator method generateMapTypeProvisionMethodForPackage.

// If dependencyInfo is not null, then it is a contributor to map biding.
private void generateMapTypeProvisionMethodForPackage(final NewBindingKey key, Set<NewDependencyInfo> dependencyInfos, String suffix) {
    Preconditions.checkArgument(!dependencyInfos.isEmpty(), String.format("Empty dependencyInfo for key: %s", key));
    NewDependencyInfo dependencyInfo = Iterables.getFirst(dependencyInfos, null);
    TypeName returnType = key.getTypeName();
    ClassName injectorClassName = getPackagedInjectorForNewDependencyInfo(key, dependencyInfo);
    TypeSpec.Builder componentSpecBuilder = getInjectorTypeSpecBuilder(injectorClassName);
    MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder(getProvisionMethodName(key) + suffix);
    methodSpecBuilder.addModifiers(Modifier.PUBLIC).returns(returnType);
    methodSpecBuilder.addStatement("$T result = new $T<>()", returnType, HashMap.class);
    TypeName mapKeyType = ((ParameterizedTypeName) returnType).typeArguments.get(0);
    TypeName mapValueType = ((ParameterizedTypeName) returnType).typeArguments.get(1);
    NewBindingKey mapValueKey = NewBindingKey.get(mapValueType);
    methodSpecBuilder.addStatement("$T mapKey", mapKeyType);
    methodSpecBuilder.addStatement("$T mapValue", mapValueType);
    for (NewDependencyInfo di : dependencyInfos) {
        AnnotationMirror mapKeyMirror = Utils.getAnnotationMirrorWithMetaAnnotation(di.getProvisionMethodElement(), MapKey.class);
        AnnotationValue unwrapValueAnnotationValue = Utils.getAnnotationValue(mapKeyMirror, "unwrapValue");
        if (unwrapValueAnnotationValue != null && !((boolean) unwrapValueAnnotationValue.getValue())) {
            errors.add(String.format("unwrapValue = false not supported yet. Consider using set binding."));
            return;
        }
        Object mapKey = Utils.getAnnotationValue(mapKeyMirror, "value").getValue();
        methodSpecBuilder.addStatement("mapKey = ($T) $S", mapKeyType, mapKey);
        if (Utils.isMapWithBuiltinValueType(key)) {
            TypeElement scope = scopeCalculator.calculate(key);
            methodSpecBuilder.addStatement("mapValue = $L", createAnonymousBuiltinTypeForMultiBinding(injectorClassName, mapValueKey, scope, di));
        } else {
            addNewStatementToMethodSpec(mapValueKey, di, injectorClassName, methodSpecBuilder, "mapValue");
        }
        methodSpecBuilder.addStatement("result.put(mapKey, mapValue)");
    }
    methodSpecBuilder.addStatement("return result");
    componentSpecBuilder.addMethod(methodSpecBuilder.build());
// messager.printMessage(Kind.NOTE, String.format(
// "generateSetTypeProvisionMethodFromModule: \n key: %s, \n injector: %s, \n method: %s.",
// key, injectorClassName, methodSpecBuilder.build()));
}
Also used : AnnotationMirror(javax.lang.model.element.AnnotationMirror) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) AnnotationValue(javax.lang.model.element.AnnotationValue) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 27 with ClassName

use of com.squareup.javapoet.ClassName in project dagger by square.

the class ModuleAdapterProcessor method bindingClassName.

private ClassName bindingClassName(ClassName adapterName, ExecutableElement providerMethod, Map<ExecutableElement, ClassName> methodToClassName, Map<String, AtomicInteger> methodNameToNextId) {
    ClassName className = methodToClassName.get(providerMethod);
    if (className != null)
        return className;
    String methodName = providerMethod.getSimpleName().toString();
    String suffix = "";
    AtomicInteger id = methodNameToNextId.get(methodName);
    if (id == null) {
        methodNameToNextId.put(methodName, new AtomicInteger(2));
    } else {
        suffix = id.toString();
        id.incrementAndGet();
    }
    String uppercaseMethodName = Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1);
    className = adapterName.nestedClass(uppercaseMethodName + "ProvidesAdapter" + suffix);
    methodToClassName.put(providerMethod, className);
    return className;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ClassName(com.squareup.javapoet.ClassName) Util.typeToString(dagger.internal.codegen.Util.typeToString) Util.elementToString(dagger.internal.codegen.Util.elementToString)

Example 28 with ClassName

use of com.squareup.javapoet.ClassName in project wire by square.

the class JavaGenerator method get.

public static JavaGenerator get(Schema schema) {
    Map<ProtoType, ClassName> nameToJavaName = new LinkedHashMap<>();
    nameToJavaName.putAll(BUILT_IN_TYPES_MAP);
    for (ProtoFile protoFile : schema.protoFiles()) {
        String javaPackage = javaPackage(protoFile);
        putAll(nameToJavaName, javaPackage, null, protoFile.types());
        for (Service service : protoFile.services()) {
            ClassName className = ClassName.get(javaPackage, service.type().simpleName());
            nameToJavaName.put(service.type(), className);
        }
    }
    return new JavaGenerator(schema, nameToJavaName, new Profile(), false, false);
}
Also used : ProtoType(com.squareup.wire.schema.ProtoType) ClassName(com.squareup.javapoet.ClassName) ProtoFile(com.squareup.wire.schema.ProtoFile) Service(com.squareup.wire.schema.Service) ByteString(okio.ByteString) LinkedHashMap(java.util.LinkedHashMap)

Example 29 with ClassName

use of com.squareup.javapoet.ClassName in project wire by square.

the class JavaGenerator method generateEnum.

/** @deprecated Use {@link #generateType(Type)} */
@Deprecated
public TypeSpec generateEnum(EnumType type) {
    ClassName javaType = (ClassName) typeName(type.type());
    TypeSpec.Builder builder = TypeSpec.enumBuilder(javaType.simpleName()).addModifiers(PUBLIC).addSuperinterface(WireEnum.class);
    if (!type.documentation().isEmpty()) {
        builder.addJavadoc("$L\n", sanitizeJavadoc(type.documentation()));
    }
    // Output Private tag field
    builder.addField(TypeName.INT, "value", PRIVATE, FINAL);
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
    constructorBuilder.addStatement("this.value = value");
    constructorBuilder.addParameter(TypeName.INT, "value");
    // Enum constant options, each of which requires a constructor parameter and a field.
    Set<ProtoMember> allOptionFieldsBuilder = new LinkedHashSet<>();
    for (EnumConstant constant : type.constants()) {
        for (ProtoMember protoMember : constant.options().map().keySet()) {
            Field optionField = schema.getField(protoMember);
            if (allOptionFieldsBuilder.add(protoMember)) {
                TypeName optionJavaType = typeName(optionField.type());
                builder.addField(optionJavaType, optionField.name(), PUBLIC, FINAL);
                constructorBuilder.addParameter(optionJavaType, optionField.name());
                constructorBuilder.addStatement("this.$L = $L", optionField.name(), optionField.name());
            }
        }
    }
    ImmutableList<ProtoMember> allOptionMembers = ImmutableList.copyOf(allOptionFieldsBuilder);
    String enumArgsFormat = "$L" + Strings.repeat(", $L", allOptionMembers.size());
    builder.addMethod(constructorBuilder.build());
    MethodSpec.Builder fromValueBuilder = MethodSpec.methodBuilder("fromValue").addJavadoc("Return the constant for {@code value} or null.\n").addModifiers(PUBLIC, STATIC).returns(javaType).addParameter(int.class, "value").beginControlFlow("switch (value)");
    Set<Integer> seenTags = new LinkedHashSet<>();
    for (EnumConstant constant : type.constants()) {
        Object[] enumArgs = new Object[allOptionMembers.size() + 1];
        enumArgs[0] = constant.tag();
        for (int i = 0; i < allOptionMembers.size(); i++) {
            ProtoMember protoMember = allOptionMembers.get(i);
            Field field = schema.getField(protoMember);
            Object value = constant.options().map().get(protoMember);
            enumArgs[i + 1] = value != null ? fieldInitializer(field.type(), value) : null;
        }
        TypeSpec.Builder constantBuilder = TypeSpec.anonymousClassBuilder(enumArgsFormat, enumArgs);
        if (!constant.documentation().isEmpty()) {
            constantBuilder.addJavadoc("$L\n", sanitizeJavadoc(constant.documentation()));
        }
        if ("true".equals(constant.options().get(ENUM_DEPRECATED))) {
            constantBuilder.addAnnotation(Deprecated.class);
        }
        builder.addEnumConstant(constant.name(), constantBuilder.build());
        // Ensure constant case tags are unique, which might not be the case if allow_alias is true.
        if (seenTags.add(constant.tag())) {
            fromValueBuilder.addStatement("case $L: return $L", constant.tag(), constant.name());
        }
    }
    builder.addMethod(fromValueBuilder.addStatement("default: return null").endControlFlow().build());
    // ADAPTER
    FieldSpec.Builder adapterBuilder = FieldSpec.builder(adapterOf(javaType), "ADAPTER").addModifiers(PUBLIC, STATIC, FINAL);
    ClassName adapterJavaType = javaType.nestedClass("ProtoAdapter_" + javaType.simpleName());
    if (!emitCompact) {
        adapterBuilder.initializer("new $T()", adapterJavaType);
    } else {
        adapterBuilder.initializer("$T.newEnumAdapter($T.class)", ProtoAdapter.class, javaType);
    }
    builder.addField(adapterBuilder.build());
    // Enum type options.
    FieldSpec options = optionsField(ENUM_OPTIONS, "ENUM_OPTIONS", type.options());
    if (options != null) {
        builder.addField(options);
    }
    // Public Getter
    builder.addMethod(MethodSpec.methodBuilder("getValue").addAnnotation(Override.class).addModifiers(PUBLIC).returns(TypeName.INT).addStatement("return value").build());
    if (!emitCompact) {
        // Adds the ProtoAdapter implementation at the bottom.
        builder.addType(enumAdapter(javaType, adapterJavaType));
    }
    return builder.build();
}
Also used : LinkedHashSet(java.util.LinkedHashSet) TypeName(com.squareup.javapoet.TypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) MethodSpec(com.squareup.javapoet.MethodSpec) ByteString(okio.ByteString) FieldSpec(com.squareup.javapoet.FieldSpec) WireField(com.squareup.wire.WireField) Field(com.squareup.wire.schema.Field) ClassName(com.squareup.javapoet.ClassName) ProtoMember(com.squareup.wire.schema.ProtoMember) EnumConstant(com.squareup.wire.schema.EnumConstant) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 30 with ClassName

use of com.squareup.javapoet.ClassName in project wire by square.

the class JavaGenerator method putAll.

private static void putAll(Map<ProtoType, ClassName> wireToJava, String javaPackage, ClassName enclosingClassName, List<Type> types) {
    for (Type type : types) {
        ClassName className = enclosingClassName != null ? enclosingClassName.nestedClass(type.type().simpleName()) : ClassName.get(javaPackage, type.type().simpleName());
        wireToJava.put(type.type(), className);
        putAll(wireToJava, javaPackage, className, type.nestedTypes());
    }
}
Also used : Type(com.squareup.wire.schema.Type) ProtoType(com.squareup.wire.schema.ProtoType) MessageType(com.squareup.wire.schema.MessageType) EnclosingType(com.squareup.wire.schema.EnclosingType) EnumType(com.squareup.wire.schema.EnumType) ClassName(com.squareup.javapoet.ClassName)

Aggregations

ClassName (com.squareup.javapoet.ClassName)99 TypeSpec (com.squareup.javapoet.TypeSpec)60 MethodSpec (com.squareup.javapoet.MethodSpec)41 TypeElement (javax.lang.model.element.TypeElement)37 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)35 TypeName (com.squareup.javapoet.TypeName)30 Element (javax.lang.model.element.Element)19 TypeMirror (javax.lang.model.type.TypeMirror)17 Builder (com.squareup.javapoet.TypeSpec.Builder)16 FieldSpec (com.squareup.javapoet.FieldSpec)15 ArrayList (java.util.ArrayList)15 CodeBlock (com.squareup.javapoet.CodeBlock)11 ExecutableElement (javax.lang.model.element.ExecutableElement)11 NotNull (org.jetbrains.annotations.NotNull)10 VariableElement (javax.lang.model.element.VariableElement)9 JavaFile (com.squareup.javapoet.JavaFile)8 Map (java.util.Map)8 WildcardTypeName (com.squareup.javapoet.WildcardTypeName)7 IOException (java.io.IOException)7 HashMap (java.util.HashMap)7