private TypeSpec buildModule(ModuleSpec spec) { CodeBlock.Builder blockBuilder = CodeBlock.builder().add("return new $T(", spec.getPresenterTypeName()); int i = 0; for (ParameterSpec parameterSpec : spec.getPresenterArgs()) { blockBuilder.add(parameterSpec.name); if (i++ < spec.getPresenterArgs().size() - 1) { blockBuilder.add(", "); } } blockBuilder.add(");\n"); MethodSpec.Builder methodSpecBuilder = MethodSpec.methodBuilder("providesPresenter") .addModifiers(Modifier.PUBLIC) .returns(spec.getPresenterTypeName()) .addAnnotation(Provides.class) .addParameters(spec.getProvideParameters()) .addCode(blockBuilder.build()); if (spec.getScopeAnnotationSpec() != null) { methodSpecBuilder.addAnnotation(spec.getScopeAnnotationSpec()); } return TypeSpec.classBuilder(spec.getClassName().simpleName()) .addModifiers(Modifier.PUBLIC) .addAnnotation(Module.class) .addMethod(methodSpecBuilder.build()) .build(); }
private static TypeSpec createBuilderClass(AutoBundleBindingClass target) { return TypeSpec.classBuilder(target.getBuilderClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC) .addField(createField(FIELD_BUNDLE_NAME)) .addMethod(createBuilderConstructor(target, FIELD_BUNDLE_NAME)) .addMethods(createBuilderMethods(target, FIELD_BUNDLE_NAME)) .addMethods(createBuildMethods(target, FIELD_BUNDLE_NAME)) .build(); }
public TypeSpec innerAnnotation(Set<String> columnNameSet) { String identifier = columnNameSet.contains(name()) ? name() + "_" : name(); return TypeSpec.annotationBuilder(identifier) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addAnnotation(retention()) .addAnnotation(target()) .addAnnotation(ForeignKeyAnnotation.class) .addAnnotation(columnAnnotationClassArrayAnnotation()) .addAnnotation(referencesAnnotationClassArrayAnnotation()) .build(); }
TypeSpec type() { return TypeSpec.classBuilder(exportClassName.simpleName()) .addAnnotation(SchemaCompiler.GENERATED) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addField(instanceField()) .addField(versionSetField()) .addMethod(constructor()) .addMethod(getMethod()) .addMethod(toStringMethod()) .build(); }
@Override public TypeSpec buildTypeSpec() { TypeSpec.Builder classBuilder = TypeSpec.classBuilder(schema.getSchemaClassName().simpleName()); classBuilder.addModifiers(Modifier.PUBLIC); classBuilder.addSuperinterface(Types.getSchema(schema.getModelClassName())); classBuilder.addFields(buildFieldSpecs()); classBuilder.addMethods(buildMethodSpecs()); return classBuilder.build(); }
public void write(Filer filer) throws IOException { TypeSpec clazz = TypeSpec.classBuilder(bindingClass.getHelperClassName()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addType(createBuilderClass(bindingClass)) .addMethod(createCallBuilderMethod(bindingClass)) .addMethod(createBindMethod(bindingClass)) .addMethod(createBindWithSourceMethod(bindingClass)) .addMethod(createPackMethod(bindingClass)) .build(); JavaFile.builder(bindingClass.getPackageName(), clazz).build().writeTo(filer); }
private TypeSpec migrationType() { MigrationVersionMetadata migrationVersion = schemaName().migrationVersion(); ClassName className = migrationVersion.className(); return TypeSpec.classBuilder(className.simpleName()) .addAnnotation(migrationAnnotation()) .addTypes( tableInfoList() .stream() .map(TableInfoMetadata::type) .collect(MoreCollectors.toImmutableList())) .build(); }
private TypeSpec schemaType() { MigrationVersionMetadata migrationVersion = schemaName().migrationVersion(); return TypeSpec.classBuilder(schemaName().simpleName()) .addAnnotation(schemaAnnotation(migrationVersion)) .addModifiers(Modifier.PUBLIC) .addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build()) .addMethods( tableInfoList() .stream() .map(TableInfoMetadata::schemaMethod) .collect(MoreCollectors.toImmutableList())) .build(); }
private void generate(RestActionClass actionClass) { TypeSpec.Builder classBuilder = TypeSpec.classBuilder(actionClass.getHelperName()) .addModifiers(Modifier.PUBLIC) .addJavadoc("SantaRest compile time, autogenerated class, which fills actions") .addSuperinterface( ParameterizedTypeName.get( ClassName.get(SantaRest.ActionHelper.class), actionClass.getTypeName())); classBuilder.addMethod(createRequestMethod(actionClass)); classBuilder.addMethod(createFillResponseMethod(actionClass)); classBuilder.addMethod(createFillErrorMethod(actionClass)); saveClass(actionClass.getPackageName(), classBuilder.build()); }
/** The access modifier is that of the sourceType. */ @NonNull @Override public TypeSpec getTypeSpec() { TypeSpec.Builder result = TypeSpec.classBuilder(getTypeName()); sourceType.applyAccessModifier(result); sourceType.applyTypeVariables(result); result.addJavadoc(createGeneratedAnnotation(processorClass).toString()); result.addJavadoc("\n"); result.addSuperinterface(getDecoratedTypeName()); for (Element element : sourceType.getAllEnclosedElements()) { if (element.getKind() == ElementKind.METHOD) { MethodSpec method = createOverridingMethod((ExecutableElement) element).build(); result.addMethod(method); } } return result.build(); }
public TypeSpec createTerminalType() { final TypeName terminal = ParameterizedTypeName.get( ClassName.get(Terminal.class), ClassName.get(packageName, terminalName)); return TypeSpec.classBuilder(terminalName) .addJavadoc("The <$L> element.\n", tag) .addAnnotation(AnnotationSpec.builder(Root.class).build()) .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addSuperinterface(terminal) .addField(createFieldMissing()) .addField(createFieldValue()) .addMethod(createPublicConstructor()) .addMethod(createPrivateConstructor()) .addMethod(createValueGetter()) .addMethod(createCompareTo()) .addMethod(createHashCode()) .addMethod(createEquals()) .addMethod(createShow()) .build(); }
private DeriveResult<DerivedCodeSpec> functionDispatchImpl(List<DataConstructor> constructors) { NameAllocator nameAllocator = nameAllocator(constructors); TypeElement f = FlavourImpl.findF(context.flavour(), utils.elements()); TypeName returnType = TypeName.get( utils .types() .getDeclaredType( f, adt.typeConstructor().declaredType(), adt.matchMethod().returnTypeVariable())); TypeSpec wrapper = TypeSpec.anonymousClassBuilder("") .addField( FieldSpec.builder(returnType, nameAllocator.get("cata")) .initializer( CodeBlock.builder() .addStatement( "$L -> $L.$L($L)", nameAllocator.get("adt var"), nameAllocator.get("adt var"), adt.matchMethod().element().getSimpleName(), Utils.joinStringsAsArguments( constructors .stream() .map( constructor -> constructor .arguments() .stream() .map(DataArguments::getType) .noneMatch( tm -> utils .types() .isSameType( tm, adt.typeConstructor() .declaredType())) ? constructor.name() : CodeBlock.builder() .add( "($L) -> $L.$L($L)", Utils.asLambdaParametersString( constructor.arguments(), constructor.typeRestrictions()), constructor.name(), MapperDerivator.mapperApplyMethod( utils, context, constructor), Utils.joinStringsAsArguments( Stream.concat( constructor .arguments() .stream() .map( argument -> utils .types() .isSameType( argument .type(), adt.typeConstructor() .declaredType()) ? "() -> this." + nameAllocator .get( "cata") + "." + FlavourImpl .functionApplyMethod( utils, context) + "(" + argument .fieldName() + ")" : argument .fieldName()), constructor .typeRestrictions() .stream() .map( TypeRestriction ::idFunction) .map( DataArgument ::fieldName)))) .build() .toString()))) .build()) .build()) .build(); MethodSpec cataMethod = MethodSpec.methodBuilder("cata") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariables( Stream.concat( adt.typeConstructor().typeVariables().stream(), Stream.of(adt.matchMethod().returnTypeVariable())) .map(TypeVariableName::get) .collect(Collectors.toList())) .returns(returnType) .addParameters( constructors .stream() .map( dc -> ParameterSpec.builder( cataMapperTypeName(dc), MapperDerivator.mapperFieldName(dc)) .build()) .collect(toList())) .addStatement("return $L.$L", wrapper, nameAllocator.get("cata")) .build(); return result(methodSpec(cataMethod)); }
public static DeriveResult<DerivedCodeSpec> derive( AlgebraicDataType adt, DeriveContext deriveContext, DeriveUtils deriveUtils) { // skip constructors for enums if (adt.typeConstructor().declaredType().asElement().getKind() == ElementKind.ENUM) { return result(none()); } TypeConstructor typeConstructor = adt.typeConstructor(); TypeElement lazyTypeElement = FlavourImpl.findF0(deriveContext.flavour(), deriveUtils.elements()); TypeName lazyArgTypeName = TypeName.get( deriveUtils.types().getDeclaredType(lazyTypeElement, typeConstructor.declaredType())); String lazyArgName = Utils.uncapitalize(typeConstructor.typeElement().getSimpleName()); TypeName typeName = TypeName.get(typeConstructor.declaredType()); List<TypeVariableName> typeVariableNames = adt.typeConstructor() .typeVariables() .stream() .map(TypeVariableName::get) .collect(Collectors.toList()); String className = "Lazy"; TypeSpec.Builder typeSpecBuilder = TypeSpec.classBuilder(className) .addModifiers(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL) .addTypeVariables(typeVariableNames) .addField( FieldSpec.builder( TypeName.get(Object.class), "lock", Modifier.PRIVATE, Modifier.FINAL) .initializer("new Object()") .build()) .addField(FieldSpec.builder(lazyArgTypeName, "expression", Modifier.PRIVATE).build()) .addField( FieldSpec.builder(typeName, "evaluation", Modifier.PRIVATE, Modifier.VOLATILE) .build()) .addMethod( MethodSpec.constructorBuilder() .addParameter(ParameterSpec.builder(lazyArgTypeName, lazyArgName).build()) .addStatement("this.expression = $N", lazyArgName) .build()) .addMethod( MethodSpec.methodBuilder("eval") .addModifiers(Modifier.PRIVATE) .returns(typeName) .addCode( CodeBlock.builder() .addStatement("$T _evaluation = this.evaluation", typeName) .beginControlFlow("if (_evaluation == null)") .beginControlFlow("synchronized (this.lock)") .addStatement("_evaluation = this.evaluation") .beginControlFlow("if (_evaluation == null)") .addStatement( "this.evaluation = _evaluation = expression.$L()", Utils.getAbstractMethods(lazyTypeElement.getEnclosedElements()) .get(0) .getSimpleName()) .addStatement("this.expression = null") .endControlFlow() .endControlFlow() .endControlFlow() .addStatement("return _evaluation") .build()) .build()) .addMethod( Utils.overrideMethodBuilder(adt.matchMethod().element()) .addStatement( "return this.eval().$L($L)", adt.matchMethod().element().getSimpleName(), Utils.asArgumentsStringOld(adt.matchMethod().element().getParameters())) .build()); if (adt.typeConstructor().declaredType().asElement().getKind() == ElementKind.INTERFACE) { typeSpecBuilder.addSuperinterface(typeName); } else { typeSpecBuilder.superclass(typeName); } typeSpecBuilder.addMethods( optionalAsStream( findAbstractEquals(typeConstructor.typeElement(), deriveUtils.elements()) .map( equals -> deriveUtils .overrideMethodBuilder(equals) .addStatement( "return this.eval().equals($L)", equals.getParameters().get(0).getSimpleName()) .build())) .collect(Collectors.toList())); typeSpecBuilder.addMethods( optionalAsStream( findAbstractHashCode(typeConstructor.typeElement(), deriveUtils.elements()) .map( hashCode -> deriveUtils .overrideMethodBuilder(hashCode) .addStatement("return this.eval().hashCode()") .build())) .collect(Collectors.toList())); typeSpecBuilder.addMethods( optionalAsStream( findAbstractToString(typeConstructor.typeElement(), deriveUtils.elements()) .map( toString -> deriveUtils .overrideMethodBuilder(toString) .addStatement("return this.eval().toString()") .build())) .collect(Collectors.toList())); return result( codeSpec( typeSpecBuilder.build(), MethodSpec.methodBuilder("lazy") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariables( typeConstructor .typeVariables() .stream() .map(TypeVariableName::get) .collect(Collectors.toList())) .addParameter(lazyArgTypeName, lazyArgName) .returns(typeName) .addStatement( "return new $L$L($L)", className, typeVariableNames.isEmpty() ? "" : "<>", lazyArgName) .build())); }
private TypeSpec build(ScopeSpec spec) { MethodSpec configureScopeSpec = MethodSpec.methodBuilder("configureScope") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addParameter(ClassName.get(MortarScope.Builder.class), "builder") .addParameter(ClassName.get(MortarScope.class), "parentScope") .addCode( CodeBlock.builder() .add( "builder.withService($T.SERVICE_NAME, $T.builder()\n", DAGGERSERVICE_CLS, spec.getDaggerComponentTypeName()) .indent() .add( ".$L(parentScope.<$T>getService($T.SERVICE_NAME))\n", spec.getDaggerComponentBuilderDependencyMethodName(), spec.getDaggerComponentBuilderDependencyTypeName(), DAGGERSERVICE_CLS) .add(".module(new Module())\n") .add(".build());\n") .unindent() .build()) .build(); List<FieldSpec> fieldSpecs = new ArrayList<>(); for (ParameterSpec parameterSpec : spec.getModuleSpec().getInternalParameters()) { fieldSpecs.add(FieldSpec.builder(parameterSpec.type, parameterSpec.name).build()); } MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addAnnotation(AnnotationSpec.builder(ParcelConstructor.class).build()) .addParameters(spec.getModuleSpec().getInternalParameters()); for (ParameterSpec parameterSpec : spec.getModuleSpec().getInternalParameters()) { constructorBuilder.addStatement("this.$L = $L", parameterSpec.name, parameterSpec.name); } TypeSpec.Builder builder = TypeSpec.classBuilder(spec.getClassName().simpleName()) .addModifiers(Modifier.PUBLIC) .addAnnotation( AnnotationSpec.builder(Generated.class) .addMember( "value", "$S", architect.autostack.compiler.AnnotationProcessor.class.getName()) .build()) .addAnnotation(spec.getComponentAnnotationSpec()) .addAnnotation( AnnotationSpec.builder(Parcel.class).addMember("parcelsIndex", "false").build()) .addType(buildModule(spec.getModuleSpec())) .addMethod(constructorBuilder.build()) .addMethod(configureScopeSpec) .addFields(fieldSpecs); if (spec.getScopeAnnotationSpec() != null) { builder.addAnnotation(spec.getScopeAnnotationSpec()); } if (spec.getPathViewTypeName() != null) { builder.addSuperinterface(PATH_CLS); MethodSpec createViewSpec = MethodSpec.methodBuilder("createView") .addModifiers(Modifier.PUBLIC) .returns(spec.getPathViewTypeName()) .addAnnotation(Override.class) .addParameter(CONTEXT_CLS, "context") .addStatement("return new $T(context)", spec.getPathViewTypeName()) .build(); builder.addMethod(createViewSpec); } else { builder.addSuperinterface(STACKABLE_CLS); } return builder.build(); }
@Override Optional<TypeSpec.Builder> write(ClassName generatedTypeName, MembersInjectionBinding binding) { // Empty members injection bindings are special and don't need source files. if (binding.injectionSites().isEmpty()) { return Optional.absent(); } // We don't want to write out resolved bindings -- we want to write out the generic version. checkState(!binding.unresolved().isPresent()); ImmutableList<TypeVariableName> typeParameters = bindingTypeElementTypeVariableNames(binding); TypeSpec.Builder injectorTypeBuilder = TypeSpec.classBuilder(generatedTypeName.simpleName()) .addModifiers(PUBLIC, FINAL) .addTypeVariables(typeParameters); TypeName injectedTypeName = TypeName.get(binding.key().type()); TypeName implementedType = membersInjectorOf(injectedTypeName); injectorTypeBuilder.addSuperinterface(implementedType); MethodSpec.Builder injectMembersBuilder = MethodSpec.methodBuilder("injectMembers") .returns(TypeName.VOID) .addModifiers(PUBLIC) .addAnnotation(Override.class) .addParameter(injectedTypeName, "instance") .addCode("if (instance == null) {") .addStatement( "throw new $T($S)", NullPointerException.class, "Cannot inject members into a null reference") .addCode("}"); ImmutableMap<BindingKey, FrameworkField> fields = SourceFiles.generateBindingFieldsForDependencies(dependencyRequestMapper, binding); ImmutableMap.Builder<BindingKey, FieldSpec> dependencyFieldsBuilder = ImmutableMap.builder(); MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder().addModifiers(PUBLIC); // We use a static create method so that generated components can avoid having // to refer to the generic types of the factory. // (Otherwise they may have visibility problems referring to the types.) MethodSpec.Builder createMethodBuilder = MethodSpec.methodBuilder("create") .returns(implementedType) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariables(typeParameters); createMethodBuilder.addCode( "return new $T(", javapoetParameterizedGeneratedTypeNameForBinding(binding)); ImmutableList.Builder<CodeBlock> constructorInvocationParameters = ImmutableList.builder(); boolean usesRawFrameworkTypes = false; UniqueNames fieldNames = new UniqueNames(); for (Entry<BindingKey, FrameworkField> fieldEntry : fields.entrySet()) { BindingKey bindingKey = fieldEntry.getKey(); FrameworkField bindingField = fieldEntry.getValue(); // If the dependency type is not visible to this members injector, then use the raw framework // type for the field. boolean useRawFrameworkType = !VISIBLE_TO_MEMBERS_INJECTOR.visit(bindingKey.key().type(), binding); String fieldName = fieldNames.getUniqueName(bindingField.name()); TypeName fieldType = useRawFrameworkType ? bindingField.javapoetFrameworkType().rawType : bindingField.javapoetFrameworkType(); FieldSpec.Builder fieldBuilder = FieldSpec.builder(fieldType, fieldName, PRIVATE, FINAL); ParameterSpec.Builder parameterBuilder = ParameterSpec.builder(fieldType, fieldName); // If we're using the raw type for the field, then suppress the injectMembers method's // unchecked-type warning and the field's and the constructor and create-method's // parameters' raw-type warnings. if (useRawFrameworkType) { usesRawFrameworkTypes = true; fieldBuilder.addAnnotation(SUPPRESS_WARNINGS_RAWTYPES); parameterBuilder.addAnnotation(SUPPRESS_WARNINGS_RAWTYPES); } constructorBuilder.addParameter(parameterBuilder.build()); createMethodBuilder.addParameter(parameterBuilder.build()); FieldSpec field = fieldBuilder.build(); injectorTypeBuilder.addField(field); constructorBuilder.addStatement("assert $N != null", field); constructorBuilder.addStatement("this.$N = $N", field, field); dependencyFieldsBuilder.put(bindingKey, field); constructorInvocationParameters.add(CodeBlocks.format("$N", field)); } createMethodBuilder.addCode(CodeBlocks.join(constructorInvocationParameters.build(), ", ")); createMethodBuilder.addCode(");"); injectorTypeBuilder.addMethod(constructorBuilder.build()); injectorTypeBuilder.addMethod(createMethodBuilder.build()); Set<String> delegateMethods = new HashSet<>(); ImmutableMap<BindingKey, FieldSpec> dependencyFields = dependencyFieldsBuilder.build(); List<MethodSpec> injectMethodsForSubclasses = new ArrayList<>(); for (InjectionSite injectionSite : binding.injectionSites()) { injectMembersBuilder.addCode( visibleToMembersInjector(binding, injectionSite.element()) ? directInjectMemberCodeBlock(binding, dependencyFields, injectionSite) : delegateInjectMemberCodeBlock(dependencyFields, injectionSite)); if (!injectionSite.element().getModifiers().contains(PUBLIC) && injectionSite.element().getEnclosingElement().equals(binding.bindingElement()) && delegateMethods.add(injectionSiteDelegateMethodName(injectionSite.element()))) { injectMethodsForSubclasses.add( injectorMethodForSubclasses( dependencyFields, typeParameters, injectedTypeName, injectionSite.element(), injectionSite.dependencies())); } } if (usesRawFrameworkTypes) { injectMembersBuilder.addAnnotation(SUPPRESS_WARNINGS_UNCHECKED); } injectorTypeBuilder.addMethod(injectMembersBuilder.build()); for (MethodSpec methodSpec : injectMethodsForSubclasses) { injectorTypeBuilder.addMethod(methodSpec); } return Optional.of(injectorTypeBuilder); }