final TypeSpec.Builder directFunctionArgs = TypeSpec.classBuilder(functionArgsClassname) .addModifiers(Modifier.PRIVATE) .superclass(ClassName.get(FunctionArgs.class)); final MethodSpec.Builder constructorBuilder = MethodSpec.constructorBuilder() .addStatement("super($L, $T.emptyMap())", funcReferenceName, ClassName.get(Collections.class)); pd.name()); parameterValues.add(CodeBlock.builder() .beginControlFlow("case $S:", pd.name()) .addStatement("return transformed$$$L", pd.name()) .endControlFlow().build()); }); directFunctionArgs.addMethod(MethodSpec.methodBuilder("getPreComputedValue") .returns(TypeName.OBJECT) .addParameter(String.class, "name") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .addCode(CodeBlock.builder() .beginControlFlow("switch (name)") .add(parameterValues.build()) .endControlFlow() .addStatement("return null") .build()) .build());
SpecMethodModel<EventMethod, EventDeclarationModel> eventMethodModel) { MethodSpec.Builder triggerMethod = MethodSpec.methodBuilder(eventMethodModel.name.toString()).addModifiers(Modifier.STATIC); triggerMethod.addParameter(contextClassName, "c"); triggerMethod.addStatement( "$L component = ($L) c.$L()", componentClass, componentClass, scopeMethodName); CodeBlock.builder().add("\n($T) $L", ClassNames.EVENT_TRIGGER_TARGET, "component"); eventTriggerParams.add(",\n$L", methodParamModel.getName()); continue; eventTriggerParams.add(",\n$L", methodParamModel.getName()); if (eventDeclaration.returnType == null || eventDeclaration.returnType.equals(TypeName.VOID)) { triggerMethod.addStatement( "component.$L($L)", eventMethodModel.name, eventTriggerParams.build()); } else { triggerMethod .addStatement( "return component.$L($L)", eventMethodModel.name, eventTriggerParams.build()) .returns(eventDeclaration.returnType);
constructor.addModifiers(Modifier.PUBLIC); } else { classBuilder.addSuperinterface(ClassName.get(PACKAGE, builderVisibleName)); final CodeBlock.Builder always = CodeBlock.builder(); final CodeBlock.Builder whenAnnotationPresent = CodeBlock.builder(); final CodeBlock.Builder whenAnnotationMissing = CodeBlock.builder(); ClassName builder = ClassName.get(PACKAGE, builderName); elements.stream().filter(BuilderElement.class::isInstance).map(BuilderElement.class::cast).forEach(m -> m.addToBuilder(classBuilder, builder, always, whenAnnotationPresent, whenAnnotationMissing)); constructor.addCode(always.build()) .beginControlFlow("if ($L)", Strings.FIELD_ENABLED) .addCode(whenAnnotationPresent.build()) .nextControlFlow("else") .addCode(whenAnnotationMissing.build()) .endControlFlow(); classBuilder.addMethod(constructor.build()); final BuildMethodCreator build = new BuildMethodCreator(Types.getOnlyMethod(processingEnv, ConfigurationBuilder.class.getName()), ClassName.get(PACKAGE, configName)); elements.stream().filter(ValidatedElement.class::isInstance).map(ValidatedElement.class::cast).forEach(element -> element.addToBuildMethod(build)); classBuilder.addMethod(build.build());
methodBuilder.addStatement("throw new RuntimeException" + "(\"cannot call constant function with void return type\")"); } else if (outputParameterTypes.size() == 1) { nativeReturnTypeName = getWrapperType(typeName); methodBuilder.returns(buildRemoteCall(nativeReturnTypeName)); methodBuilder.addStatement("final $T function = " + "new $T($N, \n$T.<$T>asList($L), " + "\n$T.<$T<?>>asList(new $T<$T>() {}))", if (nativeReturnTypeName.equals(ClassName.get(List.class))) { CodeBlock.Builder callCode = CodeBlock.builder(); callCode.addStatement( "$T result = " + "($T) executeCallSingleValueReturn(function, $T.class)", listType, listType, nativeReturnTypeName); callCode.addStatement("return convertToNative(result)"); .addException(Exception.class) .returns(nativeReturnTypeName) .addCode(callCode.build()) .build()) .build();
static TypeSpecDataHolder generateGetEventHandlerMethod( SpecModel specModel, EventDeclarationModel eventDeclaration) { final String scopeMethodName = specModel.getScopeMethodName(); return TypeSpecDataHolder.newBuilder() .addMethod( MethodSpec.methodBuilder("get" + eventDeclaration.name.simpleName() + "Handler") .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .returns(ClassNames.EVENT_HANDLER) .addParameter(specModel.getContextClass(), "context") .addCode( CodeBlock.builder() .beginControlFlow("if (context.$L() == null)", scopeMethodName) .addStatement("return null") .endControlFlow() .build()) .addStatement( "return (($L) context.$L()).$L", specModel.getComponentName(), scopeMethodName, ComponentBodyGenerator.getEventHandlerInstanceName(eventDeclaration.name)) .build()) .build(); }
private static MethodSpec generateRecordRenderDataMethod(SpecModel specModel) { final TypeName renderInfoTypeName = ClassName.bestGuess(getRenderDataImplClassName(specModel)); final CodeBlock code = CodeBlock.builder() .add("$T $L = $L != null ?\n", renderInfoTypeName, "renderInfo", "toRecycle") .indent() .add("($T) $L :\n", renderInfoTypeName, "toRecycle") .add("new $T();\n", renderInfoTypeName) .unindent() .addStatement("$L.record(this)", "renderInfo") .addStatement("return $L", "renderInfo") .build(); return MethodSpec.methodBuilder("recordRenderData") .addAnnotation(Override.class) .addModifiers(Modifier.PROTECTED) .addParameter(ClassNames.RENDER_DATA, "toRecycle") .returns(ClassNames.RENDER_DATA) .addCode(code) .build(); }
MethodSpec.methodBuilder("dispatch" + eventDeclaration.name.simpleName()) .addModifiers(Modifier.STATIC) .addParameter(ClassNames.EVENT_HANDLER, "_eventHandler"); final CodeBlock.Builder resetCode = CodeBlock.builder(); for (FieldModel fieldModel : eventDeclaration.fields) { if (fieldModel.field.modifiers.contains(Modifier.FINAL)) { .addParameter(fieldModel.field.type, fieldModel.field.name) .addStatement("_eventState.$L = $L", fieldModel.field.name, fieldModel.field.name); if (!fieldModel.field.type.isPrimitive()) { resetCode.addStatement("_eventState.$L = null", fieldModel.field.name); ClassNames.EVENT_DISPATCHER); resetCode.addStatement("$L.release(_eventState)", poolName); if (eventDeclaration.returnType.equals(TypeName.VOID)) { eventDispatcherMethod.addStatement("_lifecycle.dispatchOnEvent(_eventHandler, _eventState)"); eventDispatcherMethod.addCode(resetCode.build()); } else { eventDispatcherMethod eventDeclaration.returnType) .returns(eventDeclaration.returnType); eventDispatcherMethod.addCode(resetCode.build()); eventDispatcherMethod.addStatement("return result");
private void generateDeepLinkDelegate(String packageName, List<TypeElement> loaderClasses) throws IOException { CodeBlock.Builder loadersInitializer = CodeBlock.builder() .add("super($T.asList(\n", ClassName.get(Arrays.class)) .indent(); int totalElements = loaderClasses.size(); for (int i = 0; i < totalElements; i++) { loadersInitializer.add("$L$L", decapitalize(moduleNameToLoaderName(loaderClasses.get(i))), i < totalElements - 1 ? ",\n" : "\n"); MethodSpec constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameters(FluentIterable.from(loaderClasses).transform( new Function<TypeElement, ParameterSpec>() { @Override public ParameterSpec apply(TypeElement typeElement) { .addCode(loadersInitializer.unindent().add("));\n").build()) .build();
String prefix = ""; CodeBlock.Builder codeBlockBuilder = CodeBlock.builder(); if (constructorInjectionTarget.throwsThrowable) { codeBlockBuilder.beginControlFlow("try"); CodeBlock invokeScopeGetMethodWithNameCodeBlock = getInvokeScopeGetMethodWithNameCodeBlock(paramInjectionTarget); String paramName = "param" + counter++; codeBlockBuilder.add("$T $L = scope.", getParamType(paramInjectionTarget), paramName); codeBlockBuilder.add(invokeScopeGetMethodWithNameCodeBlock); codeBlockBuilder.add(";"); codeBlockBuilder.add(LINE_SEPARATOR); localVarStatement.append(prefix); localVarStatement.append(paramName); codeBlockBuilder.addStatement(localVarStatement.toString()); codeBlockBuilder.addStatement("memberInjector.inject($L, scope)", varName); codeBlockBuilder.addStatement("return $L", varName); if (constructorInjectionTarget.throwsThrowable) { codeBlockBuilder.nextControlFlow("catch($L ex)", ClassName.get(Throwable.class)); codeBlockBuilder.addStatement("throw new $L(ex)", ClassName.get(RuntimeException.class)); codeBlockBuilder.endControlFlow(); createInstanceBuilder.addCode(codeBlockBuilder.build());
result.beginControlFlow("if (view != null)"); bindName = "view"; CodeBlock.Builder builder = CodeBlock.builder(); if (hasReturnType) { builder.add("return "); builder.add("target.$L(", methodBinding.getName()); List<Parameter> parameters = methodBinding.getParameters(); String[] listenerParameters = method.parameters(); for (int i = 0, count = parameters.size(); i < count; i++) { if (i > 0) { builder.add(", "); builder.add("$T.castParam(p$L, $S, $L, $S, $L, $T.class)", UTILS, listenerPosition, method.name(), listenerPosition, methodBinding.getName(), i, parameter.getType()); } else { builder.add("($T) p$L", parameter.getType(), listenerPosition); builder.add("p$L", listenerPosition); builder.add(");\n"); builder.add("$L;\n", method.defaultReturn()); callbackMethod.addCode(builder.build());
static MethodSpec generateEventHandlerFactory( SpecMethodModel<EventMethod, EventDeclarationModel> eventMethodModel, TypeName paramClass) { final MethodSpec.Builder builder = MethodSpec.methodBuilder(eventMethodModel.name.toString()) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addTypeVariables(eventMethodModel.typeVariables) .addParameter(paramClass, "c") .returns( ParameterizedTypeName.get( ClassNames.EVENT_HANDLER, eventMethodModel.typeModel.name)); final CodeBlock.Builder paramsBlock = CodeBlock.builder(); paramsBlock.add("new Object[] {\n"); paramsBlock.indent(); paramsBlock.add("c,\n"); builder.addParameter(methodParamModel.getTypeName(), methodParamModel.getName()); paramsBlock.add("$L,\n", methodParamModel.getName()); paramsBlock.unindent(); paramsBlock.add("}"); builder.addStatement( "return newEventHandler(c, $L, $L)", eventMethodModel.name.toString().hashCode(), paramsBlock.build()); return builder.build();
private CodeBlock includesInitializer(TypeElement type, Object[] includes) { CodeBlock.Builder result = CodeBlock.builder(); result.add("{ "); for (Object include : includes) { if (!(include instanceof TypeMirror)) { // TODO(tbroyer): pass annotation information processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Unexpected value: " + include + " in includes of " + type, type); continue; } TypeMirror typeMirror = (TypeMirror) include; result.add("$T.class, ", typeMirror); } result.add("}"); return result.build(); }
final TypeName singleParameterType = varArgType.typeArguments.get(0); final ParameterizedTypeName listType = ParameterizedTypeName.get(ClassName.get(ArrayList.class), singleParameterType); CodeBlock.Builder codeBlockBuilder = CodeBlock.builder(); codeBlockBuilder.beginControlFlow( "if (this.$L.$L == null || this.$L.$L == $L.$L)", componentMemberInstanceName, propName); } else { codeBlockBuilder.beginControlFlow( "if (this.$L.$L == null)", componentMemberInstanceName, propName); .addStatement("this.$L.$L = new $T()", componentMemberInstanceName, propName, listType) .endControlFlow() .add( "final $T res = ", singleParameterType.isBoxedPrimitive() ? singleParameterType.unbox() : singleParameterType) .addStatement(statement, formatObjects) .addStatement("this.$L.$L.add(res)", componentMemberInstanceName, propName); return getMethodSpecBuilder(specModel, prop, requiredIndex, name, parameters, codeBlockBuilder.build());
final CodeBlock.Builder argAssignment = CodeBlock.builder(); args.getArgs().forEach((name, argExpr) -> { final Object varRef = blockOrMissing(codeSnippet.get(argExpr), argExpr); target.addStatement("$L.setAndTransform$$$L($L)", mangledFuncArgsHolder, name, varRef); }); currentMethod.addCode(argAssignment.build()); CodeBlock functionInvocation = CodeBlock.of("$L.evaluate($L, context)", mangledFunctionName, mangledFuncArgsHolder); currentMethod.addStatement("$L", functionInvocation); } else { currentMethod.addStatement("$T $L = $L", ClassName.get(function.returnType()), functionValueVarName, functionInvocation); FieldSpec.builder(expr.getFunction().getClass(), mangledFunctionName, Modifier.PRIVATE, Modifier.FINAL) .build()); functionReferences.add(CodeBlock.of("$L = ($T) functionRegistry.resolve($S)", mangledFunctionName, expr.getFunction().getClass(),
final CodeBlock.Builder codeBlock = CodeBlock.builder(); codeBlock .add( "final $L inputs = new $L(", getInputsClassName(cachedValueName), getInputsClassName(cachedValueName)) .indent(); codeBlock.add( "$L,", ComponentBodyGenerator.getImplAccessor( specModel, onCalculateCachedValueMethod.methodParams.get(i))); } else { codeBlock.add( "$L);\n", ComponentBodyGenerator.getImplAccessor( codeBlock.unindent(); .addCode(codeBlock.build()) final CodeBlock.Builder delegation = CodeBlock.builder(); delegation .add( "$L = $L.$L(", cachedValueName, specModel.getSpecName(), onCalculateCachedValueMethod.name) .indent();
private static MethodSpec generateCommonStaticTriggerMethodCode( ClassName contextClassName, SpecMethodModel<EventMethod, EventDeclarationModel> eventMethodModel, MethodSpec.Builder eventTriggerMethod) { EventDeclarationModel eventDeclaration = eventMethodModel.typeModel; eventTriggerMethod.addStatement( "$T _eventState = new $T()", eventDeclaration.name, // need to make these into types eventDeclaration.name); final CodeBlock.Builder paramsBlock = CodeBlock.builder(); paramsBlock.add("new Object[] {\n"); paramsBlock.indent(); addParametersToStaticTriggerMethods(contextClassName, eventMethodModel, eventTriggerMethod); addTriggerParams(contextClassName, eventMethodModel, eventTriggerMethod, paramsBlock); paramsBlock.unindent(); paramsBlock.add("}"); if (eventDeclaration.returnType == null || eventDeclaration.returnType.equals(TypeName.VOID)) { eventTriggerMethod.addStatement( "trigger.dispatchOnTrigger(_eventState, $L)", paramsBlock.build()); } else { eventTriggerMethod .addStatement( "return ($L) trigger.dispatchOnTrigger(_eventState, $L)", eventDeclaration.returnType, paramsBlock.build()) .returns(eventDeclaration.returnType); } return eventTriggerMethod.build(); }
stateContainerClassBuilder.addField( FieldSpec.builder( ParameterizedTypeName.get(ClassNames.LIST, specModel.getTransitionClass().box()), GeneratorConstants.STATE_TRANSITIONS_FIELD_NAME) .initializer("new $T<>()", ClassNames.ARRAY_LIST) MethodSpec.methodBuilder("consumeTransitions") .addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class) .returns( ParameterizedTypeName.get(ClassNames.LIST, specModel.getTransitionClass().box())) .addCode( CodeBlock.builder() .beginControlFlow( "if ($L.isEmpty())", GeneratorConstants.STATE_TRANSITIONS_FIELD_NAME) .addStatement("return $T.EMPTY_LIST", ClassNames.COLLECTIONS) .endControlFlow() .build()) .addStatement( "$T<$T> $N",
private MethodSpec getTypeMethod(Data.MethodData m) { CodeBlock.Builder code = CodeBlock.builder() .addStatement("$T obj = decorators.$L($L)", TypeName.get(m._method.getReturnType()), m._method.getSimpleName(), getCommaSeparatedParams(m, buffer)) .beginControlFlow("if (obj != null)") .addStatement("return obj") .nextControlFlow("else") .add("//region user inputed code\n") .add(MethodBodyReader.getMethodBody(processingEnv, m)) .add("//endregion\n") .endControlFlow(); return buildEmptyMethod(m, true) .addCode(code.build()) .build(); }
ParameterizedTypeName.get(ClassName.get(ArrayList.class), varArgTypeName); CodeBlock.Builder codeBlockBuilder = CodeBlock.builder() .beginControlFlow("if ($L == null)", varArgName) .addStatement("return this") .endControlFlow(); codeBlockBuilder.beginControlFlow( "if (this.$L.$L == null || this.$L.$L == $L.$L)", implMemberInstanceName, propName); } else { codeBlockBuilder.beginControlFlow( "if (this.$L.$L == null)", implMemberInstanceName, propName); .addStatement("this.$L.$L = new $T()", implMemberInstanceName, propName, listType) .endControlFlow() .addStatement("this.$L.$L.add($L)", implMemberInstanceName, propName, varArgName) .build(); Arrays.asList(parameter(prop, varArgTypeName, varArgName, extraAnnotations)), codeBlock) .build();
CodeBlock.Builder builder = CodeBlock.builder(); builder.add("$T.asList(", Arrays.class); boolean first = true; for (Object o : (List<?>) value) { if (!first) builder.add(","); first = false; builder.add("\n$>$>$L$<$<", fieldInitializer(type, o)); builder.add(")"); return builder.build(); CodeBlock.Builder builder = CodeBlock.builder(); builder.add("new $T.Builder()", javaType); for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { ProtoMember protoMember = (ProtoMember) entry.getKey(); Field field = schema.getField(protoMember); CodeBlock valueInitializer = fieldInitializer(field.type(), entry.getValue()); builder.add("\n$>$>.$L($L)$<$<", fieldName(type, field), valueInitializer); builder.add("\n$>$>.build()$<$<"); return builder.build(); } else if (javaType.equals(TypeName.BOOLEAN.box())) { return CodeBlock.of("$L", value != null ? value : false); } else if (javaType.equals(TypeName.INT.box())) { return CodeBlock.of("$L", valueToInt(value));