Search in sources :

Example 11 with Builder

use of com.squareup.javapoet.TypeSpec.Builder in project tiger by google.

the class NewInjectorGenerator method generateProvisionMethodIfNeeded.

private void generateProvisionMethodIfNeeded(final NewBindingKey key, TypeElement referencingClass) {
    ClassName packagedInjectorClassName = getInjectorFor(key, referencingClass);
    Builder injectorSpecBuilder = getInjectorTypeSpecBuilder(packagedInjectorClassName);
    if (!generatedBindingsForPackagedInjector.put(packagedInjectorClassName, key)) {
        return;
    }
    NewDependencyInfo dependencyInfo = Iterables.getFirst(dependencies.get(key), null);
    // System.out.println("generateProvisionMethodIfNeeded, key: " + key);
    // System.out.println("generateProvisionMethodIfNeeded, NewDependencyInfo: " +
    // dependencyInfo);
    // System.out.println("generateProvisionMethodIfNeeded, scope: " +
    // scopeCalculator.calculate(key));
    boolean scoped = explicitScopes.contains(key);
    String suffix = scoped ? UNSCOPED_SUFFIX : "";
    if (dependencyInfo != null) {
        if (dependencyInfo.isSet()) {
            // TODO(freeman): support binding for Set of Provider or Lazy.
            generateProvisionMethodForSet(key, referencingClass, suffix);
        } else {
            if (dependencyInfo.getProvisionMethodElement() == null) {
                generateProvisionMethodFromClass(key, referencingClass, suffix);
            } else {
                generateUniqueTypeProvisionMethodFromModule(key, suffix);
            }
        }
    } else if (Utils.hasBuiltinBinding(key)) {
        generateProvisionMethodForProviderOrLazy(key, referencingClass, suffix);
    } else if (Utils.isMap(key)) {
        generateProvisionMethodForMap(key, referencingClass, suffix);
    } else {
        NewDependencyInfo genericDependencyInfo = Utils.getDependencyInfoByGeneric(dependencies, key);
        if (genericDependencyInfo != null) {
            if (genericDependencyInfo.getProvisionMethodElement() == null) {
                generateProvisionMethodFromClass(key, referencingClass, suffix);
            } else {
                errors.add(String.format("Generic provision method not supported yet: %s -> %s", key, genericDependencyInfo));
            }
        } else {
            errors.add(String.format("Cannot resolve %s.", key));
            throw new RuntimeException();
        }
    }
    if (scoped) {
        generateField(injectorSpecBuilder, key);
        generateScopedProvisionMethod(injectorSpecBuilder, key);
    }
}
Also used : Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName)

Example 12 with Builder

use of com.squareup.javapoet.TypeSpec.Builder in project tiger by google.

the class NewInjectorGenerator method generateAll.

private void generateAll() {
    for (ComponentInfo component : orderedComponents) {
        Set<ClassName> injected = new HashSet<>();
        Set<TypeElement> allMembersInjectors = Sets.newHashSet(memberInjectors.get(component));
        while (!allMembersInjectors.isEmpty()) {
            TypeElement injector = Iterables.getFirst(allMembersInjectors, null);
            Preconditions.checkNotNull(injector, String.format("Empty allMembersInjector."));
            allMembersInjectors.remove(injector);
            for (TypeMirror parentInterface : injector.getInterfaces()) {
                allMembersInjectors.add((TypeElement) ((DeclaredType) parentInterface).asElement());
            }
            for (Element method : injector.getEnclosedElements()) {
                if (Utils.isInjectionMethod(method)) {
                    VariableElement var = Iterables.getOnlyElement(((ExecutableElement) method).getParameters());
                    if (var.asType().getKind().equals(TypeKind.TYPEVAR)) {
                        // TODO(freeman): support generic injection method.
                        continue;
                    }
                    TypeElement varTypeElement = (TypeElement) ((DeclaredType) var.asType()).asElement();
                    if (!injected.add(ClassName.get(varTypeElement))) {
                        continue;
                    }
                    generateInjectionMethod(varTypeElement, component.getScope());
                } else if (Utils.isProvisionMethodInInjector(method)) {
                    generateProvisionMethodIfNeeded(Utils.getKeyProvidedByMethod((ExecutableElement) method), injector);
                } else {
                    messager.printMessage(Kind.WARNING, String.format("Unknown element %s from injector %s.", method, injector));
                }
            }
        }
    }
    for (ComponentInfo component : orderedComponents) {
        if (componentTree.get(component) == null) {
            continue;
        }
        for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
            ClassName packagedInjectorClassName = entry.getKey();
            if (!component.equals(getComponentFromPackagedInjectorClassName(packagedInjectorClassName))) {
                continue;
            }
            generateInheritedProvisionMethods(packagedInjectorClassName);
        }
    }
    for (ComponentInfo component : orderedComponents) {
        if (componentTree.get(component) == null) {
            continue;
        }
        for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
            ClassName packagedInjectorClassName = entry.getKey();
            if (!component.equals(getComponentFromPackagedInjectorClassName(packagedInjectorClassName))) {
                continue;
            }
            generateInheritedInjectionMethods(packagedInjectorClassName);
        }
    }
    for (Map.Entry<ClassName, TypeSpec.Builder> entry : packagedInjectorBuilders.entrySet()) {
        String packageString = entry.getKey().packageName();
        TypeSpec.Builder builder = entry.getValue();
        JavaFile javaFile = JavaFile.builder(packageString, builder.build()).build();
        // messager.printMessage(Kind.NOTE, String.format("java file: %s", javaFile));
        try {
            javaFile.writeTo(processingEnv.getFiler());
        } catch (IOException e) {
            Throwables.propagate(e);
        }
    }
    generateTopLevelInjectors();
}
Also used : TypeElement(javax.lang.model.element.TypeElement) PackageElement(javax.lang.model.element.PackageElement) VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) ExecutableElement(javax.lang.model.element.ExecutableElement) Element(javax.lang.model.element.Element) Builder(com.squareup.javapoet.TypeSpec.Builder) VariableElement(javax.lang.model.element.VariableElement) IOException(java.io.IOException) TypeMirror(javax.lang.model.type.TypeMirror) Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) JavaFile(com.squareup.javapoet.JavaFile) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) DeclaredType(javax.lang.model.type.DeclaredType) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 13 with Builder

use of com.squareup.javapoet.TypeSpec.Builder in project tiger by google.

the class Tiger2InjectorGenerator method doSpecific.

@Override
protected void doSpecific() {
    // TODO: remove this, just and the contracts to trigger generating things when needed.
    // generateImplicitMethods();
    // Injection methods and non-injection methods.
    Set<String> miscMethodNames = new HashSet<>();
    DeclaredType eitherComponentType = (DeclaredType) eitherComponent.asType();
    utils.traverseAndDo(types, eitherComponentType, eitherComponent, p -> {
        Element element = p.second;
        messager.printMessage(Kind.NOTE, "method: " + 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) {
                messager.printMessage(Kind.WARNING, "duplicate injection method: " + method);
                return null;
            }
            TypeMirror typeMirror = Iterables.getOnlyElement(methodType.getParameterTypes());
            TypeElement cls = (TypeElement) ((DeclaredType) typeMirror).asElement();
            messager.printMessage(Kind.NOTE, TAG + ".generateTopLevelInjector-injection method : " + methodType);
            injectorBuilder.addMethod(MethodSpec.methodBuilder(method.getSimpleName().toString()).addModifiers(Modifier.PUBLIC).addParameter(ClassName.get(cls), "arg").addStatement("inject(arg)").build());
        } else if (utils.isComponentProvisionMethod(element)) {
            messager.printMessage(Kind.ERROR, "Injecting components is not supported: " + element);
        } else if (utils.isSubcomponentProvisionMethod(element)) {
            /**
             * TODO: handle this in {@link #generateProvisionMethodIfNeeded(BindingKey)}
             */
            generateGetSubcomponentMethod((ExecutableElement) element, injectorBuilder);
        } 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) {
            // messager.printMessage(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));
            // }
            // messager.printMessage(Kind.NOTE, "provision method added: " + methodBuilder.build());
            injectorBuilder.addMethod(methodBuilder.build());
        // } 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 (isIrrelevantMethodInInjector(element)) {
        // do nothing
        } else {
            messager.printMessage(Kind.WARNING, String.format("Element %s ignored from injector %s.", element, eitherComponentType));
        }
        return null;
    });
    // Builder.
    TypeElement explicitBuilder = utils.findBuilder(elements, eitherComponent);
    generateInjectorBuilder(explicitBuilder);
    // builder().
    ClassName builderClassName = ClassName.get(utils.getPackageString(eitherComponent), utils.getComponentImplementationSimpleNameFromInterface(eitherComponent), explicitBuilder != null ? explicitBuilder.getSimpleName().toString() : "Builder");
    MethodSpec.Builder builderMethodSpecBuilder = MethodSpec.methodBuilder("builder").addModifiers(Modifier.PUBLIC, Modifier.STATIC).returns(builderClassName);
    boolean isSubcomponent = utils.isSubcomponent(eitherComponent);
    if (isSubcomponent) {
        builderMethodSpecBuilder.addParameter(ClassName.get(parentEitherComponent.asType()), "v");
    }
    builderMethodSpecBuilder.addCode("return new $T($L);", builderClassName, isSubcomponent ? "v" : "");
    injectorBuilder.addMethod(builderMethodSpecBuilder.build());
// provision methods for (sub)component builders that can be provided by this core injector.
// TODO: handle implicit ones here, explicit ones have been handled in {@link
// #generateProvisionMethodForThoseFromTopLevel}.
// generateImplicitProvisionMethodForEitherComponentBuilder(injectorBuilder, builder);
}
Also used : ExecutableType(javax.lang.model.type.ExecutableType) MethodSpec(com.squareup.javapoet.MethodSpec) TypeElement(javax.lang.model.element.TypeElement) VariableElement(javax.lang.model.element.VariableElement) 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) TypeMirror(javax.lang.model.type.TypeMirror) ClassName(com.squareup.javapoet.ClassName) HashSet(java.util.HashSet) DeclaredType(javax.lang.model.type.DeclaredType)

Example 14 with Builder

use of com.squareup.javapoet.TypeSpec.Builder in project vue-gwt by Axellience.

the class ComponentJsTypeGenerator method generate.

public void generate(TypeElement component, ComponentInjectedDependenciesBuilder dependenciesBuilder) {
    // Template resource abstract class
    ClassName componentWithSuffixClassName = componentJsTypeName(component);
    Builder componentJsTypeBuilder = getComponentJsTypeBuilder(component, componentWithSuffixClassName);
    // Initialize Options getter builder
    MethodSpec.Builder optionsBuilder = getOptionsMethodBuilder(component);
    Set<ExecutableElement> hookMethodsFromInterfaces = getHookMethodsFromInterfaces(component);
    processData(component, optionsBuilder);
    processProps(component, optionsBuilder);
    processComputed(component, optionsBuilder, componentJsTypeBuilder);
    processWatchers(component, optionsBuilder, componentJsTypeBuilder);
    processPropValidators(component, optionsBuilder, componentJsTypeBuilder);
    processPropDefaultValues(component, optionsBuilder, componentJsTypeBuilder);
    processHooks(component, optionsBuilder, hookMethodsFromInterfaces);
    processTemplateMethods(component, optionsBuilder, componentJsTypeBuilder, hookMethodsFromInterfaces);
    processInvalidEmitMethods(component);
    processRenderFunction(component, optionsBuilder, componentJsTypeBuilder);
    createCreatedHook(component, optionsBuilder, componentJsTypeBuilder, dependenciesBuilder);
    // Process the HTML template if there is one
    if (hasTemplate(processingEnv, component)) {
        componentTemplateProcessor.processComponentTemplate(component, componentJsTypeBuilder);
        optionsBuilder.addStatement("options.initRenderFunctions(getRenderFunction(), getStaticRenderFunctions())");
    }
    // Finish building Options getter
    optionsBuilder.addStatement("return options");
    componentJsTypeBuilder.addMethod(optionsBuilder.build());
    // And generate our Java Class
    GeneratorsUtil.toJavaFile(filer, componentJsTypeBuilder, componentWithSuffixClassName, component);
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) VNodeBuilder(com.axellience.vuegwt.core.client.vnode.builder.VNodeBuilder) Builder(com.squareup.javapoet.TypeSpec.Builder) ExecutableElement(javax.lang.model.element.ExecutableElement) ClassName(com.squareup.javapoet.ClassName)

Example 15 with Builder

use of com.squareup.javapoet.TypeSpec.Builder in project glide by bumptech.

the class AppModuleGenerator method generate.

TypeSpec generate(TypeElement appGlideModule, Set<String> libraryGlideModuleClassNames) {
    ClassName appGlideModuleClassName = ClassName.get(appGlideModule);
    List<String> excludedGlideModuleClassNames = getExcludedGlideModuleClassNames(appGlideModule);
    List<String> orderedLibraryGlideModuleClassNames = new ArrayList<>(libraryGlideModuleClassNames);
    Collections.sort(orderedLibraryGlideModuleClassNames);
    MethodSpec constructor = generateConstructor(appGlideModuleClassName, orderedLibraryGlideModuleClassNames, excludedGlideModuleClassNames);
    MethodSpec registerComponents = generateRegisterComponents(orderedLibraryGlideModuleClassNames, excludedGlideModuleClassNames);
    MethodSpec getExcludedModuleClasses = generateGetExcludedModuleClasses(excludedGlideModuleClassNames);
    MethodSpec applyOptions = MethodSpec.methodBuilder("applyOptions").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addParameter(ParameterSpec.builder(ClassName.get("android.content", "Context"), "context").addAnnotation(nonNull()).build()).addParameter(ParameterSpec.builder(ClassName.get("com.bumptech.glide", "GlideBuilder"), "builder").addAnnotation(nonNull()).build()).addStatement("appGlideModule.applyOptions(context, builder)", appGlideModule).build();
    MethodSpec isManifestParsingEnabled = MethodSpec.methodBuilder("isManifestParsingEnabled").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).returns(boolean.class).addStatement("return appGlideModule.isManifestParsingEnabled()", appGlideModule).build();
    Builder builder = TypeSpec.classBuilder(GENERATED_APP_MODULE_IMPL_SIMPLE_NAME).addModifiers(Modifier.FINAL).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "deprecation").build()).superclass(ClassName.get(GENERATED_ROOT_MODULE_PACKAGE_NAME, GENERATED_ROOT_MODULE_SIMPLE_NAME)).addField(appGlideModuleClassName, "appGlideModule", Modifier.PRIVATE, Modifier.FINAL).addMethod(constructor).addMethod(applyOptions).addMethod(registerComponents).addMethod(isManifestParsingEnabled).addMethod(getExcludedModuleClasses);
    ClassName generatedRequestManagerFactoryClassName = ClassName.get(RequestManagerFactoryGenerator.GENERATED_REQUEST_MANAGER_FACTORY_PACKAGE_NAME, RequestManagerFactoryGenerator.GENERATED_REQUEST_MANAGER_FACTORY_SIMPLE_NAME);
    builder.addMethod(MethodSpec.methodBuilder("getRequestManagerFactory").addAnnotation(Override.class).addAnnotation(nonNull()).returns(generatedRequestManagerFactoryClassName).addStatement("return new $T()", generatedRequestManagerFactoryClassName).build());
    return builder.build();
}
Also used : MethodSpec(com.squareup.javapoet.MethodSpec) Builder(com.squareup.javapoet.TypeSpec.Builder) ClassName(com.squareup.javapoet.ClassName) ArrayList(java.util.ArrayList)

Aggregations

Builder (com.squareup.javapoet.TypeSpec.Builder)42 ClassName (com.squareup.javapoet.ClassName)28 MethodSpec (com.squareup.javapoet.MethodSpec)25 TypeSpec (com.squareup.javapoet.TypeSpec)18 TypeElement (javax.lang.model.element.TypeElement)16 TypeName (com.squareup.javapoet.TypeName)14 ExecutableElement (javax.lang.model.element.ExecutableElement)13 ParameterizedTypeName (com.squareup.javapoet.ParameterizedTypeName)12 IOException (java.io.IOException)7 PackageElement (javax.lang.model.element.PackageElement)7 VariableElement (javax.lang.model.element.VariableElement)7 TypeMirror (javax.lang.model.type.TypeMirror)7 JavaFile (com.squareup.javapoet.JavaFile)6 ArrayList (java.util.ArrayList)6 DeclaredType (javax.lang.model.type.DeclaredType)6 Element (javax.lang.model.element.Element)5 HashSet (java.util.HashSet)4 BindTypeBuilder (com.abubusoft.kripton.processor.bind.BindTypeBuilder)3 PrefsProperty (com.abubusoft.kripton.processor.sharedprefs.model.PrefsProperty)3 HashMap (java.util.HashMap)3