Java Code Examples for lombok.javac.JavacTreeMaker#Return

The following examples show how to use lombok.javac.JavacTreeMaker#Return . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.generateMethods(data, builderType, source, fluent, chain);
		return;
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	
	JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
 
Example 2
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
	if (useGuavaInstead(builderType)) {
		guavaListSetSingularizer.generateMethods(data, builderType, source, fluent, chain);
		return;
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	Name thisName = builderType.toName("this");
	
	JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	JCStatement returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
	generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	returnStatement = chain ? maker.Return(maker.Ident(thisName)) : null;
	generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
 
Example 3
Source File: HandleBuilder.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCMethodDecl generateBuilderMethod(String builderMethodName, String builderClassName, JavacNode type, List<JCTypeParameter> typeParams) {
	JavacTreeMaker maker = type.getTreeMaker();
	
	ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
	for (JCTypeParameter typeParam : typeParams) {
		typeArgs.append(maker.Ident(typeParam.name));
	}
	
	JCExpression call = maker.NewClass(null, List.<JCExpression>nil(), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), List.<JCExpression>nil(), null);
	JCStatement statement = maker.Return(call);
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(statement));
	return maker.MethodDef(maker.Modifiers(Flags.STATIC | Flags.PUBLIC), type.toName(builderMethodName), namePlusTypeParamsToTypeReference(maker, type.toName(builderClassName), typeParams), copyTypeParams(maker, typeParams), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null);
}
 
Example 4
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void generateMethods(SingularData data, JavacNode builderType, JCTree source, boolean fluent, boolean chain) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	JCExpression returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	JCStatement returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generateSingularMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
	
	returnType = chain ? cloneSelfType(builderType) : maker.Type(createVoidType(maker, CTC_VOID));
	returnStatement = chain ? maker.Return(maker.Ident(builderType.toName("this"))) : null;
	generatePluralMethod(maker, returnType, returnStatement, data, builderType, source, fluent);
}
 
Example 5
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private JCTree.JCBlock addReturnBlock(JavacTreeMaker singletonClassTreeMaker, JavacNode holderInnerClass) {

        JCTree.JCClassDecl holderInnerClassDecl = (JCTree.JCClassDecl) holderInnerClass.get();
        JavacTreeMaker holderInnerClassTreeMaker = holderInnerClass.getTreeMaker();
        JCTree.JCIdent holderInnerClassType = holderInnerClassTreeMaker.Ident(holderInnerClassDecl.name);

        JCTree.JCFieldAccess instanceVarAccess = holderInnerClassTreeMaker.Select(holderInnerClassType, holderInnerClass.toName("INSTANCE"));
        JCTree.JCReturn returnValue = singletonClassTreeMaker.Return(instanceVarAccess);

        ListBuffer<JCTree.JCStatement> statements = new ListBuffer<>();
        statements.append(returnValue);

        return singletonClassTreeMaker.Block(0L, statements.toList());
    }
 
Example 6
Source File: HandleSetter.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static JCMethodDecl createSetter(long access, JavacNode field, JavacTreeMaker treeMaker, String setterName, boolean shouldReturnThis, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
	if (setterName == null) return null;
	
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	
	JCExpression fieldRef = createFieldAccessor(treeMaker, field, FieldAccess.ALWAYS_FIELD);
	JCAssign assign = treeMaker.Assign(fieldRef, treeMaker.Ident(fieldDecl.name));
	
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN);
	
	Name methodName = field.toName(setterName);
	List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables);
	
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext());
	JCVariableDecl param = treeMaker.VarDef(treeMaker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null);
	
	if (nonNulls.isEmpty()) {
		statements.append(treeMaker.Exec(assign));
	} else {
		JCStatement nullCheck = generateNullCheck(treeMaker, field, source);
		if (nullCheck != null) statements.append(nullCheck);
		statements.append(treeMaker.Exec(assign));
	}
	
	JCExpression methodType = null;
	if (shouldReturnThis) {
		methodType = cloneSelfType(field);
	}
	
	if (methodType == null) {
		//WARNING: Do not use field.getSymbolTable().voidType - that field has gone through non-backwards compatible API changes within javac1.6.
		methodType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));
		shouldReturnThis = false;
	}
	
	if (shouldReturnThis) {
		JCReturn returnStatement = treeMaker.Return(treeMaker.Ident(field.toName("this")));
		statements.append(returnStatement);
	}
	
	JCBlock methodBody = treeMaker.Block(0, statements.toList());
	List<JCTypeParameter> methodGenericParams = List.nil();
	List<JCVariableDecl> parameters = List.of(param);
	List<JCExpression> throwsClauses = List.nil();
	JCExpression annotationMethodDefaultValue = null;
	
	List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
	if (isFieldDeprecated(field)) {
		annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
	}
	
	JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
			methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext());
	copyJavadoc(field, decl, CopyJavadoc.SETTER);
	return decl;
}
 
Example 7
Source File: HandleToString.java    From EasyMPermission with MIT License 4 votes vote down vote up
static JCMethodDecl createToString(JavacNode typeNode, Collection<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
	JCExpression returnType = genJavaLangTypeRef(typeNode, "String");
	
	boolean first = true;
	
	String typeName = getTypeName(typeNode);
	String infix = ", ";
	String suffix = ")";
	String prefix;
	if (callSuper) {
		prefix = typeName + "(super=";
	} else if (fields.isEmpty()) {
		prefix = typeName + "()";
	} else if (includeFieldNames) {
		prefix = typeName + "(" + ((JCVariableDecl)fields.iterator().next().get()).name.toString() + "=";
	} else {
		prefix = typeName + "(";
	}
	
	JCExpression current = maker.Literal(prefix);
	
	if (callSuper) {
		JCMethodInvocation callToSuper = maker.Apply(List.<JCExpression>nil(),
				maker.Select(maker.Ident(typeNode.toName("super")), typeNode.toName("toString")),
				List.<JCExpression>nil());
		current = maker.Binary(CTC_PLUS, current, callToSuper);
		first = false;
	}
	
	for (JavacNode fieldNode : fields) {
		JCExpression expr;
		
		JCExpression fieldAccessor = createFieldAccessor(maker, fieldNode, fieldAccess);
		
		JCExpression fieldType = getFieldType(fieldNode, fieldAccess);
		
		// The distinction between primitive and object will be useful if we ever add a 'hideNulls' option.
		boolean fieldIsPrimitive = fieldType instanceof JCPrimitiveTypeTree;
		boolean fieldIsPrimitiveArray = fieldType instanceof JCArrayTypeTree && ((JCArrayTypeTree) fieldType).elemtype instanceof JCPrimitiveTypeTree;
		boolean fieldIsObjectArray = !fieldIsPrimitiveArray && fieldType instanceof JCArrayTypeTree;
		@SuppressWarnings("unused")
		boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray;
		
		if (fieldIsPrimitiveArray || fieldIsObjectArray) {
			JCExpression tsMethod = chainDots(typeNode, "java", "util", "Arrays", fieldIsObjectArray ? "deepToString" : "toString");
			expr = maker.Apply(List.<JCExpression>nil(), tsMethod, List.<JCExpression>of(fieldAccessor));
		} else expr = fieldAccessor;
		
		if (first) {
			current = maker.Binary(CTC_PLUS, current, expr);
			first = false;
			continue;
		}
		
		if (includeFieldNames) {
			current = maker.Binary(CTC_PLUS, current, maker.Literal(infix + fieldNode.getName() + "="));
		} else {
			current = maker.Binary(CTC_PLUS, current, maker.Literal(infix));
		}
		
		current = maker.Binary(CTC_PLUS, current, expr);
	}
	
	if (!first) current = maker.Binary(CTC_PLUS, current, maker.Literal(suffix));
	
	JCStatement returnStatement = maker.Return(current);
	
	JCBlock body = maker.Block(0, List.of(returnStatement));
	
	return recursiveSetGeneratedBy(maker.MethodDef(mods, typeNode.toName("toString"), returnType,
			List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
 
Example 8
Source File: HandleWither.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCMethodDecl createWither(long access, JavacNode field, JavacTreeMaker maker, JavacNode source, List<JCAnnotation> onMethod, List<JCAnnotation> onParam) {
	String witherName = toWitherName(field);
	if (witherName == null) return null;
	
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	List<JCAnnotation> nonNulls = findAnnotations(field, NON_NULL_PATTERN);
	List<JCAnnotation> nullables = findAnnotations(field, NULLABLE_PATTERN);
	
	Name methodName = field.toName(witherName);
	List<JCAnnotation> annsOnParam = copyAnnotations(onParam).appendList(nonNulls).appendList(nullables);
	
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, field.getContext());
	JCVariableDecl param = maker.VarDef(maker.Modifiers(flags, annsOnParam), fieldDecl.name, fieldDecl.vartype, null);
	
	JCExpression selfType = cloneSelfType(field);
	if (selfType == null) return null;
	
	ListBuffer<JCExpression> args = new ListBuffer<JCExpression>();
	for (JavacNode child : field.up().down()) {
		if (child.getKind() != Kind.FIELD) continue;
		JCVariableDecl childDecl = (JCVariableDecl) child.get();
		// Skip fields that start with $
		if (childDecl.name.toString().startsWith("$")) continue;
		long fieldFlags = childDecl.mods.flags;
		// Skip static fields.
		if ((fieldFlags & Flags.STATIC) != 0) continue;
		// Skip initialized final fields.
		if (((fieldFlags & Flags.FINAL) != 0) && childDecl.init != null) continue;
		if (child.get() == field.get()) {
			args.append(maker.Ident(fieldDecl.name));
		} else {
			args.append(createFieldAccessor(maker, child, FieldAccess.ALWAYS_FIELD));
		}
	}
	
	JCNewClass newClass = maker.NewClass(null, List.<JCExpression>nil(), selfType, args.toList(), null);
	JCExpression identityCheck = maker.Binary(CTC_EQUAL, createFieldAccessor(maker, field, FieldAccess.ALWAYS_FIELD), maker.Ident(fieldDecl.name));
	JCConditional conditional = maker.Conditional(identityCheck, maker.Ident(field.toName("this")), newClass);
	JCReturn returnStatement = maker.Return(conditional);
	
	if (nonNulls.isEmpty()) {
		statements.append(returnStatement);
	} else {
		JCStatement nullCheck = generateNullCheck(maker, field, source);
		if (nullCheck != null) statements.append(nullCheck);
		statements.append(returnStatement);
	}
	
	JCExpression returnType = cloneSelfType(field);
	
	JCBlock methodBody = maker.Block(0, statements.toList());
	List<JCTypeParameter> methodGenericParams = List.nil();
	List<JCVariableDecl> parameters = List.of(param);
	List<JCExpression> throwsClauses = List.nil();
	JCExpression annotationMethodDefaultValue = null;
	
	List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
	
	if (isFieldDeprecated(field)) {
		annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
	}
	JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType,
			methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source.get(), field.getContext());
	copyJavadoc(field, decl, CopyJavadoc.WITHER);
	return decl;
}
 
Example 9
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCStatement returnBool(JavacTreeMaker maker, boolean bool) {
	return maker.Return(maker.Literal(CTC_BOOLEAN, bool ? 1 : 0));
}
 
Example 10
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 4 votes vote down vote up
private JCMethodDecl createOnRequestPermissionMethod(JavacNode typeNode, List<PermissionAnnotatedItem> permissionList) {
    JavacTreeMaker treeMaker = typeNode.getTreeMaker();

    ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();

    JCTree.JCExpression returnType = treeMaker.Type(Javac.createVoidType(treeMaker, CTC_VOID));

    List<JCVariableDecl> paramList = List.of(
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("requestCode")
                .type(treeMaker.TypeIdent(CTC_INT))
                .value(null)
                .build(),
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("permissions")
                .type(treeMaker.TypeArray(genJavaLangTypeRef(typeNode, "String")))
                .value(null)
                .build(),
        Variable(typeNode)
                .modifiers(Flags.PARAMETER)
                .name("grantResults")
                .type(treeMaker.TypeArray(treeMaker.TypeIdent(CTC_INT)))
                .value(null)
                .build()
    );

    for (PermissionAnnotatedItem item : permissionList) {

        JCReturn jcReturn = treeMaker.Return(null);

        JCBinary cmpRequestCode = treeMaker.Binary(CTC_EQUAL,
                treeMaker.Ident(typeNode.toName("requestCode")),
                treeMaker.Literal(CTC_INT, item.getRequestCode()));

        JCBinary cmpGrantResult = treeMaker.Binary(CTC_NOT_EQUAL,
                treeMaker.Indexed(treeMaker.Ident(typeNode.toName("grantResults")), treeMaker.Literal(CTC_INT, 0)),
                JavacHandlerUtil.chainDots(typeNode, "android", "content", "pm", "PackageManager", "PERMISSION_GRANTED"));

        JCExpression toastMethod =
                JavacHandlerUtil.chainDots(typeNode, "android", "widget", "Toast", "makeText");
        List<JCExpression> toastArgs = List.<JCTree.JCExpression>of(
                treeMaker.Ident(typeNode.toName("this")),
                treeMaker.Literal(MESSAGE_PERMISSIONS_WERE_NOT_GRANTED),
                treeMaker.Literal(CTC_INT, 1));
        JCMethodInvocation printlnInvocation =
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs);
        JCExpressionStatement thenPart = treeMaker.Exec(
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil()));

        toastArgs = List.<JCTree.JCExpression>of(
                treeMaker.Ident(typeNode.toName("this")),
                treeMaker.Literal(MESSAGE_PERMISSIONS_HAVE_BEEN_GRANTED),
                treeMaker.Literal(CTC_INT, 1));
        printlnInvocation =
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), toastMethod, toastArgs);
        JCExpressionStatement elsePart = treeMaker.Exec(
                treeMaker.Apply(List.<JCTree.JCExpression>nil(), treeMaker.Select(printlnInvocation, typeNode.toName("show")), List.<JCExpression>nil()));

        JCIf jcIfGrantResult = If(typeNode)
                .condition(cmpGrantResult)
                .withThen(Block(typeNode).last(thenPart).build())
                .withElse(Block(typeNode).last(elsePart).build())
                .build();

        JCIf jcIfRequestCode = If(typeNode)
                .condition(cmpRequestCode)
                .onlyThen(Block(typeNode).add(jcIfGrantResult).last(jcReturn).build())
                .build();

        statements.append(jcIfRequestCode);
    }

    JCBlock body = Block(typeNode)
            .last(statements.toList())
            .build();

    return Method(typeNode)
            .modifiers(Flags.PUBLIC)
            .returnType(returnType)
            .name("onRequestPermissionsResult")
            .paramType()
            .parameters(paramList)
            .thrown()
            .body(body)
            .build();
}