Java Code Examples for lombok.javac.JavacNode#rebuild()

The following examples show how to use lombok.javac.JavacNode#rebuild() . 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: 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 2
Source File: HandleColumn.java    From sqlitemagic with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(AnnotationValues<Column> annotation, JCTree.JCAnnotation ast, JavacNode annotationNode) {
  // FIXME: 9.04.16 remove
  JavacNode node = annotationNode.up();
  if (node.getKind() == AST.Kind.FIELD) {
    JCTree.JCVariableDecl fieldDec = (JCTree.JCVariableDecl) node.get();
    if ((fieldDec.mods.flags & Flags.PRIVATE) != 0 && (fieldDec.mods.flags & (Flags.STATIC | Flags.FINAL)) == 0) {
      fieldDec.mods.flags &= ~Flags.PRIVATE;
    }
    node.rebuild();
  }
}
 
Example 3
Source File: HandleValue.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public void handle(AnnotationValues<Value> annotation, JCAnnotation ast, JavacNode annotationNode) {
	@SuppressWarnings("deprecation")
	Class<? extends Annotation> oldExperimentalValue = lombok.experimental.Value.class;
	
	handleFlagUsage(annotationNode, ConfigurationKeys.VALUE_FLAG_USAGE, "@Value");
	
	deleteAnnotationIfNeccessary(annotationNode, Value.class, oldExperimentalValue);
	JavacNode typeNode = annotationNode.up();
	boolean notAClass = !isClass(typeNode);
	
	if (notAClass) {
		annotationNode.addError("@Value is only supported on a class.");
		return;
	}
	
	String staticConstructorName = annotation.getInstance().staticConstructor();
	
	if (!hasAnnotationAndDeleteIfNeccessary(NonFinal.class, typeNode)) {
		JCModifiers jcm = ((JCClassDecl) typeNode.get()).mods;
		if ((jcm.flags & Flags.FINAL) == 0) {
			jcm.flags |= Flags.FINAL;
			typeNode.rebuild();
		}
	}
	new HandleFieldDefaults().generateFieldDefaultsForType(typeNode, annotationNode, AccessLevel.PRIVATE, true, true);
	
	// TODO move this to the end OR move it to the top in eclipse.
	new HandleConstructor().generateAllArgsConstructor(typeNode, AccessLevel.PUBLIC, staticConstructorName, SkipIfConstructorExists.YES, annotationNode);
	new HandleGetter().generateGetterForType(typeNode, annotationNode, AccessLevel.PUBLIC, true);
	new HandleEqualsAndHashCode().generateEqualsAndHashCodeForType(typeNode, annotationNode);
	new HandleToString().generateToStringForType(typeNode, annotationNode);
}
 
Example 4
Source File: HandleSneakyThrows.java    From EasyMPermission with MIT License 5 votes vote down vote up
public void handleMethod(JavacNode annotation, JCMethodDecl method, Collection<String> exceptions) {
	JavacNode methodNode = annotation.up();
	
	if ( (method.mods.flags & Flags.ABSTRACT) != 0) {
		annotation.addError("@SneakyThrows can only be used on concrete methods.");
		return;
	}
	
	if (method.body == null || method.body.stats.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, false);
		return;
	}
	
	final JCStatement constructorCall = method.body.stats.get(0);
	final boolean isConstructorCall = isConstructorCall(constructorCall);
	List<JCStatement> contents = isConstructorCall ? method.body.stats.tail : method.body.stats;
	
	if (contents == null || contents.isEmpty()) {
		generateEmptyBlockWarning(methodNode, annotation, true);
		return;
	}
	
	for (String exception : exceptions) {
		contents = List.of(buildTryCatchBlock(methodNode, contents, exception, annotation.get()));
	}
	
	method.body.stats = isConstructorCall ? List.of(constructorCall).appendList(contents) : contents;
	methodNode.rebuild();
}
 
Example 5
Source File: HandleExtensionMethod.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override
public void handle(final AnnotationValues<ExtensionMethod> annotation, final JCAnnotation source, final JavacNode annotationNode) {
	handleExperimentalFlagUsage(annotationNode, ConfigurationKeys.EXTENSION_METHOD_FLAG_USAGE, "@ExtensionMethod");
	
	deleteAnnotationIfNeccessary(annotationNode, ExtensionMethod.class);
	JavacNode typeNode = annotationNode.up();
	boolean isClassOrEnum = isClassOrEnum(typeNode);
	
	if (!isClassOrEnum) {
		annotationNode.addError("@ExtensionMethod can only be used on a class or an enum");
		return;
	}
	
	boolean suppressBaseMethods = annotation.getInstance().suppressBaseMethods();
	
	List<Object> extensionProviders = annotation.getActualExpressions("value");
	if (extensionProviders.isEmpty()) {
		annotationNode.addError(String.format("@%s has no effect since no extension types were specified.", ExtensionMethod.class.getName()));
		return;
	}
	final List<Extension> extensions = getExtensions(annotationNode, extensionProviders);
	if (extensions.isEmpty()) return;
	
	new ExtensionMethodReplaceVisitor(annotationNode, extensions, suppressBaseMethods).replace();
	
	annotationNode.rebuild();
}
 
Example 6
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 7
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();
}