Search in sources :

Example 66 with ExecutableType

use of javax.lang.model.type.ExecutableType in project j2objc by google.

the class CastResolver method getDeclaredReturnType.

private TypeMirror getDeclaredReturnType(ExecutableElement method, TypeMirror receiverType) {
    // Check if the method is declared on the receiver type.
    if (ElementUtil.getDeclaringClass(method).equals(TypeUtil.asTypeElement(receiverType))) {
        return method.getReturnType();
    }
    // Search all inherited types for matching method declarations. Choose the
    // most narrow return type, because AbstractMethodRewriter will ensure that
    // a declaration exists with the most narrow return type.
    ExecutableType methodType = (ExecutableType) method.asType();
    String selector = nameTable.getMethodSelector(method);
    for (TypeMirror typeBound : typeUtil.getUpperBounds(receiverType)) {
        if (TypeUtil.isDeclaredType(typeBound)) {
            // Normalize any parameterized types before searching for method declarations.
            typeBound = ((DeclaredType) typeBound).asElement().asType();
        }
        TypeMirror returnType = null;
        for (DeclaredType inheritedType : typeUtil.getObjcOrderedInheritedTypes(typeBound)) {
            TypeElement inheritedElem = (TypeElement) inheritedType.asElement();
            for (ExecutableElement currentMethod : ElementUtil.getMethods(inheritedElem)) {
                ExecutableType currentMethodType = typeUtil.asMemberOf(inheritedType, currentMethod);
                if (typeUtil.isSubsignature(methodType, currentMethodType) && nameTable.getMethodSelector(currentMethod).equals(selector)) {
                    TypeMirror newReturnType = typeUtil.erasure(currentMethodType.getReturnType());
                    if (returnType == null || typeUtil.isSubtype(newReturnType, returnType)) {
                        returnType = newReturnType;
                    }
                }
            }
        }
        if (returnType != null) {
            return returnType;
        }
    }
    // Last resort. Might be a GeneratedExecutableElement.
    return method.getReturnType();
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) GeneratedExecutableElement(com.google.devtools.j2objc.types.GeneratedExecutableElement) ExecutableElement(javax.lang.model.element.ExecutableElement) DeclaredType(javax.lang.model.type.DeclaredType)

Example 67 with ExecutableType

use of javax.lang.model.type.ExecutableType in project arez by arez.

the class ComponentDescriptor method buildRepositoryCreate.

@Nonnull
private MethodSpec buildRepositoryCreate(@Nonnull final ExecutableElement constructor, @Nonnull final ExecutableType methodType, @Nonnull final ClassName arezType) {
    final String suffix = constructor.getParameters().stream().map(p -> p.getSimpleName().toString()).collect(Collectors.joining("_"));
    final String actionName = "create" + (suffix.isEmpty() ? "" : "_" + suffix);
    final AnnotationSpec annotationSpec = AnnotationSpec.builder(ClassName.bestGuess(Constants.ACTION_ANNOTATION_CLASSNAME)).addMember("name", "$S", actionName).build();
    final MethodSpec.Builder builder = MethodSpec.methodBuilder("create").addAnnotation(annotationSpec).addAnnotation(GeneratorUtil.NONNULL_CLASSNAME).returns(TypeName.get(asDeclaredType()));
    ProcessorUtil.copyAccessModifiers(getElement(), builder);
    ProcessorUtil.copyExceptions(methodType, builder);
    ProcessorUtil.copyTypeParameters(methodType, builder);
    final StringBuilder newCall = new StringBuilder();
    newCall.append("final $T entity = new $T(");
    final ArrayList<Object> parameters = new ArrayList<>();
    parameters.add(arezType);
    parameters.add(arezType);
    boolean firstParam = true;
    for (final VariableElement element : constructor.getParameters()) {
        final ParameterSpec.Builder param = ParameterSpec.builder(TypeName.get(element.asType()), element.getSimpleName().toString(), Modifier.FINAL);
        ProcessorUtil.copyDocumentedAnnotations(element, param);
        builder.addParameter(param.build());
        parameters.add(element.getSimpleName().toString());
        if (!firstParam) {
            newCall.append(",");
        }
        firstParam = false;
        newCall.append("$N");
    }
    newCall.append(")");
    builder.addStatement(newCall.toString(), parameters.toArray());
    builder.addStatement("registerEntity( entity )");
    builder.addStatement("return entity");
    return builder.build();
}
Also used : Arrays(java.util.Arrays) PackageElement(javax.lang.model.element.PackageElement) Modifier(javax.lang.model.element.Modifier) FieldSpec(com.squareup.javapoet.FieldSpec) VariableElement(javax.lang.model.element.VariableElement) ClassName(com.squareup.javapoet.ClassName) HashMap(java.util.HashMap) TypeElement(javax.lang.model.element.TypeElement) Elements(javax.lang.model.util.Elements) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Generated(javax.annotation.Generated) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) DeclaredType(javax.lang.model.type.DeclaredType) NestingKind(javax.lang.model.element.NestingKind) Nonnull(javax.annotation.Nonnull) CodeBlock(com.squareup.javapoet.CodeBlock) Nullable(javax.annotation.Nullable) ParameterSpec(com.squareup.javapoet.ParameterSpec) ElementKind(javax.lang.model.element.ElementKind) ExecutableType(javax.lang.model.type.ExecutableType) MethodSpec(com.squareup.javapoet.MethodSpec) Collection(java.util.Collection) ExecutableElement(javax.lang.model.element.ExecutableElement) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) Element(javax.lang.model.element.Element) TypeSpec(com.squareup.javapoet.TypeSpec) Types(javax.lang.model.util.Types) Collectors(java.util.stream.Collectors) AnnotationMirror(javax.lang.model.element.AnnotationMirror) TypeKind(javax.lang.model.type.TypeKind) Objects(java.util.Objects) SourceVersion(javax.lang.model.SourceVersion) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) Stream(java.util.stream.Stream) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) TypeName(com.squareup.javapoet.TypeName) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) MethodSpec(com.squareup.javapoet.MethodSpec) ParameterSpec(com.squareup.javapoet.ParameterSpec) ArrayList(java.util.ArrayList) VariableElement(javax.lang.model.element.VariableElement) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) Nonnull(javax.annotation.Nonnull)

Example 68 with ExecutableType

use of javax.lang.model.type.ExecutableType in project ucsFramework by cjsoftware-lib.

the class ProxyQueueBuilder method buildCacheClass.

private TypeSpec buildCacheClass(TypeElement proxiedInterface, ExecutableElement interfaceMethod, int methodId) {
    Types typeUtils = getProcessorModel().getTypeUtils();
    DeclaredType declaredType = (DeclaredType) proxiedInterface.asType();
    ExecutableType executableType = (ExecutableType) typeUtils.asMemberOf(declaredType, interfaceMethod);
    List<? extends TypeMirror> resolvedParameterTypes = executableType.getParameterTypes();
    TypeSpec.Builder methodCallCacheClass = TypeSpec.classBuilder(String.format(GENERATED_CALL_CACHE_CLASS_NAME_TEMPLATE, interfaceMethod.getSimpleName().toString())).addModifiers(Modifier.PRIVATE, Modifier.STATIC).addSuperinterface(ParameterizedTypeName.get(ClassName.get(CachedMethodCall.class), ClassName.get(proxiedInterface)));
    MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder();
    StringBuilder params = new StringBuilder();
    List<? extends VariableElement> parameters = interfaceMethod.getParameters();
    for (int paramIndex = 0; paramIndex < parameters.size(); paramIndex++) {
        VariableElement variableElement = parameters.get(paramIndex);
        TypeName resolvedTypeName = TypeName.get(resolvedParameterTypes.get(paramIndex));
        String paramName = variableElement.getSimpleName().toString();
        if (params.length() > 0) {
            params.append(", ");
        }
        params.append("this.");
        params.append(variableElement.getSimpleName());
        methodCallCacheClass.addField(resolvedTypeName, paramName, Modifier.PRIVATE, Modifier.FINAL);
        constructorBuilder.addParameter(resolvedTypeName, paramName);
        constructorBuilder.addStatement("this.$N = $N", paramName, paramName);
    }
    methodCallCacheClass.addMethod(constructorBuilder.build());
    MethodSpec.Builder methodCallImplementation = MethodSpec.methodBuilder("execute").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ClassName.get(proxiedInterface), "implementation").build()).addCode(CodeBlock.builder().addStatement("implementation.$N($L)", interfaceMethod.getSimpleName(), params.toString()).build());
    methodCallCacheClass.addMethod(methodCallImplementation.build());
    methodCallCacheClass.addMethod(MethodSpec.methodBuilder("methodId").addAnnotation(Override.class).addModifiers(Modifier.PUBLIC).returns(TypeName.INT).addCode("return $L;", methodId).addCode("\n").build());
    return methodCallCacheClass.build();
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) Types(javax.lang.model.util.Types) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) VariableElement(javax.lang.model.element.VariableElement) DeclaredType(javax.lang.model.type.DeclaredType) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 69 with ExecutableType

use of javax.lang.model.type.ExecutableType in project tiger by google.

the class DependencyCollector method collectFromCtorInjectedClass.

/**
 * Returns dependency info from ctor injected class, null if such class not found.
 */
@Nullable
public Collection<DependencyInfo> collectFromCtorInjectedClass(TypeElement classElement, DeclaredType type) {
    // logger.n(TAG + ".collectFromCtorInjectedClass: classElement: " + classElement);
    Collection<DependencyInfo> result = new HashSet<>();
    Preconditions.checkArgument(!utils.hasAnonymousParentClass(classElement), String.format("class %s should not have anonymous ancestor.", classElement));
    ExecutableElement ctor = utils.findInjectedCtor(classElement);
    // logger.n(TAG + ".collectFromCtorInjectedClass ctor: " + ctor);
    if (ctor == null) {
        return null;
    }
    TypeMirror typeMirror = types.asMemberOf(type, ctor);
    // logger.n(TAG + ".collectFromCtorInjectedClass typeMirror: " + typeMirror);
    Set<BindingKey> dependencies = getDependenciesFrom(ctor, (ExecutableType) typeMirror);
    for (Element element : classElement.getEnclosedElements()) {
        if (element.getKind().equals(ElementKind.FIELD) && utils.isInjected(element)) {
            dependencies.add(utils.getKeyForField(type, element));
        }
        if (element.getKind().equals(ElementKind.METHOD) && utils.isInjected(element)) {
            dependencies.addAll(getDependenciesFrom((ExecutableElement) element, (ExecutableType) types.asMemberOf(type, element)));
        }
    }
    DependencyInfo dependenceInfo = new DependencyInfo(DependencySourceType.CTOR_INJECTED_CLASS, BindingKey.get(type), dependencies, classElement, UNIQUE);
    result.add(dependenceInfo);
    return result;
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) TypeMirror(javax.lang.model.type.TypeMirror) ExecutableElement(javax.lang.model.element.ExecutableElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) HashSet(java.util.HashSet) Nullable(javax.annotation.Nullable)

Example 70 with ExecutableType

use of javax.lang.model.type.ExecutableType in project tiger by google.

the class HubInjectorGenerator4 method generateProvisionAndInjectionMethods.

private void generateProvisionAndInjectionMethods() {
    // Injection methods and non-injection methods.
    Set<String> miscMethodNames = new HashSet<>();
    DeclaredType eitherComponentType = (DeclaredType) eitherComponent.asType();
    final int[] count = { 0 };
    utils.generateDebugInfoMethod(injectorBuilder, "generateProvisionAndInjectionMethods");
    utils.traverseAndDo(types, eitherComponentType, eitherComponent, p -> {
        Element element = p.second;
        // logger.n("" + element);
        if (!element.getKind().equals(ElementKind.METHOD)) {
            return null;
        }
        ExecutableElement method = (ExecutableElement) element;
        ExecutableType methodType = (ExecutableType) processingEnv.getTypeUtils().asMemberOf(eitherComponentType, method);
        // Injection methods.
        if (utils.isInjectionMethod(element)) {
            // TODO: add duplicate check for provision method also.
            if (injectionMethodsDone.add(Pair.of(method.getSimpleName().toString(), TypeName.get(Iterables.getOnlyElement(methodType.getParameterTypes())))) == false) {
                // logger.w("injection method: " + method);
                return null;
            }
            TypeMirror typeMirror = Iterables.getOnlyElement(methodType.getParameterTypes());
            TypeElement cls = (TypeElement) ((DeclaredType) typeMirror).asElement();
            // logger.n(methodType.toString());
            injectorBuilder.addMethod(MethodSpec.methodBuilder(method.getSimpleName().toString()).addModifiers(Modifier.PUBLIC).addParameter(ClassName.get(cls), "arg").addStatement("inject(arg)").build());
            count[0]++;
        } else if (utils.isComponentProvisionMethod(element)) {
            logger.l(Kind.ERROR, "Injecting components is not supported: " + element);
        } else if (utils.isSubcomponentProvisionMethod(element)) {
            /**
             * TODO: handle this in {@link #generateProvisionMethodIfNeeded(BindingKey)}
             */
            generateGetSubcomponentMethod((ExecutableElement) element, injectorBuilder);
            count[0]++;
        } else if (utils.isProvisionMethodInInjector(element)) {
            if (!miscMethodNames.add(method.getSimpleName().toString())) {
                return null;
            }
            MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(method.getSimpleName().toString()).addModifiers(Modifier.PUBLIC).returns(TypeName.get(method.getReturnType()));
            BindingKey providedKey = utils.getKeyProvidedByMethod(method);
            // ClassName packagedInjectorClassName = null;
            // for (ClassName className : keyToPackagedInjectorMap.get(providedKey)) {
            // if (isInjectorOfScope(className, coreInjectorInfo.getScope())) {
            // packagedInjectorClassName = className;
            // break;
            // }
            // }
            // if (packagedInjectorClassName == null) {
            // logger.l(Kind.WARNING,
            // String.format(
            // "PackagedInjector or multiBindingInjector not found for key: %s "
            // + "from provisionMethod: %s. Probably it is not used.",
            // providedKey, method));
            // // Create a dumb method
            // String statement = "return ";
            // TypeKind typeKind = method.getReturnType().getKind();
            // if (typeKind.equals(TypeKind.BOOLEAN)) {
            // statement += "false";
            // } else if (typeKind.equals(TypeKind.CHAR)) {
            // statement += "\'0\'";
            // } else if (typeKind.isPrimitive()) {
            // statement += "0";
            // } else {
            // statement += "null";
            // }
            // methodBuilder.addStatement(statement);
            // } else {
            String statement = "return $L()";
            methodBuilder.addStatement(statement, Utils.getProvisionMethodName(dependencies, providedKey));
            // }
            // logger.n("method added: " + methodBuilder.build());
            injectorBuilder.addMethod(methodBuilder.build());
            count[0]++;
        // } else if (utils.isEitherComponentProvisionMethod(element)) {
        // // TODO: support get component method.
        // if(utils.isComponentProvisionMethod(element)) {
        // throw new RuntimeException("component provision method is not suported yet.");
        // }
        // generateGetSubcomponentMethod((ExecutableElement) element, injectorBuilder);
        // } else if (utils.isEitherComponentBuilderProvisionMethod(element)) {
        // /**
        // * TODO: handle it in the way consistent with other {@link DependencySourceType} in
        // * {@link #generateProvisionMethodIfNeeded(BindingKey, TypeElement)}
        // */
        // generateExplicitProvisionMethodForEitherComponentBuilder(
        // (ExecutableElement) element, injectorBuilder);
        } else if (utils.isIrrelevantMethodInInjector(element)) {
        // do nothing
        } else {
            logger.l(Kind.WARNING, "Element %s ignored from injector %s.", element, eitherComponentType);
        }
        return null;
    });
    logger.w("count: %d", count[0]);
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) TypeMirror(javax.lang.model.type.TypeMirror) TypeElement(javax.lang.model.element.TypeElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) ExecutableElement(javax.lang.model.element.ExecutableElement) Builder(com.squareup.javapoet.TypeSpec.Builder) HashSet(java.util.HashSet) DeclaredType(javax.lang.model.type.DeclaredType)

Aggregations

ExecutableType (javax.lang.model.type.ExecutableType)83 ExecutableElement (javax.lang.model.element.ExecutableElement)64 DeclaredType (javax.lang.model.type.DeclaredType)47 TypeMirror (javax.lang.model.type.TypeMirror)45 TypeElement (javax.lang.model.element.TypeElement)44 Element (javax.lang.model.element.Element)33 VariableElement (javax.lang.model.element.VariableElement)33 Nonnull (javax.annotation.Nonnull)22 ArrayList (java.util.ArrayList)18 MethodSpec (com.squareup.javapoet.MethodSpec)15 HashMap (java.util.HashMap)15 Map (java.util.Map)15 AnnotationMirror (javax.lang.model.element.AnnotationMirror)15 TypeSpec (com.squareup.javapoet.TypeSpec)14 HashSet (java.util.HashSet)14 TypeKind (javax.lang.model.type.TypeKind)14 IOException (java.io.IOException)13 Nullable (javax.annotation.Nullable)13 PackageElement (javax.lang.model.element.PackageElement)13 List (java.util.List)12