lombok.javac.JavacNode Java Examples

The following examples show how to use lombok.javac.JavacNode. 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: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * Given a list of field names and a node referring to a type, finds each name in the list that does not match a field within the type.
 */
public static List<Integer> createListOfNonExistentFields(List<String> list, JavacNode type, boolean excludeStandard, boolean excludeTransient) {
	boolean[] matched = new boolean[list.size()];
	
	for (JavacNode child : type.down()) {
		if (list.isEmpty()) break;
		if (child.getKind() != Kind.FIELD) continue;
		JCVariableDecl field = (JCVariableDecl)child.get();
		if (excludeStandard) {
			if ((field.mods.flags & Flags.STATIC) != 0) continue;
			if (field.name.toString().startsWith("$")) continue;
		}
		if (excludeTransient && (field.mods.flags & Flags.TRANSIENT) != 0) continue;
		
		int idx = list.indexOf(child.getName());
		if (idx > -1) matched[idx] = true;
	}
	
	ListBuffer<Integer> problematic = new ListBuffer<Integer>();
	for (int i = 0 ; i < list.size() ; i++) {
		if (!matched[i]) problematic.append(i);
	}
	
	return problematic.toList();
}
 
Example #2
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 #3
Source File: HandleWither.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<Wither> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.WITHER_FLAG_USAGE, "@Wither");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Wither.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	AccessLevel level = annotation.getInstance().value();
	
	if (level == AccessLevel.NONE || node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Wither(onMethod=", annotationNode);
	List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Wither(onParam=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createWitherForFields(level, fields, annotationNode, true, onMethod, onParam);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Wither on a type.");
		if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Wither on a type.");
		generateWitherForType(node, annotationNode, level, false);
		break;
	}
}
 
Example #4
Source File: HandleSetter.java    From EasyMPermission with MIT License 6 votes vote down vote up
@Override public void handle(AnnotationValues<Setter> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.SETTER_FLAG_USAGE, "@Setter");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Setter.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	AccessLevel level = annotation.getInstance().value();
	
	if (level == AccessLevel.NONE || node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Setter(onMethod=", annotationNode);
	List<JCAnnotation> onParam = unboxAndRemoveAnnotationParameter(ast, "onParam", "@Setter(onParam=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createSetterForFields(level, fields, annotationNode, true, onMethod, onParam);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) annotationNode.addError("'onMethod' is not supported for @Setter on a type.");
		if (!onParam.isEmpty()) annotationNode.addError("'onParam' is not supported for @Setter on a type.");
		generateSetterForType(node, annotationNode, level, false);
		break;
	}
}
 
Example #5
Source File: HandleGetter.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void generateGetterForType(JavacNode typeNode, JavacNode errorNode, AccessLevel level, boolean checkForTypeLevelGetter) {
	if (checkForTypeLevelGetter) {
		if (hasAnnotation(Getter.class, typeNode)) {
			//The annotation will make it happen, so we can skip it.
			return;
		}
	}
	
	JCClassDecl typeDecl = null;
	if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get();
	long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags;
	boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0;
	
	if (typeDecl == null || notAClass) {
		errorNode.addError("@Getter is only supported on a class, an enum, or a field.");
		return;
	}
	
	for (JavacNode field : typeNode.down()) {
		if (fieldQualifiesForGetterGeneration(field)) generateGetterForField(field, errorNode.get(), level, false);
	}
}
 
Example #6
Source File: HandleConstructor.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static List<JavacNode> findRequiredFields(JavacNode typeNode) {
	ListBuffer<JavacNode> fields = new ListBuffer<JavacNode>();
	for (JavacNode child : typeNode.down()) {
		if (child.getKind() != Kind.FIELD) continue;
		JCVariableDecl fieldDecl = (JCVariableDecl) child.get();
		//Skip fields that start with $
		if (fieldDecl.name.toString().startsWith("$")) continue;
		long fieldFlags = fieldDecl.mods.flags;
		//Skip static fields.
		if ((fieldFlags & Flags.STATIC) != 0) continue;
		boolean isFinal = (fieldFlags & Flags.FINAL) != 0;
		boolean isNonNull = !findAnnotations(child, NON_NULL_PATTERN).isEmpty();
		if ((isFinal || isNonNull) && fieldDecl.init == null) fields.append(child);
	}
	return fields.toList();
}
 
Example #7
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 #8
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
/**
 * In javac, dotted access of any kind, from {@code java.lang.String} to {@code var.methodName}
 * is represented by a fold-left of {@code Select} nodes with the leftmost string represented by
 * a {@code Ident} node. This method generates such an expression.
 * <p>
 * The position of the generated node(s) will be equal to the {@code pos} parameter.
 *
 * For example, maker.Select(maker.Select(maker.Ident(NAME[java]), NAME[lang]), NAME[String]).
 * 
 * @see com.sun.tools.javac.tree.JCTree.JCIdent
 * @see com.sun.tools.javac.tree.JCTree.JCFieldAccess
 */
public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) {
	assert elems != null;
	
	JavacTreeMaker maker = node.getTreeMaker();
	if (pos != -1) maker = maker.at(pos);
	JCExpression e = null;
	if (elem1 != null) e = maker.Ident(node.toName(elem1));
	if (elem2 != null) e = e == null ? maker.Ident(node.toName(elem2)) : maker.Select(e, node.toName(elem2));
	for (int i = 0 ; i < elems.length ; i++) {
		e = e == null ? maker.Ident(node.toName(elems[i])) : maker.Select(e, node.toName(elems[i]));
	}
	
	assert e != null;
	
	return e;
}
 
Example #9
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
private static boolean hasAnnotation(Class<? extends Annotation> type, JavacNode node, boolean delete) {
	if (node == null) return false;
	if (type == null) return false;
	switch (node.getKind()) {
	case ARGUMENT:
	case FIELD:
	case LOCAL:
	case TYPE:
	case METHOD:
		for (JavacNode child : node.down()) {
			if (annotationTypeMatches(type, child)) {
				if (delete) deleteAnnotationIfNeccessary(child, type);
				return true;
			}
		}
		// intentional fallthrough
	default:
		return false;
	}
}
 
Example #10
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 #11
Source File: HandleFieldDefaults.java    From EasyMPermission with MIT License 6 votes vote down vote up
public void setFieldDefaultsForField(JavacNode fieldNode, DiagnosticPosition pos, AccessLevel level, boolean makeFinal) {
	JCVariableDecl field = (JCVariableDecl) fieldNode.get();
	if (level != null && level != AccessLevel.NONE) {
		if ((field.mods.flags & (Flags.PUBLIC | Flags.PRIVATE | Flags.PROTECTED)) == 0) {
			if (!hasAnnotationAndDeleteIfNeccessary(PackagePrivate.class, fieldNode)) {
				field.mods.flags |= toJavacModifier(level);
			}
		}
	}
	
	if (makeFinal && (field.mods.flags & Flags.FINAL) == 0) {
		if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, fieldNode)) {
			field.mods.flags |= Flags.FINAL;
		}
	}
	
	fieldNode.rebuild();
}
 
Example #12
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 6 votes vote down vote up
public static void sanityCheckForMethodGeneratingAnnotationsOnBuilderClass(JavacNode typeNode, JavacNode errorNode) {
	List<String> disallowed = List.nil();
	for (JavacNode child : typeNode.down()) {
		for (Class<? extends java.lang.annotation.Annotation> annType : INVALID_ON_BUILDERS) {
			if (annotationTypeMatches(annType, child)) {
				disallowed = disallowed.append(annType.getSimpleName());
			}
		}
	}
	
	int size = disallowed.size();
	if (size == 0) return;
	if (size == 1) {
		errorNode.addError("@" + disallowed.head + " is not allowed on builder classes.");
		return;
	}
	StringBuilder out = new StringBuilder();
	for (String a : disallowed) out.append("@").append(a).append(", ");
	out.setLength(out.length() - 2);
	errorNode.addError(out.append(" are not allowed on builder classes.").toString());
}
 
Example #13
Source File: JavacJavaUtilMapSingularizer.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public java.util.List<Name> listFieldsToBeGenerated(SingularData data, JavacNode builderType) {
	if (useGuavaInstead(builderType)) {
		return guavaMapSingularizer.listFieldsToBeGenerated(data, builderType);
	}
	
	String p = data.getPluralName().toString();
	return Arrays.asList(builderType.toName(p + "$key"), builderType.toName(p + "$value"));
}
 
Example #14
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private void generateMagicMethods(JavacTreeMaker maker, JavacNode tableElement) {
  final Set<String> allStaticMethodNames = findAllStaticMethodNames(tableElement);
  final Set<String> allMethodNames = findAllMethodNames(tableElement);
  final String tableClassName = tableElement.getName();
  generateMethod(maker, tableElement, allMethodNames, METHOD_INSERT, CLASS_INSERT, tableClassName);
  generateMethod(maker, tableElement, allMethodNames, METHOD_UPDATE, CLASS_UPDATE, tableClassName);
  generateMethod(maker, tableElement, allMethodNames, METHOD_PERSIST, CLASS_PERSIST, tableClassName);
  generateMethod(maker, tableElement, allMethodNames, METHOD_DELETE, CLASS_DELETE, tableClassName);
  generateBulkMethod(maker, tableElement, allStaticMethodNames, METHOD_INSERT, CLASS_BULK_INSERT, tableClassName, ITERABLE);
  generateBulkMethod(maker, tableElement, allStaticMethodNames, METHOD_UPDATE, CLASS_BULK_UPDATE, tableClassName, ITERABLE);
  generateBulkMethod(maker, tableElement, allStaticMethodNames, METHOD_PERSIST, CLASS_BULK_PERSIST, tableClassName, ITERABLE);
  generateBulkMethod(maker, tableElement, allStaticMethodNames, METHOD_DELETE, CLASS_BULK_DELETE, tableClassName, COLLECTION);
  generateDeleteTable(maker, tableElement, allStaticMethodNames, tableClassName);
}
 
Example #15
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static JCExpression genTypeRef(JavacNode node, String complexName) {
	String[] parts = complexName.split("\\.");
	if (parts.length > 2 && parts[0].equals("java") && parts[1].equals("lang")) {
		String[] subParts = new String[parts.length - 2];
		System.arraycopy(parts, 2, subParts, 0, subParts.length);
		return genJavaLangTypeRef(node, subParts);
	}
	
	return chainDots(node, parts);
}
 
Example #16
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 #17
Source File: HandleConstructor.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static boolean checkLegality(JavacNode typeNode, JavacNode errorNode, String name) {
	JCClassDecl typeDecl = null;
	if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl) typeNode.get();
	long modifiers = typeDecl == null ? 0 : typeDecl.mods.flags;
	boolean notAClass = (modifiers & (Flags.INTERFACE | Flags.ANNOTATION)) != 0;
	
	if (typeDecl == null || notAClass) {
		errorNode.addError(name + " is only supported on a class or an enum.");
		return false;
	}
	
	return true;
}
 
Example #18
Source File: HandleRuntimePermission.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override
public void handle(AnnotationValues<RuntimePermission> annotation, JCAnnotation ast, JavacNode annotationNode) {

    deleteAnnotationIfNeccessary(annotationNode, RuntimePermission.class);
    JavacNode typeNode = annotationNode.up();
    boolean notAClass = !isClass(typeNode);

    if (notAClass) {
        annotationNode.addError("@RuntimePermission is only supported on a class.");
        return;
    }

    JCMethodDecl method;

    List<PermissionAnnotatedItem> permissionList = findAllAnnotatedMethods(typeNode);
    for (PermissionAnnotatedItem item : permissionList) {
        method = createPermissionCheckedMethod(typeNode, item);
        removeMethod(typeNode, item.getMethod());
        injectMethod(typeNode, recursiveSetGeneratedBy(method, annotationNode.get(), typeNode.getContext()));
    }

    method = recursiveSetGeneratedBy(createIsPermissionGrantedMethod(typeNode), annotationNode.get(), typeNode.getContext());
    injectMethod(typeNode, method);

    method = recursiveSetGeneratedBy(createOnRequestPermissionMethod(typeNode, permissionList), annotationNode.get(), typeNode.getContext());
    injectMethod(typeNode, method);
}
 
Example #19
Source File: HandleTable.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
private static Set<String> findAllStaticMethodNames(JavacNode typeNode) {
  Set<String> methodNames = new LinkedHashSet<>();
  for (JavacNode child : typeNode.down()) {
    if (child.getKind() != AST.Kind.METHOD) continue;
    JCTree.JCMethodDecl methodDecl = (JCTree.JCMethodDecl) child.get();
    long methodFlags = methodDecl.mods.flags;
    //Take static methods
    if ((methodFlags & Flags.STATIC) != 0) {
      methodNames.add(child.getName());
    }
  }
  return methodNames;
}
 
Example #20
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static boolean isClassAndDoesNotHaveFlags(JavacNode typeNode, int flags) {
	JCClassDecl typeDecl = null;
	if (typeNode.get() instanceof JCClassDecl) typeDecl = (JCClassDecl)typeNode.get();
	else return false;
	
	long typeDeclflags = typeDecl == null ? 0 : typeDecl.mods.flags;
	return (typeDeclflags & flags) == 0;
}
 
Example #21
Source File: HandleToString.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void generateToStringForType(JavacNode typeNode, JavacNode errorNode) {
	if (hasAnnotation(ToString.class, typeNode)) {
		//The annotation will make it happen, so we can skip it.
		return;
	}
	
	
	boolean includeFieldNames = true;
	try {
		Boolean configuration = typeNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES);
		includeFieldNames = configuration != null ? configuration : ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue();
	} catch (Exception ignore) {}
	generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false, FieldAccess.GETTER);
}
 
Example #22
Source File: HandleToString.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<ToString> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.TO_STRING_FLAG_USAGE, "@ToString");
	
	deleteAnnotationIfNeccessary(annotationNode, ToString.class);
	
	ToString ann = annotation.getInstance();
	List<String> excludes = List.from(ann.exclude());
	List<String> includes = List.from(ann.of());
	JavacNode typeNode = annotationNode.up();
	
	checkForBogusFieldNames(typeNode, annotation);
	
	Boolean callSuper = ann.callSuper();
	
	if (!annotation.isExplicit("callSuper")) callSuper = null;
	if (!annotation.isExplicit("exclude")) excludes = null;
	if (!annotation.isExplicit("of")) includes = null;
	
	if (excludes != null && includes != null) {
		excludes = null;
		annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored.");
	}
	
	Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS);
	boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration;
	FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER;
	
	Boolean fieldNamesConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES);
	boolean includeFieldNames = annotation.isExplicit("includeFieldNames") || fieldNamesConfiguration == null ? ann.includeFieldNames() : fieldNamesConfiguration;
	
	generateToString(typeNode, annotationNode, excludes, includes, includeFieldNames, callSuper, true, fieldAccess);
}
 
Example #23
Source File: HandleFieldDefaults.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<FieldDefaults> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.FIELD_DEFAULTS_FLAG_USAGE, "@FieldDefaults");
	
	deleteAnnotationIfNeccessary(annotationNode, FieldDefaults.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	FieldDefaults instance = annotation.getInstance();
	AccessLevel level = instance.level();
	boolean makeFinal = instance.makeFinal();
	
	if (level == AccessLevel.NONE && !makeFinal) {
		annotationNode.addError("This does nothing; provide either level or makeFinal or both.");
		return;
	}
	
	if (level == AccessLevel.PACKAGE) {
		annotationNode.addError("Setting 'level' to PACKAGE does nothing. To force fields as package private, use the @PackagePrivate annotation on the field.");
	}
	
	if (!makeFinal && annotation.isExplicit("makeFinal")) {
		annotationNode.addError("Setting 'makeFinal' to false does nothing. To force fields to be non-final, use the @NonFinal annotation on the field.");
	}
	
	if (node == null) return;
	
	generateFieldDefaultsForType(node, annotationNode, level, makeFinal, false);
}
 
Example #24
Source File: HandleGetter.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<Getter> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_FLAG_USAGE, "@Getter");
	
	Collection<JavacNode> fields = annotationNode.upFromAnnotationToFields();
	deleteAnnotationIfNeccessary(annotationNode, Getter.class);
	deleteImportFromCompilationUnit(annotationNode, "lombok.AccessLevel");
	JavacNode node = annotationNode.up();
	Getter annotationInstance = annotation.getInstance();
	AccessLevel level = annotationInstance.value();
	boolean lazy = annotationInstance.lazy();
	if (lazy) handleFlagUsage(annotationNode, ConfigurationKeys.GETTER_LAZY_FLAG_USAGE, "@Getter(lazy=true)");
	
	if (level == AccessLevel.NONE) {
		if (lazy) annotationNode.addWarning("'lazy' does not work with AccessLevel.NONE.");
		return;
	}
	
	if (node == null) return;
	
	List<JCAnnotation> onMethod = unboxAndRemoveAnnotationParameter(ast, "onMethod", "@Getter(onMethod=", annotationNode);
	
	switch (node.getKind()) {
	case FIELD:
		createGetterForFields(level, fields, annotationNode, true, lazy, onMethod);
		break;
	case TYPE:
		if (!onMethod.isEmpty()) {
			annotationNode.addError("'onMethod' is not supported for @Getter on a type.");
		}
		if (lazy) annotationNode.addError("'lazy' is not supported for @Getter on a type.");
		generateGetterForType(node, annotationNode, level, false);
		break;
	}
}
 
Example #25
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static JCExpression genJavaLangTypeRef(JavacNode node, String... simpleNames) {
	if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().javaLangAsFqn()) {
		return chainDots(node, "java", "lang", simpleNames);
	} else {
		return chainDots(node, null, null, simpleNames);
	}
}
 
Example #26
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
private static JavacNode injectField(JavacNode typeNode, JCVariableDecl field, boolean addGenerated) {
	JCClassDecl type = (JCClassDecl) typeNode.get();
	
	if (addGenerated) {
		addSuppressWarningsAll(field.mods, typeNode, field.pos, getGeneratedBy(field), typeNode.getContext());
		addGenerated(field.mods, typeNode, field.pos, getGeneratedBy(field), typeNode.getContext());
	}
	
	List<JCTree> insertAfter = null;
	List<JCTree> insertBefore = type.defs;
	while (insertBefore.tail != null) {
		if (insertBefore.head instanceof JCVariableDecl) {
			JCVariableDecl f = (JCVariableDecl) insertBefore.head;
			if (isEnumConstant(f) || isGenerated(f)) {
				insertAfter = insertBefore;
				insertBefore = insertBefore.tail;
				continue;
			}
		}
		break;
	}
	List<JCTree> fieldEntry = List.<JCTree>of(field);
	fieldEntry.tail = insertBefore;
	if (insertAfter == null) {
		type.defs = fieldEntry;
	} else {
		insertAfter.tail = fieldEntry;
	}
	
	return typeNode.add(field, Kind.FIELD);
}
 
Example #27
Source File: HandleCleanup.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void doAssignmentCheck0(JavacNode node, JCTree statement, Name name) {
	if (statement instanceof JCAssign) doAssignmentCheck0(node, ((JCAssign)statement).rhs, name);
	if (statement instanceof JCExpressionStatement) doAssignmentCheck0(node,
			((JCExpressionStatement)statement).expr, name);
	if (statement instanceof JCVariableDecl) doAssignmentCheck0(node, ((JCVariableDecl)statement).init, name);
	if (statement instanceof JCTypeCast) doAssignmentCheck0(node, ((JCTypeCast)statement).expr, name);
	if (statement instanceof JCIdent) {
		if (((JCIdent)statement).name.contentEquals(name)) {
			JavacNode problemNode = node.getNodeFor(statement);
			if (problemNode != null) problemNode.addWarning(
			"You're assigning an auto-cleanup variable to something else. This is a bad idea.");
		}
	}
}
 
Example #28
Source File: HandleUtilityClass.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<UtilityClass> annotation, JCAnnotation ast, JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.UTLITY_CLASS_FLAG_USAGE, "@UtilityClass");
	
	deleteAnnotationIfNeccessary(annotationNode, UtilityClass.class);
	
	JavacNode typeNode = annotationNode.up();
	if (!checkLegality(typeNode, annotationNode)) return;
	changeModifiersAndGenerateConstructor(annotationNode.up(), annotationNode);
}
 
Example #29
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static JCExpression chainDots(JavacNode node, LombokImmutableList<String> elems) {
	assert elems != null;
	
	JavacTreeMaker maker = node.getTreeMaker();
	JCExpression e = null;
	for (String elem : elems) {
		if (e == null) e = maker.Ident(node.toName(elem));
		else e = maker.Select(e, node.toName(elem));
	}
	return e;
}
 
Example #30
Source File: JavacHandlerUtil.java    From EasyMPermission with MIT License 5 votes vote down vote up
public static JCExpression genJavaLangTypeRef(JavacNode node, int pos, String... simpleNames) {
	if (LombokOptionsFactory.getDelombokOptions(node.getContext()).getFormatPreferences().javaLangAsFqn()) {
		return chainDots(node, pos, "java", "lang", simpleNames);
	} else {
		return chainDots(node, pos, null, null, simpleNames);
	}
}