Java Code Examples for lombok.javac.JavacTreeMaker#Select

The following examples show how to use lombok.javac.JavacTreeMaker#Select . 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: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCExpression createTypeReference(JavacNode type) {
	java.util.List<String> list = new ArrayList<String>();
	list.add(type.getName());
	JavacNode tNode = type.up();
	while (tNode != null && tNode.getKind() == Kind.TYPE) {
		list.add(tNode.getName());
		tNode = tNode.up();
	}
	Collections.reverse(list);
	
	JavacTreeMaker maker = type.getTreeMaker();
	JCExpression chain = maker.Ident(type.toName(list.get(0)));
	
	for (int i = 1; i < list.size(); i++) {
		chain = maker.Select(chain, type.toName(list.get(i)));
	}
	
	return chain;
}
 
Example 2
Source File: JavacJavaUtilListSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
private List<JCStatement> createListCopy(JavacTreeMaker maker, SingularData data, JavacNode builderType, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	Name thisName = builderType.toName("this");
	
	JCExpression argToUnmodifiable; {
		 // new java.util.ArrayList<Generics>(this.pluralName);
		List<JCExpression> constructorArgs = List.nil();
		JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
		constructorArgs = List.<JCExpression>of(thisDotPluralName);
		JCExpression targetTypeExpr = chainDots(builderType, "java", "util", "ArrayList");
		targetTypeExpr = addTypeArgs(1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
		argToUnmodifiable = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
	}
	
	JCStatement unmodifiableStat; {
		// pluralname = Collections.unmodifiableInterfaceType(-newlist-);
		JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiableList"), List.of(argToUnmodifiable));
		unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
	}
	
	return List.of(unmodifiableStat);
}
 
Example 3
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
static JCExpression createFieldAccessor(JavacTreeMaker maker, JavacNode field, FieldAccess fieldAccess, JCExpression receiver) {
	boolean lookForGetter = lookForGetter(field, fieldAccess);
	
	GetterMethod getter = lookForGetter ? findGetter(field) : null;
	JCVariableDecl fieldDecl = (JCVariableDecl) field.get();
	
	if (getter == null) {
		if (receiver == null) {
			if ((fieldDecl.mods.flags & Flags.STATIC) == 0) {
				receiver = maker.Ident(field.toName("this"));
			} else {
				JavacNode containerNode = field.up();
				if (containerNode != null && containerNode.get() instanceof JCClassDecl) {
					JCClassDecl container = (JCClassDecl) field.up().get();
					receiver = maker.Ident(container.name);
				}
			}
		}
		
		return receiver == null ? maker.Ident(fieldDecl.name) : maker.Select(receiver, fieldDecl.name);
	}
	
	if (receiver == null) receiver = maker.Ident(field.toName("this"));
	JCMethodInvocation call = maker.Apply(List.<JCExpression>nil(),
			maker.Select(receiver, getter.name), List.<JCExpression>nil());
	return call;
}
 
Example 4
Source File: JavacSingularsRecipes.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** Generates 'this.<em>name</em>.size()' as an expression; if nullGuard is true, it's this.name == null ? 0 : this.name.size(). */
protected JCExpression getSize(JavacTreeMaker maker, JavacNode builderType, Name name, boolean nullGuard) {
	Name thisName = builderType.toName("this");
	JCExpression fn = maker.Select(maker.Select(maker.Ident(thisName), name), builderType.toName("size"));
	JCExpression sizeInvoke = maker.Apply(List.<JCExpression>nil(), fn, List.<JCExpression>nil());
	if (nullGuard) {
		JCExpression isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(thisName), name), maker.Literal(CTC_BOT, 0));
		return maker.Conditional(isNull, maker.Literal(CTC_INT, 0), sizeInvoke);
	}
	return sizeInvoke;
}
 
Example 5
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression thisDotField2 = maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName());
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	
	JCExpression create = maker.Apply(jceBlank, chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), getBuilderMethodName(data)), jceBlank);
	JCStatement thenPart = maker.Exec(maker.Assign(thisDotField2, create));
	
	return maker.If(cond, thenPart, null);
}
 
Example 6
Source File: JavacJavaUtilSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected JCStatement createConstructBuilderVarIfNeeded(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, JCTree source) {
	List<JCExpression> jceBlank = List.nil();

	Name v1Name = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName();
	Name v2Name = mapMode ? builderType.toName(data.getPluralName() + "$value") : null;
	JCExpression thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name);
	JCExpression cond = maker.Binary(CTC_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
	thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v1Name);
	JCExpression v1Type = chainDots(builderType, "java", "util", "ArrayList");
	v1Type = addTypeArgs(1, false, builderType, v1Type, data.getTypeArgs(), source);
	JCExpression constructArrayList = maker.NewClass(null, jceBlank, v1Type, jceBlank, null);
	JCStatement initV1 = maker.Exec(maker.Assign(thisDotField, constructArrayList));
	JCStatement thenPart;
	if (mapMode) {
		thisDotField = maker.Select(maker.Ident(builderType.toName("this")), v2Name);
		JCExpression v2Type = chainDots(builderType, "java", "util", "ArrayList");
		List<JCExpression> tArgs = data.getTypeArgs();
		if (tArgs != null && tArgs.tail != null) tArgs = tArgs.tail;
		else tArgs = List.nil();
		v2Type = addTypeArgs(1, false, builderType, v2Type, tArgs, source);
		constructArrayList = maker.NewClass(null, jceBlank, v2Type, jceBlank, null);
		JCStatement initV2 = maker.Exec(maker.Assign(thisDotField, constructArrayList));
		thenPart = maker.Block(0, List.of(initV1, initV2));
	} else {
		thenPart = initV1;
	}
	return maker.If(cond, thenPart, null);
}
 
Example 7
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 8
Source File: HandleLog.java    From EasyMPermission with MIT License 4 votes vote down vote up
public static JCFieldAccess selfType(JavacNode typeNode) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	Name name = ((JCClassDecl) typeNode.get()).name;
	return maker.Select(maker.Ident(name), typeNode.toName("class"));
}
 
Example 9
Source File: HandleLog.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public JCExpression createFactoryParameter(JavacNode typeNode, JCFieldAccess loggingType) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	JCExpression method = maker.Select(loggingType, typeNode.toName("getName"));
	return maker.Apply(List.<JCExpression>nil(), method, List.<JCExpression>nil());
}
 
Example 10
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 4 votes vote down vote up
private static JCExpression cloneType0(JavacTreeMaker maker, JCTree in) {
	if (in == null) return null;
	
	if (in instanceof JCPrimitiveTypeTree) return (JCExpression) in;
	
	if (in instanceof JCIdent) {
		return maker.Ident(((JCIdent) in).name);
	}
	
	if (in instanceof JCFieldAccess) {
		JCFieldAccess fa = (JCFieldAccess) in;
		return maker.Select(cloneType0(maker, fa.selected), fa.name);
	}
	
	if (in instanceof JCArrayTypeTree) {
		JCArrayTypeTree att = (JCArrayTypeTree) in;
		return maker.TypeArray(cloneType0(maker, att.elemtype));
	}
	
	if (in instanceof JCTypeApply) {
		JCTypeApply ta = (JCTypeApply) in;
		ListBuffer<JCExpression> lb = new ListBuffer<JCExpression>();
		for (JCExpression typeArg : ta.arguments) {
			lb.append(cloneType0(maker, typeArg));
		}
		return maker.TypeApply(cloneType0(maker, ta.clazz), lb.toList());
	}
	
	if (in instanceof JCWildcard) {
		JCWildcard w = (JCWildcard) in;
		JCExpression newInner = cloneType0(maker, w.inner);
		TypeBoundKind newKind;
		switch (w.getKind()) {
		case SUPER_WILDCARD:
			newKind = maker.TypeBoundKind(BoundKind.SUPER);
			break;
		case EXTENDS_WILDCARD:
			newKind = maker.TypeBoundKind(BoundKind.EXTENDS);
			break;
		default:
		case UNBOUNDED_WILDCARD:
			newKind = maker.TypeBoundKind(BoundKind.UNBOUND);
			break;
		}
		return maker.Wildcard(newKind, newInner);
	}
	
	// This is somewhat unsafe, but it's better than outright throwing an exception here. Returning null will just cause an exception down the pipeline.
	return (JCExpression) in;
}
 
Example 11
Source File: HandleDelegate.java    From EasyMPermission with MIT License 4 votes vote down vote up
public JCExpression get(final JavacNode node, final Name name) {
	final JavacTreeMaker maker = node.getTreeMaker();
	return maker.Select(maker.Ident(node.toName("this")), name);
}
 
Example 12
Source File: HandleCleanup.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");
	
	if (inNetbeansEditor(annotationNode)) return;
	
	deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
	String cleanupName = annotation.getInstance().value();
	if (cleanupName.length() == 0) {
		annotationNode.addError("cleanupName cannot be the empty string.");
		return;
	}
	
	if (annotationNode.up().getKind() != Kind.LOCAL) {
		annotationNode.addError("@Cleanup is legal only on local variable declarations.");
		return;
	}
	
	JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get();
	
	if (decl.init == null) {
		annotationNode.addError("@Cleanup variable declarations need to be initialized.");
		return;
	}
	
	JavacNode ancestor = annotationNode.up().directUp();
	JCTree blockNode = ancestor.get();
	
	final List<JCStatement> statements;
	if (blockNode instanceof JCBlock) {
		statements = ((JCBlock)blockNode).stats;
	} else if (blockNode instanceof JCCase) {
		statements = ((JCCase)blockNode).stats;
	} else if (blockNode instanceof JCMethodDecl) {
		statements = ((JCMethodDecl)blockNode).body.stats;
	} else {
		annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
		return;
	}
	
	boolean seenDeclaration = false;
	ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>();
	ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>();
	for (JCStatement statement : statements) {
		if (!seenDeclaration) {
			if (statement == decl) seenDeclaration = true;
			newStatements.append(statement);
		} else {
			tryBlock.append(statement);
		}
	}
	
	if (!seenDeclaration) {
		annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
		return;
	}
	doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);
	
	JavacTreeMaker maker = annotationNode.getTreeMaker();
	JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
	List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(
			maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));
	
	JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
	JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));
	
	JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);
	
	Context context = annotationNode.getContext();
	JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast, context);
	
	newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.<JCCatch>nil(), finalizer), ast, context));
	
	if (blockNode instanceof JCBlock) {
		((JCBlock)blockNode).stats = newStatements.toList();
	} else if (blockNode instanceof JCCase) {
		((JCCase)blockNode).stats = newStatements.toList();
	} else if (blockNode instanceof JCMethodDecl) {
		((JCMethodDecl)blockNode).body.stats = newStatements.toList();
	} else throw new AssertionError("Should not get here");
	
	ancestor.rebuild();
}
 
Example 13
Source File: HandleSynchronized.java    From EasyMPermission with MIT License 4 votes vote down vote up
@Override public void handle(AnnotationValues<Synchronized> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.SYNCHRONIZED_FLAG_USAGE, "@Synchronized");
	
	if (inNetbeansEditor(annotationNode)) return;
	
	deleteAnnotationIfNeccessary(annotationNode, Synchronized.class);
	JavacNode methodNode = annotationNode.up();
	
	if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof JCMethodDecl)) {
		annotationNode.addError("@Synchronized is legal only on methods.");
		
		return;
	}
	
	JCMethodDecl method = (JCMethodDecl)methodNode.get();
	
	if ((method.mods.flags & Flags.ABSTRACT) != 0) {
		annotationNode.addError("@Synchronized is legal only on concrete methods.");
		
		return;
	}
	boolean isStatic = (method.mods.flags & Flags.STATIC) != 0;
	String lockName = annotation.getInstance().value();
	boolean autoMake = false;
	if (lockName.length() == 0) {
		autoMake = true;
		lockName = isStatic ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME;
	}
	
	JavacTreeMaker maker = methodNode.getTreeMaker().at(ast.pos);
	Context context = methodNode.getContext();
	
	if (fieldExists(lockName, methodNode) == MemberExistsResult.NOT_EXISTS) {
		if (!autoMake) {
			annotationNode.addError("The field " + lockName + " does not exist.");
			return;
		}
		JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object");
		//We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
		JCNewArray newObjectArray = maker.NewArray(genJavaLangTypeRef(methodNode, ast.pos, "Object"),
				List.<JCExpression>of(maker.Literal(CTC_INT, 0)), null);
		JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
				maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (isStatic ? Flags.STATIC : 0)),
				methodNode.toName(lockName), objectType, newObjectArray), ast, context);
		injectFieldAndMarkGenerated(methodNode.up(), fieldDecl);
	}
	
	if (method.body == null) return;
	
	JCExpression lockNode;
	if (isStatic) {
		lockNode = chainDots(methodNode, ast.pos, methodNode.up().getName(), lockName);
	} else {
		lockNode = maker.Select(maker.Ident(methodNode.toName("this")), methodNode.toName(lockName));
	}
	
	recursiveSetGeneratedBy(lockNode, ast, context);
	method.body = setGeneratedBy(maker.Block(0, List.<JCStatement>of(setGeneratedBy(maker.Synchronized(lockNode, method.body), ast, context))), ast, context);
	
	methodNode.rebuild();
}
 
Example 14
Source File: JavacJavaUtilSingularizer.java    From EasyMPermission with MIT License 4 votes vote down vote up
protected List<JCStatement> createJavaUtilSimpleCreationAndFillStatements(JavacTreeMaker maker, SingularData data, JavacNode builderType, boolean mapMode, boolean defineVar, boolean addInitialCapacityArg, boolean nullGuard, String targetType, JCTree source) {
	List<JCExpression> jceBlank = List.nil();
	Name thisName = builderType.toName("this");
	
	JCStatement createStat; {
		 // pluralName = new java.util.TargetType(initialCap);
		List<JCExpression> constructorArgs = List.nil();
		if (addInitialCapacityArg) {
			Name varName = mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName();
			// this.varName.size() < MAX_POWER_OF_2 ? 1 + this.varName.size() + (this.varName.size() - 3) / 3 : Integer.MAX_VALUE;
			// lessThanCutOff = this.varName.size() < MAX_POWER_OF_2
			JCExpression lessThanCutoff = maker.Binary(CTC_LESS_THAN, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 0x40000000));
			JCExpression integerMaxValue = genJavaLangTypeRef(builderType, "Integer", "MAX_VALUE");
			JCExpression sizeFormulaLeft = maker.Binary(CTC_PLUS, maker.Literal(CTC_INT, 1), getSize(maker, builderType, varName, nullGuard));
			JCExpression sizeFormulaRightLeft = maker.Binary(CTC_MINUS, getSize(maker, builderType, varName, nullGuard), maker.Literal(CTC_INT, 3));
			JCExpression sizeFormulaRight = maker.Binary(CTC_DIV, sizeFormulaRightLeft, maker.Literal(CTC_INT, 3));
			JCExpression sizeFormula = maker.Binary(CTC_PLUS, sizeFormulaLeft, sizeFormulaRight);
			constructorArgs = List.<JCExpression>of(maker.Conditional(lessThanCutoff, sizeFormula, integerMaxValue));
		}
		
		JCExpression targetTypeExpr = chainDots(builderType, "java", "util", targetType);
		targetTypeExpr = addTypeArgs(mapMode ? 2 : 1, false, builderType, targetTypeExpr, data.getTypeArgs(), source);
		JCExpression constructorCall = maker.NewClass(null, jceBlank, targetTypeExpr, constructorArgs, null);
		if (defineVar) {
			JCExpression localShadowerType = chainDotsString(builderType, data.getTargetFqn());
			localShadowerType = addTypeArgs(mapMode ? 2 : 1, false, builderType, localShadowerType, data.getTypeArgs(), source);
			createStat = maker.VarDef(maker.Modifiers(0), data.getPluralName(), localShadowerType, constructorCall);
		} else {
			createStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), constructorCall));
		}
	}
	
	JCStatement fillStat; {
		if (mapMode) {
			// for (int $i = 0; $i < this.pluralname$key.size(); i++) pluralname.put(this.pluralname$key.get($i), this.pluralname$value.get($i));
			Name ivar = builderType.toName("$i");
			Name keyVarName = builderType.toName(data.getPluralName() + "$key");
			JCExpression pluralnameDotPut = maker.Select(maker.Ident(data.getPluralName()), builderType.toName("put"));
			JCExpression arg1 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$key", "get"), List.<JCExpression>of(maker.Ident(ivar)));
			JCExpression arg2 = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName() + "$value", "get"), List.<JCExpression>of(maker.Ident(ivar)));
			JCStatement putStatement = maker.Exec(maker.Apply(jceBlank, pluralnameDotPut, List.of(arg1, arg2)));
			JCStatement forInit = maker.VarDef(maker.Modifiers(0), ivar, maker.TypeIdent(CTC_INT), maker.Literal(CTC_INT, 0));
			JCExpression checkExpr = maker.Binary(CTC_LESS_THAN, maker.Ident(ivar), getSize(maker, builderType, keyVarName, nullGuard));
			JCExpression incrementExpr = maker.Unary(CTC_POSTINC, maker.Ident(ivar));
			fillStat = maker.ForLoop(List.of(forInit), checkExpr, List.of(maker.Exec(incrementExpr)), putStatement);
		} else {
			// pluralname.addAll(this.pluralname);
			JCExpression thisDotPluralName = maker.Select(maker.Ident(thisName), data.getPluralName());
			fillStat = maker.Exec(maker.Apply(jceBlank, maker.Select(maker.Ident(data.getPluralName()), builderType.toName("addAll")), List.of(thisDotPluralName)));
		}
		if (nullGuard) {
			JCExpression thisDotField = maker.Select(maker.Ident(thisName), mapMode ? builderType.toName(data.getPluralName() + "$key") : data.getPluralName());
			JCExpression nullCheck = maker.Binary(CTC_NOT_EQUAL, thisDotField, maker.Literal(CTC_BOT, null));
			fillStat = maker.If(nullCheck, fillStat, null);
		}
	}
	JCStatement unmodifiableStat; {
		// pluralname = Collections.unmodifiableInterfaceType(pluralname);
		JCExpression arg = maker.Ident(data.getPluralName());
		JCExpression invoke = maker.Apply(jceBlank, chainDots(builderType, "java", "util", "Collections", "unmodifiable" + data.getTargetSimpleType()), List.of(arg));
		unmodifiableStat = maker.Exec(maker.Assign(maker.Ident(data.getPluralName()), invoke));
	}
	
	return List.of(createStat, fillStat, unmodifiableStat);
}