lombok.javac.JavacTreeMaker Java Examples

The following examples show how to use lombok.javac.JavacTreeMaker. 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: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(AnnotationValues<Table> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {
  if (environment.isProcessingFailed()) {
    return;
  }
  Table tableInstance = annotation.getInstance();

  deleteAnnotationIfNeccessary(annotationNode, Table.class);
  deleteImportFromCompilationUnit(annotationNode, Table.class.getCanonicalName());

  JavacNode tableNode = annotationNode.up();
  final JavacTreeMaker maker = tableNode.getTreeMaker();

  final String tableName = getTableName(tableInstance, tableNode);
  final TableElement tableElement = environment.getTableElementByTableName(tableName);
  generateMagicMethods(maker, tableNode);
  generateMissingIdIfNeeded(maker, tableNode, tableElement);
}
 
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: HandleLog.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static boolean createField(LoggingFramework framework, JavacNode typeNode, JCFieldAccess loggingType, JCTree source, String logFieldName, boolean useStatic, String loggerTopic) {
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	// private static final <loggerType> log = <factoryMethod>(<parameter>);
	JCExpression loggerType = chainDotsString(typeNode, framework.getLoggerTypeName());
	JCExpression factoryMethod = chainDotsString(typeNode, framework.getLoggerFactoryMethodName());

	JCExpression loggerName;
	if (loggerTopic == null || loggerTopic.trim().length() == 0) {
		loggerName = framework.createFactoryParameter(typeNode, loggingType);
	} else {
		loggerName = maker.Literal(loggerTopic);
	}

	JCMethodInvocation factoryMethodCall = maker.Apply(List.<JCExpression>nil(), factoryMethod, List.<JCExpression>of(loggerName));

	JCVariableDecl fieldDecl = recursiveSetGeneratedBy(maker.VarDef(
			maker.Modifiers(Flags.PRIVATE | Flags.FINAL | (useStatic ? Flags.STATIC : 0)),
			typeNode.toName(logFieldName), loggerType, factoryMethodCall), source, typeNode.getContext());
	
	injectFieldAndMarkGenerated(typeNode, fieldDecl);
	return true;
}
 
Example #4
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateDeleteTable(JavacTreeMaker maker, JavacNode tableElement, Set<String> allStaticMethodNames, String tableClassName) {
  final String callClassName = CLASS_DELETE_TABLE;
  final String methodName = METHOD_DELETE_TABLE;
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allStaticMethodNames.contains(methodName)) {
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(maker.Literal(invokeKey)));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_STATIC, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.<JCTree.JCVariableDecl>nil(),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example #5
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateBulkMethod(JavacTreeMaker maker, JavacNode tableElement,
                                Set<String> allStaticMethodNames, String methodName,
                                String callClassName, String tableClassName,
                                CollectionType collectionType) {
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allStaticMethodNames.contains(methodName)) {
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(maker.Literal(invokeKey)));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_STATIC, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCExpression tableClassType = chainDotsString(tableElement, tableElement.getPackageDeclaration() + "." + tableClassName);
    final JCTree.JCExpression paramType = maker.TypeApply(collectionType.genericType(tableElement), List.of(tableClassType));
    long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, tableElement.getContext());
    final JCTree.JCVariableDecl param = maker.VarDef(maker.Modifiers(flags), tableElement.toName("o"), paramType, null);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.of(param),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example #6
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private void generateMethod(JavacTreeMaker maker, JavacNode tableElement, Set<String> allMethodNames, String methodName, String callClassName, String tableClassName) {
  final String invokeKey = getCreateInvokeKey(callClassName, tableClassName);
  if (!allMethodNames.contains(methodName)) {
    final JCTree.JCAssign value = maker.Assign(maker.Ident(tableElement.toName("value")),
        maker.Literal(invokeKey));
    final JCTree.JCAssign useThisAsOnlyParam = maker.Assign(maker.Ident(tableElement.toName("useThisAsOnlyParam")),
        maker.Literal(true));
    final JCTree.JCAnnotation invokesAnnotation = maker.Annotation(chainDotsString(tableElement, Invokes.class.getCanonicalName()),
        List.<JCTree.JCExpression>of(value, useThisAsOnlyParam));
    final JCTree.JCModifiers mods = maker.Modifiers(PUBLIC_FINAL, List.of(invokesAnnotation));
    final Name name = tableElement.toName(methodName);
    final JCTree.JCExpression returnType = getMagicMethodReturnType(tableElement, callClassName, tableClassName);
    final JCTree.JCBlock body = defaultMagicMethodBody(maker, tableElement);
    final JCTree.JCMethodDecl method = maker.MethodDef(mods, name, returnType,
        List.<JCTree.JCTypeParameter>nil(),
        List.<JCTree.JCVariableDecl>nil(),
        List.<JCTree.JCExpression>nil(),
        body,
        null);
    injectMethod(tableElement, recursiveSetGeneratedBy(method, tableElement.get(), tableElement.getContext()));
  }
}
 
Example #7
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "addAll");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getPluralName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getPluralName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("addAll", name.toString()));
	JCExpression paramType = chainDots(builderType, "java", "util", "Collection");
	paramType = addTypeArgs(1, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #8
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static JCExpression cloneSelfType(JavacNode childOfType) {
	JavacNode typeNode = childOfType;
	JavacTreeMaker maker = childOfType.getTreeMaker();
	while (typeNode != null && typeNode.getKind() != Kind.TYPE) typeNode = typeNode.up();
	if (typeNode != null && typeNode.get() instanceof JCClassDecl) {
		JCClassDecl type = (JCClassDecl) typeNode.get();
		ListBuffer<JCExpression> typeArgs = new ListBuffer<JCExpression>();
		if (!type.typarams.isEmpty()) {
			for (JCTypeParameter tp : type.typarams) {
				typeArgs.append(maker.Ident(tp.name));
			}
			return maker.TypeApply(maker.Ident(type.name), typeArgs.toList());
		} else {
			return maker.Ident(type.name);
		}
	} else {
		return null;
	}
}
 
Example #9
Source File: JavacJavaUtilListSetSingularizer.java    From EasyMPermission with MIT License 6 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, false, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), "add");
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, List.<JCExpression>of(maker.Ident(data.getSingularName())));
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name name = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) name = builderType.toName(HandlerUtil.buildAccessorName("add", name.toString()));
	JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, name, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #10
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 #11
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 #12
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
	JavacTreeMaker maker = node.getTreeMaker();
	
	Context context = node.getContext();
	JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
	JCExpression varType = chainDots(node, exception.split("\\."));
	
	JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
	JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
	JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(
			List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef,
			List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
	JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
	if (JavacHandlerUtil.inNetbeansEditor(node)) {
		//set span (start and end position) of the try statement and the main block
		//this allows NetBeans to dive into the statement correctly:
		JCCompilationUnit top = (JCCompilationUnit) node.top().get();
		int startPos = contents.head.pos;
		int endPos = Javac.getEndPosition(contents.last().pos(), top);
		tryBlock.pos = startPos;
		tryStatement.pos = startPos;
		Javac.storeEnd(tryBlock, endPos, top);
		Javac.storeEnd(tryStatement, endPos, top);
	}
	return setGeneratedBy(tryStatement, source, context);
}
 
Example #13
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 6 votes vote down vote up
public JCMethodDecl createCanEqual(JavacNode typeNode, JCTree source, List<JCAnnotation> onParam) {
	/* public boolean canEqual(final java.lang.Object other) {
	 *     return other instanceof Outer.Inner.MyType;
	 * }
	 */
	JavacTreeMaker maker = typeNode.getTreeMaker();
	
	JCModifiers mods = maker.Modifiers(Flags.PROTECTED, List.<JCAnnotation>nil());
	JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
	Name canEqualName = typeNode.toName("canEqual");
	JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
	Name otherName = typeNode.toName("other");
	long flags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, typeNode.getContext());
	List<JCVariableDecl> params = List.of(maker.VarDef(maker.Modifiers(flags, onParam), otherName, objectType, null));
	
	JCBlock body = maker.Block(0, List.<JCStatement>of(
			maker.Return(maker.TypeTest(maker.Ident(otherName), createTypeReference(typeNode)))));
	
	return recursiveSetGeneratedBy(maker.MethodDef(mods, canEqualName, returnType, List.<JCTypeParameter>nil(), params, List.<JCExpression>nil(), body, null), source, typeNode.getContext());
}
 
Example #14
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 #15
Source File: JavacSingularsRecipes.java    From EasyMPermission with MIT License 6 votes vote down vote up
protected JCExpression cloneParamType(int index, JavacTreeMaker maker, List<JCExpression> typeArgs, JavacNode builderType, JCTree source) {
	if (typeArgs == null || typeArgs.size() <= index) {
		return genJavaLangTypeRef(builderType, "Object");
	} else {
		JCExpression originalType = typeArgs.get(index);
		if (originalType.getKind() == Kind.UNBOUNDED_WILDCARD || originalType.getKind() == Kind.SUPER_WILDCARD) {
			return genJavaLangTypeRef(builderType, "Object");
		} else if (originalType.getKind() == Kind.EXTENDS_WILDCARD) {
			try {
				return cloneType(maker, (JCExpression) ((JCWildcard) originalType).inner, source, builderType.getContext());
			} catch (Exception e) {
				return genJavaLangTypeRef(builderType, "Object");
			}
		} else {
			return cloneType(maker, originalType, source, builderType.getContext());
		}
	}
}
 
Example #16
Source File: HandleBuilder.java    From EasyMPermission with MIT License 6 votes vote down vote up
private JCMethodDecl generateCleanMethod(java.util.List<BuilderFieldData> builderFields, JavacNode type, JCTree source) {
	JavacTreeMaker maker = type.getTreeMaker();
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	
	for (BuilderFieldData bfd : builderFields) {
		if (bfd.singularData != null && bfd.singularData.getSingularizer() != null) {
			bfd.singularData.getSingularizer().appendCleaningCode(bfd.singularData, type, source, statements);
		}
	}
	
	statements.append(maker.Exec(maker.Assign(maker.Select(maker.Ident(type.toName("this")), type.toName("$lombokUnclean")), maker.Literal(CTC_BOOLEAN, false))));
	JCBlock body = maker.Block(0, statements.toList());
	return maker.MethodDef(maker.Modifiers(Flags.PUBLIC), type.toName("$lombokClean"), maker.Type(Javac.createVoidType(maker, CTC_VOID)), List.<JCTypeParameter>nil(), List.<JCVariableDecl>nil(), List.<JCExpression>nil(), body, 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;
	}

	 */
}
 
Example #17
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
protected void generatePluralMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAddAll = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "putAll" : "addAll");
	JCExpression invokeAddAll = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAddAll, List.<JCExpression>of(maker.Ident(data.getPluralName())));
	statements.append(maker.Exec(invokeAddAll));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getPluralName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "putAll" : "addAll", methodName.toString()));
	JCExpression paramType;
	if (mapMode) {
		paramType = chainDots(builderType, "java", "util", "Map");
	} else {
		paramType = genJavaLangTypeRef(builderType, "Iterable");
	}
	paramType = addTypeArgs(mapMode ? 2 : 1, true, builderType, paramType, data.getTypeArgs(), source);
	JCVariableDecl param = maker.VarDef(maker.Modifiers(paramFlags), data.getPluralName(), paramType, null);
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, List.of(param), thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #18
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
void generateSingularMethod(JavacTreeMaker maker, JCExpression returnType, JCStatement returnStatement, SingularData data, JavacNode builderType, JCTree source, boolean fluent) {
	List<JCTypeParameter> typeParams = List.nil();
	List<JCExpression> thrown = List.nil();
	boolean mapMode = isMap();
	
	Name keyName = !mapMode ? data.getSingularName() : builderType.toName(data.getSingularName() + "$key");
	Name valueName = !mapMode ? null : builderType.toName(data.getSingularName() + "$value");
	
	JCModifiers mods = maker.Modifiers(Flags.PUBLIC);
	ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
	statements.append(createConstructBuilderVarIfNeeded(maker, data, builderType, mapMode, source));
	JCExpression thisDotFieldDotAdd = chainDots(builderType, "this", data.getPluralName().toString(), mapMode ? "put" : "add");
	List<JCExpression> invokeAddExpr;
	if (mapMode) {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName), maker.Ident(valueName));
	} else {
		invokeAddExpr = List.<JCExpression>of(maker.Ident(keyName));
	}
	JCExpression invokeAdd = maker.Apply(List.<JCExpression>nil(), thisDotFieldDotAdd, invokeAddExpr);
	statements.append(maker.Exec(invokeAdd));
	if (returnStatement != null) statements.append(returnStatement);
	JCBlock body = maker.Block(0, statements.toList());
	Name methodName = data.getSingularName();
	long paramFlags = JavacHandlerUtil.addFinalIfNeeded(Flags.PARAMETER, builderType.getContext());
	if (!fluent) methodName = builderType.toName(HandlerUtil.buildAccessorName(mapMode ? "put" : "add", methodName.toString()));
	List<JCVariableDecl> params;
	if (mapMode) {
		JCExpression keyType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		JCExpression valueType = cloneParamType(1, maker, data.getTypeArgs(), builderType, source);
		JCVariableDecl paramKey = maker.VarDef(maker.Modifiers(paramFlags), keyName, keyType, null);
		JCVariableDecl paramValue = maker.VarDef(maker.Modifiers(paramFlags), valueName, valueType, null);
		params = List.of(paramKey, paramValue);
	} else {
		JCExpression paramType = cloneParamType(0, maker, data.getTypeArgs(), builderType, source);
		params = List.of(maker.VarDef(maker.Modifiers(paramFlags), data.getSingularName(), paramType, null));
	}
	JCMethodDecl method = maker.MethodDef(mods, methodName, returnType, typeParams, params, thrown, body, null);
	injectMethod(builderType, method);
}
 
Example #19
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 #20
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	List<JCExpression> jceBlank = List.nil();
	boolean mapMode = isMap();
	
	JCExpression varType = chainDotsString(builderType, data.getTargetFqn());
	varType = addTypeArgs(mapMode ? 2 : 1, false, builderType, varType, data.getTypeArgs(), source);
	
	JCExpression empty; {
		//ImmutableX.of()
		JCExpression emptyMethod = chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "of");
		List<JCExpression> invokeTypeArgs = createTypeArgs(mapMode ? 2 : 1, false, builderType, data.getTypeArgs(), source);
		empty = maker.Apply(invokeTypeArgs, emptyMethod, jceBlank);
	}
	
	JCExpression invokeBuild; {
		//this.pluralName.build();
		invokeBuild = maker.Apply(jceBlank, chainDots(builderType, "this", data.getPluralName().toString(), "build"), jceBlank);
	}
	
	JCExpression isNull; {
		//this.pluralName == null
		isNull = maker.Binary(CTC_EQUAL, maker.Select(maker.Ident(builderType.toName("this")), data.getPluralName()), maker.Literal(CTC_BOT, null));
	}
	
	JCExpression init = maker.Conditional(isNull, empty, invokeBuild); // this.pluralName == null ? ImmutableX.of() : this.pluralName.build()
	
	JCStatement jcs = maker.VarDef(maker.Modifiers(0), data.getPluralName(), varType, init);
	statements.append(jcs);
}
 
Example #21
Source File: JavacGuavaSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public java.util.List<JavacNode> generateFields(SingularData data, JavacNode builderType, JCTree source) {
	JavacTreeMaker maker = builderType.getTreeMaker();
	JCExpression type = JavacHandlerUtil.chainDots(builderType, "com", "google", "common", "collect", getSimpleTargetTypeName(data), "Builder");
	type = addTypeArgs(isMap() ? 2 : 1, false, builderType, type, data.getTypeArgs(), source);
	
	JCVariableDecl buildField = maker.VarDef(maker.Modifiers(Flags.PRIVATE), data.getPluralName(), type, null);
	return Collections.singletonList(injectFieldAndMarkGenerated(builderType, buildField));
}
 
Example #22
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCExpression preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) {
	if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().danceAroundIdeChecks()) {
		JCMethodInvocation singletonList = maker.Apply(List.<JCExpression>nil(), chainDotsString(node, "java.util.Collections.singletonList"), List.of(expression));
		JCMethodInvocation cleanedExpr = maker.Apply(List.<JCExpression>nil(), maker.Select(singletonList, node.toName("get")) , List.<JCExpression>of(maker.Literal(CTC_INT, 0)));
		return cleanedExpr;
	} else {
		return expression;
	}
}
 
Example #23
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
		JavacTreeMaker maker, JavacNode node, boolean isDouble) {
	/* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
	JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float");
	List<JCExpression> args = List.of(thisDotField, otherDotField);
	JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply(
			List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0));
	return maker.If(compareCallEquals0, returnBool(maker, false), null);
}
 
Example #24
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 #25
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private void addInstanceVar(JavacNode singletonClass, JavacTreeMaker singletonClassTM, JavacNode holderClass) {
    JCTree.JCModifiers fieldMod = singletonClassTM.Modifiers(Flags.PRIVATE | Flags.STATIC | Flags.FINAL);

    JCTree.JCClassDecl singletonClassDecl = (JCTree.JCClassDecl) singletonClass.get();
    JCTree.JCIdent singletonClassType = singletonClassTM.Ident(singletonClassDecl.name);

    JCTree.JCNewClass newKeyword = singletonClassTM.NewClass(null, List.nil(), singletonClassType, List.nil(), null);

    JCTree.JCVariableDecl instanceVar = singletonClassTM.VarDef(fieldMod, singletonClass.toName("INSTANCE"), singletonClassType, newKeyword);
    JavacHandlerUtil.injectField(holderClass, instanceVar);
}
 
Example #26
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 5 votes vote down vote up
/** The 2 references must be clones of each other. */
public JCExpression longToIntForHashCode(JavacTreeMaker maker, JCExpression ref1, JCExpression ref2) {
	/* (int)(ref >>> 32 ^ ref) */
	JCExpression shift = maker.Binary(CTC_UNSIGNED_SHIFT_RIGHT, ref1, maker.Literal(32));
	JCExpression xorBits = maker.Binary(CTC_BITXOR, shift, ref2);
	return maker.TypeCast(maker.TypeIdent(CTC_INT), xorBits);
}
 
Example #27
Source File: HandleEqualsAndHashCode.java    From EasyMPermission with MIT License 5 votes vote down vote up
public JCExpressionStatement createResultCalculation(JavacNode typeNode, JCExpression expr) {
	/* result = result * PRIME + (expr); */
	JavacTreeMaker maker = typeNode.getTreeMaker();
	Name resultName = typeNode.toName(RESULT_NAME);
	JCExpression mult = maker.Binary(CTC_MUL, maker.Ident(resultName), maker.Ident(typeNode.toName(PRIME_NAME)));
	JCExpression add = maker.Binary(CTC_PLUS, mult, expr);
	return maker.Exec(maker.Assign(maker.Ident(resultName), add));
}
 
Example #28
Source File: HandleBuilder.java    From EasyMPermission with MIT License 5 votes vote down vote up
private void makeSimpleSetterMethodForBuilder(JavacNode builderType, JavacNode fieldNode, JavacNode source, boolean fluent, boolean chain) {
	Name fieldName = ((JCVariableDecl) fieldNode.get()).name;
	
	for (JavacNode child : builderType.down()) {
		if (child.getKind() != Kind.METHOD) continue;
		Name existingName = ((JCMethodDecl) child.get()).name;
		if (existingName.equals(fieldName)) return;
	}
	
	String setterName = fluent ? fieldNode.getName() : HandlerUtil.buildAccessorName("set", fieldNode.getName());
	
	JavacTreeMaker maker = fieldNode.getTreeMaker();
	JCMethodDecl newMethod = HandleSetter.createSetter(Flags.PUBLIC, fieldNode, maker, setterName, chain, source, List.<JCAnnotation>nil(), List.<JCAnnotation>nil());
	injectMethod(builderType, newMethod);
}
 
Example #29
Source File: SingletonJavacHandler.java    From tutorials with MIT License 5 votes vote down vote up
private void addPrivateConstructor(JavacNode singletonClass, JavacTreeMaker singletonTM) {
    JCTree.JCModifiers modifiers = singletonTM.Modifiers(Flags.PRIVATE);
    JCTree.JCBlock block = singletonTM.Block(0L, List.nil());
    JCTree.JCMethodDecl constructor = singletonTM.MethodDef(modifiers, singletonClass.toName("<init>"), null, List.nil(), List.nil(), List.nil(), block, null);

    JavacHandlerUtil.injectMethod(singletonClass, constructor);
}
 
Example #30
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void appendBuildCode(SingularData data, JavacNode builderType, JCTree source, ListBuffer<JCStatement> statements, Name targetVariableName) {
	if (useGuavaInstead(builderType)) {
		guavaMapSingularizer.appendBuildCode(data, builderType, source, statements, targetVariableName);
		return;
	}
	
	JavacTreeMaker maker = builderType.getTreeMaker();
	
	if (data.getTargetFqn().equals("java.util.Map")) {
		statements.appendList(createJavaUtilSetMapInitialCapacitySwitchStatements(maker, data, builderType, true, "emptyMap", "singletonMap", "LinkedHashMap", source));
	} else {
		statements.appendList(createJavaUtilSimpleCreationAndFillStatements(maker, data, builderType, true, true, false, true, "TreeMap", source));
	}
}