Added complete support for delombok's 'pretty' format options; covering all of the issue #608.

This commit is contained in:
Reinier Zwitserloot committed 2013-12-11 22:40:48 +01:00
1 parent 9ac86c8a23
commit a19b99cba2
15 files changed
+162 -90

No files matched your search

+1
View File
@@ -4,6 +4,7 @@ Lombok Changelog
### v1.12.3 "Edgy Guinea Pig"
* BUGFIX: v1.12.2's delombok turns all operator+assignments into just assignment. Fixed. [Issue #598](https://code.google.com/p/projectlombok/issues/detail?id=598)
* BUGFIX: {Netbeans} v1.12.2 doesn't well with netbeans. [Issue #591](https://code.google.com/p/projectlombok/issues/detail?id=591)
* ENHANCEMENT: Delombok now supports varied options for how it formats the resulting source files. This includes scanning the source for things like the preferred indent. Use option `--format-help` for more information. [Issue #608](http://code.google.com/p/projectlombok/issues/detail?id=608)
### v1.12.2 (October 10th, 2013)
* PLATFORM: Initial JDK8 support, without affecting existing support for JDK6 and 7. [Issue #451](https://code.google.com/p/projectlombok/issues/detail?id=451). While lombok will now work on JDK8 / javac8, and netbeans 7.4 and up, lombok does not (yet) support new language features introduced with java8, such as lambda expressions. Support for these features will be added in a future version.
@@ -26,6 +26,7 @@ import static lombok.javac.Javac.*;
import lombok.Cleanup;
import lombok.core.AST.Kind;
import lombok.core.AnnotationValues;
import lombok.delombok.LombokOptionsFactory;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
import lombok.javac.JavacTreeMaker;
@@ -119,7 +120,7 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> {
List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(
maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));
JCMethodInvocation preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
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);
@@ -140,10 +141,14 @@ public class HandleCleanup extends JavacAnnotationHandler<Cleanup> {
ancestor.rebuild();
}
private JCMethodInvocation preventNullAnalysis(JavacTreeMaker maker, JavacNode node, JCExpression expression) {
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;
private 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;
}
}
private void doAssignmentCheck(JavacNode node, List<JCStatement> statements, Name name) {
@@ -29,6 +29,7 @@ import lombok.RequiredArgsConstructor;
import lombok.core.AnnotationValues;
import lombok.core.TransformationsUtil;
import lombok.core.AST.Kind;
import lombok.delombok.LombokOptionsFactory;
import lombok.experimental.Builder;
import lombok.javac.JavacAnnotationHandler;
import lombok.javac.JavacNode;
@@ -249,7 +250,7 @@ public class HandleConstructor {
}
JCModifiers mods = maker.Modifiers(toJavacModifier(level), List.<JCAnnotation>nil());
if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(typeNode)) {
if (!suppressConstructorProperties && level != AccessLevel.PRIVATE && !isLocalType(typeNode) && LombokOptionsFactory.getDelombokOptions(typeNode.getContext()).getFormatPreferences().generateConstructorProperties()) {
addConstructorProperties(mods, typeNode, fields);
}
if (onConstructor != null) mods.annotations = mods.annotations.appendList(copyAnnotations(onConstructor));
@@ -271,7 +271,7 @@ public class HandleDelegate extends JavacAnnotationHandler<Delegate> {
com.sun.tools.javac.util.List<JCAnnotation> annotations;
if (sig.isDeprecated) {
annotations = com.sun.tools.javac.util.List.of(maker.Annotation(
chainDots(annotation, "java", "lang", "Deprecated"),
genJavaLangTypeRef(annotation, "Deprecated"),
com.sun.tools.javac.util.List.<JCExpression>nil()));
} else {
annotations = com.sun.tools.javac.util.List.nil();
@@ -221,7 +221,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
private JCMethodDecl createHashCode(JavacNode typeNode, List<JavacNode> fields, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
JavacTreeMaker maker = typeNode.getTreeMaker();
JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil());
JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
JCExpression returnType = maker.TypeIdent(CTC_INT);
ListBuffer<JCStatement> statements = new ListBuffer<JCStatement>();
@@ -267,7 +267,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
/* Float.floatToIntBits(this.fieldName) */
statements.append(createResultCalculation(typeNode, maker.Apply(
List.<JCExpression>nil(),
chainDots(typeNode, "java", "lang", "Float", "floatToIntBits"),
genJavaLangTypeRef(typeNode, "Float", "floatToIntBits"),
List.of(fieldAccessor))));
break;
case DOUBLE: {
@@ -275,7 +275,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name);
JCExpression init = maker.Apply(
List.<JCExpression>nil(),
chainDots(typeNode, "java", "lang", "Double", "doubleToLongBits"),
genJavaLangTypeRef(typeNode, "Double", "doubleToLongBits"),
List.of(fieldAccessor));
statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, maker.TypeIdent(CTC_LONG), init));
statements.append(createResultCalculation(typeNode, longToIntForHashCode(maker, maker.Ident(dollarFieldName), maker.Ident(dollarFieldName))));
@@ -303,7 +303,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
/* $fieldName == null ? 0 : $fieldName.hashCode() */
Name dollarFieldName = dollar.append(((JCVariableDecl)fieldNode.get()).name);
statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, chainDots(typeNode, "java", "lang", "Object"), fieldAccessor));
statements.append(maker.VarDef(maker.Modifiers(finalFlag), dollarFieldName, genJavaLangTypeRef(typeNode, "Object"), fieldAccessor));
JCExpression hcCall = maker.Apply(List.<JCExpression>nil(), maker.Select(maker.Ident(dollarFieldName), typeNode.toName("hashCode")),
List.<JCExpression>nil());
@@ -366,9 +366,9 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
Name otherName = typeNode.toName("other");
Name thisName = typeNode.toName("this");
JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil());
JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
JCExpression objectType = chainDots(typeNode, "java", "lang", "Object");
JCExpression objectType = genJavaLangTypeRef(typeNode, "Object");
JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
long finalFlag = JavacHandlerUtil.addFinalIfNeeded(0L, typeNode.getContext());
@@ -414,7 +414,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
if (needsCanEqual) {
List<JCExpression> exprNil = List.nil();
JCExpression thisRef = maker.Ident(thisName);
JCExpression castThisRef = maker.TypeCast(chainDots(typeNode, "java", "lang", "Object"), thisRef);
JCExpression castThisRef = maker.TypeCast(genJavaLangTypeRef(typeNode, "Object"), thisRef);
JCExpression equalityCheck = maker.Apply(exprNil,
maker.Select(maker.Ident(otherName), typeNode.toName("canEqual")),
List.of(castThisRef));
@@ -471,8 +471,8 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
Name thisDollarFieldName = thisDollar.append(fieldName);
Name otherDollarFieldName = otherDollar.append(fieldName);
statements.append(maker.VarDef(maker.Modifiers(finalFlag), thisDollarFieldName, chainDots(typeNode, "java", "lang", "Object"), thisFieldAccessor));
statements.append(maker.VarDef(maker.Modifiers(finalFlag), otherDollarFieldName, chainDots(typeNode, "java", "lang", "Object"), otherFieldAccessor));
statements.append(maker.VarDef(maker.Modifiers(finalFlag), thisDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), thisFieldAccessor));
statements.append(maker.VarDef(maker.Modifiers(finalFlag), otherDollarFieldName, genJavaLangTypeRef(typeNode, "Object"), otherFieldAccessor));
JCExpression thisEqualsNull = maker.Binary(CTC_EQUAL, maker.Ident(thisDollarFieldName), maker.Literal(CTC_BOT, null));
JCExpression otherNotEqualsNull = maker.Binary(CTC_NOT_EQUAL, maker.Ident(otherDollarFieldName), maker.Literal(CTC_BOT, null));
@@ -502,7 +502,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.<JCAnnotation>nil());
JCExpression returnType = maker.TypeIdent(CTC_BOOLEAN);
Name canEqualName = typeNode.toName("canEqual");
JCExpression objectType = chainDots(typeNode, "java", "lang", "Object");
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), otherName, objectType, null));
@@ -516,7 +516,7 @@ public class HandleEqualsAndHashCode extends JavacAnnotationHandler<EqualsAndHas
private JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
JavacTreeMaker maker, JavacNode node, boolean isDouble) {
/* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
JCExpression clazz = chainDots(node, "java", "lang", isDouble ? "Double" : "Float");
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));
@@ -246,7 +246,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> {
List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod).appendList(nonNulls).appendList(nullables);
if (isFieldDeprecated(field)) {
annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil()));
annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
}
JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
@@ -287,20 +287,19 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> {
}
private static final String AR = "java.util.concurrent.atomic.AtomicReference";
private static final String JLO = "java.lang.Object";
private static final List<JCExpression> NIL_EXPRESSION = List.nil();
private static final java.util.Map<TypeTag, String> TYPE_MAP;
static {
Map<TypeTag, String> m = new HashMap<TypeTag, String>();
m.put(CTC_INT, "java.lang.Integer");
m.put(CTC_DOUBLE, "java.lang.Double");
m.put(CTC_FLOAT, "java.lang.Float");
m.put(CTC_SHORT, "java.lang.Short");
m.put(CTC_BYTE, "java.lang.Byte");
m.put(CTC_LONG, "java.lang.Long");
m.put(CTC_BOOLEAN, "java.lang.Boolean");
m.put(CTC_CHAR, "java.lang.Character");
m.put(CTC_INT, "Integer");
m.put(CTC_DOUBLE, "Double");
m.put(CTC_FLOAT, "Float");
m.put(CTC_SHORT, "Short");
m.put(CTC_BYTE, "Byte");
m.put(CTC_LONG, "Long");
m.put(CTC_BOOLEAN, "Boolean");
m.put(CTC_CHAR, "Character");
TYPE_MAP = Collections.unmodifiableMap(m);
}
@@ -339,8 +338,8 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> {
String boxed = TYPE_MAP.get(typeTag(field.vartype));
if (boxed != null) {
isPrimitive = true;
field.vartype = chainDotsString(fieldNode, boxed);
copyOfBoxedFieldType = chainDotsString(fieldNode, boxed);
field.vartype = genJavaLangTypeRef(fieldNode, boxed);
copyOfBoxedFieldType = genJavaLangTypeRef(fieldNode, boxed);
}
}
if (copyOfBoxedFieldType == null) copyOfBoxedFieldType = copyType(maker, field);
@@ -349,7 +348,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> {
Name actualValueName = fieldNode.toName("actualValue");
/* java.lang.Object value = this.fieldName.get();*/ {
JCExpression valueVarType = chainDotsString(fieldNode, JLO);
JCExpression valueVarType = genJavaLangTypeRef(fieldNode, "Object");
statements.append(maker.VarDef(maker.Modifiers(0), valueName, valueVarType, callGet(fieldNode, createFieldAccessor(maker, fieldNode, FieldAccess.ALWAYS_FIELD))));
}
@@ -417,7 +416,7 @@ public class HandleGetter extends JavacAnnotationHandler<Getter> {
/* private final java.util.concurrent.atomic.AtomicReference<Object> fieldName = new java.util.concurrent.atomic.AtomicReference<Object>(); */ {
field.vartype = recursiveSetGeneratedBy(
maker.TypeApply(chainDotsString(fieldNode, AR), List.<JCExpression>of(chainDotsString(fieldNode, JLO))), source, fieldNode.getContext());
maker.TypeApply(chainDotsString(fieldNode, AR), List.<JCExpression>of(genJavaLangTypeRef(fieldNode, "Object"))), source, fieldNode.getContext());
field.init = recursiveSetGeneratedBy(maker.NewClass(null, NIL_EXPRESSION, copyType(maker, field), NIL_EXPRESSION, null), source, fieldNode.getContext());
}
@@ -246,7 +246,7 @@ public class HandleSetter extends JavacAnnotationHandler<Setter> {
List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
if (isFieldDeprecated(field)) {
annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil()));
annsOnMethod = annsOnMethod.prepend(treeMaker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
}
JCMethodDecl decl = recursiveSetGeneratedBy(treeMaker.MethodDef(treeMaker.Modifiers(access, annsOnMethod), methodName, methodType,
@@ -88,9 +88,9 @@ public class HandleSynchronized extends JavacAnnotationHandler<Synchronized> {
annotationNode.addError("The field " + lockName + " does not exist.");
return;
}
JCExpression objectType = chainDots(methodNode, ast.pos, "java", "lang", "Object");
JCExpression objectType = genJavaLangTypeRef(methodNode, ast.pos, "Object");
//We use 'new Object[0];' because unlike 'new Object();', empty arrays *ARE* serializable!
JCNewArray newObjectArray = maker.NewArray(chainDots(methodNode, ast.pos, "java", "lang", "Object"),
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)),
@@ -169,9 +169,9 @@ public class HandleToString extends JavacAnnotationHandler<ToString> {
static JCMethodDecl createToString(JavacNode typeNode, Collection<JavacNode> fields, boolean includeFieldNames, boolean callSuper, FieldAccess fieldAccess, JCTree source) {
JavacTreeMaker maker = typeNode.getTreeMaker();
JCAnnotation overrideAnnotation = maker.Annotation(chainDots(typeNode, "java", "lang", "Override"), List.<JCExpression>nil());
JCAnnotation overrideAnnotation = maker.Annotation(genJavaLangTypeRef(typeNode, "Override"), List.<JCExpression>nil());
JCModifiers mods = maker.Modifiers(Flags.PUBLIC, List.of(overrideAnnotation));
JCExpression returnType = chainDots(typeNode, "java", "lang", "String");
JCExpression returnType = genJavaLangTypeRef(typeNode, "String");
boolean first = true;
@@ -262,7 +262,7 @@ public class HandleWither extends JavacAnnotationHandler<Wither> {
List<JCAnnotation> annsOnMethod = copyAnnotations(onMethod);
if (isFieldDeprecated(field)) {
annsOnMethod = annsOnMethod.prepend(maker.Annotation(chainDots(field, "java", "lang", "Deprecated"), List.<JCExpression>nil()));
annsOnMethod = annsOnMethod.prepend(maker.Annotation(genJavaLangTypeRef(field, "Deprecated"), List.<JCExpression>nil()));
}
JCMethodDecl decl = recursiveSetGeneratedBy(maker.MethodDef(maker.Modifiers(access, annsOnMethod), methodName, returnType,
methodGenericParams, parameters, throwsClauses, methodBody, annotationMethodDefaultValue), source, field.getContext());
@@ -900,10 +900,26 @@ public class JavacHandlerUtil {
return flags;
}
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);
}
}
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);
}
}
private static void addSuppressWarningsAll(JCModifiers mods, JavacNode node, int pos, JCTree source, Context context) {
if (!LombokOptionsFactory.getDelombokOptions(context).getFormatPreferences().generateSuppressWarnings()) return;
JavacTreeMaker maker = node.getTreeMaker();
JCExpression suppressWarningsType = chainDots(node, "java", "lang", "SuppressWarnings");
JCExpression suppressWarningsType = genJavaLangTypeRef(node, "SuppressWarnings");
JCLiteral allLiteral = maker.Literal("all");
suppressWarningsType.pos = pos;
allLiteral.pos = pos;
@@ -933,8 +949,12 @@ public class JavacHandlerUtil {
* @see com.sun.tools.javac.tree.JCTree.JCIdent
* @see com.sun.tools.javac.tree.JCTree.JCFieldAccess
*/
public static JCExpression chainDots(JavacNode node, String... elems) {
return chainDots(node, -1, elems);
public static JCExpression chainDots(JavacNode node, String elem1, String elem2, String... elems) {
return chainDots(node, -1, elem1, elem2, elems);
}
public static JCExpression chainDots(JavacNode node, String[] elems) {
return chainDots(node, -1, null, null, elems);
}
/**
@@ -949,17 +969,20 @@ public class JavacHandlerUtil {
* @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... elems) {
public static JCExpression chainDots(JavacNode node, int pos, String elem1, String elem2, String... elems) {
assert elems != null;
assert elems.length > 0;
JavacTreeMaker maker = node.getTreeMaker();
if (pos != -1) maker = maker.at(pos);
JCExpression e = maker.Ident(node.toName(elems[0]));
for (int i = 1 ; i < elems.length ; i++) {
e = maker.Select(e, node.toName(elems[i]));
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;
}
@@ -975,7 +998,7 @@ public class JavacHandlerUtil {
* @see com.sun.tools.javac.tree.JCTree.JCFieldAccess
*/
public static JCExpression chainDotsString(JavacNode node, String elems) {
return chainDots(node, elems.split("\\."));
return chainDots(node, null, null, elems.split("\\."));
}
/**
@@ -1007,7 +1030,7 @@ public class JavacHandlerUtil {
JCVariableDecl varDecl = (JCVariableDecl) variable.get();
if (isPrimitive(varDecl.vartype)) return null;
Name fieldName = varDecl.name;
JCExpression npe = chainDots(variable, "java", "lang", "NullPointerException");
JCExpression npe = genJavaLangTypeRef(variable, "NullPointerException");
JCExpression exception = maker.NewClass(null, List.<JCExpression>nil(), npe, List.<JCExpression>of(maker.Literal(fieldName.toString())), null);
JCStatement throwStatement = maker.Throw(exception);
JCBlock throwBlock = maker.Block(0, List.of(throwStatement));
+28 -6
View File
@@ -206,26 +206,47 @@ public class Delombok {
System.out.println(indentAndWordbreak(e.getValue(), 4, 70));
}
System.out.println("Example: -f indent:4 -f emptyLines:indent");
System.out.println("The '-f pretty' option is shorthand for '-f suppressWarnings:skip -f danceAroundIdeChecks:skip -f generateDelombokComment:skip -f javaLangAsFQN:skip'");
System.exit(0);
return;
}
boolean prettyEnabled = false;
for (String format : args.format) {
int idx = format.indexOf(':');
if (idx == -1) {
System.err.println("Format keys need to be 2 values separated with a colon. Try -f help.");
System.exit(1);
return;
if (format.equalsIgnoreCase("pretty")) {
prettyEnabled = true;
continue;
} else {
System.err.println("Format keys need to be 2 values separated with a colon. Try -f help.");
System.exit(1);
return;
}
}
String key = format.substring(0, idx);
String value = format.substring(idx + 1);
if (!FormatPreferences.getKeysAndDescriptions().containsKey(key)) {
boolean valid = false;
for (String k : FormatPreferences.getKeysAndDescriptions().keySet()) {
if (k.equalsIgnoreCase(key)) {
valid = true;
break;
}
}
if (!valid) {
System.err.println("Unknown format key: '" + key + "'. Try -f help.");
System.exit(1);
return;
}
formatPrefs.put(key, value);
formatPrefs.put(key.toLowerCase(), value);
}
if (prettyEnabled) {
if (!formatPrefs.containsKey("suppresswarnings")) formatPrefs.put("suppresswarnings", "skip");
if (!formatPrefs.containsKey("dancearoundidechecks")) formatPrefs.put("dancearoundidechecks", "skip");
if (!formatPrefs.containsKey("generatedelombokcomment")) formatPrefs.put("generatedelombokcomment", "skip");
if (!formatPrefs.containsKey("javalangasfqn")) formatPrefs.put("javalangasfqn", "skip");
}
delombok.setFormatPreferences(formatPrefs);
@@ -474,8 +495,9 @@ public class Delombok {
Object care = callAttributeMethodOnJavaCompiler(delegate, delegate.todo);
callFlowMethodOnJavaCompiler(delegate, care);
FormatPreferences fps = new FormatPreferences(formatPrefs);
for (JCCompilationUnit unit : roots) {
DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), formatPrefs);
DelombokResult result = new DelombokResult(catcher.getComments(unit), unit, force || options.isChanged(unit), fps);
if (verbose) feedback.printf("File: %s [%s]\n", unit.sourcefile.getName(), result.isChanged() ? "delomboked" : "unchanged");
Writer rawWriter;
if (presetWriter != null) rawWriter = presetWriter;
@@ -1,5 +1,5 @@
/*
* Copyright (C) 2009-2010 The Project Lombok Authors.
* Copyright (C) 2009-2013 The Project Lombok Authors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
@@ -25,7 +25,6 @@ import java.io.IOException;
import java.io.Writer;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.tools.JavaFileObject;
@@ -37,9 +36,9 @@ public class DelombokResult {
private final List<CommentInfo> comments;
private final JCCompilationUnit compilationUnit;
private final boolean changed;
private final Map<String, String> formatPreferences;
private final FormatPreferences formatPreferences;
public DelombokResult(List<CommentInfo> comments, JCCompilationUnit compilationUnit, boolean changed, Map<String, String> formatPreferences) {
public DelombokResult(List<CommentInfo> comments, JCCompilationUnit compilationUnit, boolean changed, FormatPreferences formatPreferences) {
this.comments = comments;
this.compilationUnit = compilationUnit;
this.changed = changed;
@@ -55,9 +54,11 @@ public class DelombokResult {
}
}
out.write("// Generated by delombok at ");
out.write(String.valueOf(new Date()));
out.write(System.getProperty("line.separator"));
if (formatPreferences.generateDelombokComment()) {
out.write("// Generated by delombok at ");
out.write(String.valueOf(new Date()));
out.write(System.getProperty("line.separator"));
}
com.sun.tools.javac.util.List<CommentInfo> comments_;
if (comments instanceof com.sun.tools.javac.util.List) comments_ = (com.sun.tools.javac.util.List<CommentInfo>) comments;
@@ -37,17 +37,16 @@ import java.util.Map;
*/
public class FormatPreferenceScanner {
/** Checks validity of preferences, and returns with a non-null value if ALL format keys are available, thus negating the need for a scan. */
private FormatPreferences tryEasy(Map<String, String> preferences, boolean force) {
private FormatPreferences tryEasy(FormatPreferences preferences, boolean force) {
int count = 0;
for (Map.Entry<String, String> e : preferences.entrySet()) {
if (!FormatPreferences.KEYS.containsKey(e.getKey())) throw new IllegalArgumentException("Unknown format key: " + e.getKey());
for (Map.Entry<String, String> e : preferences.rawMap.entrySet()) {
if (!"scan".equalsIgnoreCase(e.getValue())) count++;
}
if (force || count >= FormatPreferences.KEYS.size()) return new FormatPreferences(preferences, "\t", false);
if (force || count >= FormatPreferences.KEYS.size()) return preferences;
return null;
}
public FormatPreferences scan(Map<String, String> preferences, final CharSequence source) {
public FormatPreferences scan(FormatPreferences preferences, final CharSequence source) {
FormatPreferences fps = tryEasy(preferences, source == null);
if (fps != null) return fps;
@@ -75,7 +74,7 @@ public class FormatPreferenceScanner {
}
}
public FormatPreferences scan(Map<String, String> preferences, char[] source) {
public FormatPreferences scan(FormatPreferences preferences, char[] source) {
FormatPreferences fps = tryEasy(preferences, source == null);
if (fps != null) return fps;
@@ -86,14 +85,14 @@ public class FormatPreferenceScanner {
}
}
public FormatPreferences scan(Map<String, String> preferences, Reader in) throws IOException {
public FormatPreferences scan(FormatPreferences preferences, Reader in) throws IOException {
FormatPreferences fps = tryEasy(preferences, in == null);
if (fps != null) return fps;
return scan_(preferences, in);
}
private static FormatPreferences scan_(Map<String, String> preferences, Reader in) throws IOException {
private static FormatPreferences scan_(FormatPreferences preferences, Reader in) throws IOException {
int filledEmpties = 0;
List<String> indents = new ArrayList<String>();
@@ -188,6 +187,6 @@ public class FormatPreferenceScanner {
indent = new String(id);
}
return new FormatPreferences(preferences, indent, filledEmpties > 0);
return new FormatPreferences(preferences.rawMap, indent, filledEmpties > 0);
}
}
@@ -29,16 +29,23 @@ import java.util.Map;
public final class FormatPreferences {
private final String indent;
private final Boolean filledEmpties;
private final boolean generateSuppressWarnings;
private final boolean generateFinalParams;
private final boolean generateConstructorProperties;
private final boolean generateSuppressWarnings, danceAroundIdeChecks, generateDelombokComment, javaLangAsFqn;
final Map<String, String> rawMap;
static final Map<String, String> KEYS;
static {
Map<String, String> keys = new LinkedHashMap<String, String>();
keys.put("indent", "The indent to use. 'tab' can be used to represent 1 tab. A number means that many spaces. Default: 'tab'");
keys.put("emptyLines", "Either 'indent' or 'blank'. indent means: Indent an empty line to the right level. Default: 'blank'");
keys.put("suppressWarnings", "Either 'generate' or 'skip'. generate means: All lombok-generated methods get a @SuppressWarnings annotation. Default: 'generate'");
keys.put("finalParams", "Either 'generate' or 'skip'. generate means: All lombok-generated methods set all parameters to final. Default: 'generate'");
keys.put("constructorProperties", "Either 'generate' or 'skip'. generate means: All lombok-generated constructors with 1 or more arguments get an @ConstructorProperties annotation. Default: 'generate'");
keys.put("suppressWarnings", "Either 'generate' or 'skip'. generate means: All lombok-generated methods get a @SuppressWarnings annotation. Default: 'generate'");
keys.put("danceAroundIdeChecks", "Either 'generate' or 'skip'. generate means: Lombok will intentionally obfuscate some generated code to avoid IDE warnings. Default: 'generate'");
keys.put("generateDelombokComment", "Either 'generate' or 'skip'. generate means: Any file modified by delombok will have a comment stating this at the top. Default: 'generate'");
keys.put("javaLangAsFQN", "Either 'generate' or 'skip'. generate means: Any generated reference to java.lang classes are prefixed with `java.lang.`. Default: 'generate'");
KEYS = Collections.unmodifiableMap(keys);
}
@@ -47,6 +54,7 @@ public final class FormatPreferences {
}
public FormatPreferences(Map<String, String> preferences, String indent, Boolean filledEmpties) {
this.rawMap = preferences;
if (preferences == null) preferences = Collections.emptyMap();
String indent_ = preferences.get("indent");
@@ -61,7 +69,7 @@ public final class FormatPreferences {
} catch (NumberFormatException ignore) {}
indent = indent_.replace("\\t", "\t").replace("tab", "\t");
}
String empties_ = preferences.get("emptyLines");
String empties_ = preferences.get("emptyLines".toLowerCase());
if ("indent".equalsIgnoreCase(empties_)) filledEmpties = true;
else if ("blank".equalsIgnoreCase(empties_)) filledEmpties = false;
else if (empties_ != null && !"scan".equalsIgnoreCase(empties_)) {
@@ -71,23 +79,20 @@ public final class FormatPreferences {
this.indent = indent;
this.filledEmpties = filledEmpties;
String generateFinalParams_ = preferences.get("finalParams");
if (generateFinalParams_ == null || "generate".equalsIgnoreCase(generateFinalParams_)) {
this.generateFinalParams = true;
} else if ("skip".equalsIgnoreCase(generateFinalParams_)) {
this.generateFinalParams = false;
} else {
throw new IllegalArgumentException("Legal values for 'finalParams' are 'generate', or 'skip'.");
}
String generateSuppressWarnings_ = preferences.get("suppressWarnings");
if (generateSuppressWarnings_ == null || "generate".equalsIgnoreCase(generateSuppressWarnings_)) {
this.generateSuppressWarnings = true;
} else if ("skip".equalsIgnoreCase(generateSuppressWarnings_)) {
this.generateSuppressWarnings = false;
} else {
throw new IllegalArgumentException("Legal values for 'suppressWarnings' are 'generate', or 'skip'.");
}
this.generateFinalParams = unrollBoolean(preferences, "finalParams", "generate", "skip", true);
this.generateConstructorProperties = unrollBoolean(preferences, "constructorProperties", "generate", "skip", true);
this.generateSuppressWarnings = unrollBoolean(preferences, "suppressWarnings", "generate", "skip", true);
this.danceAroundIdeChecks = unrollBoolean(preferences, "danceAroundIdeChecks", "generate", "skip", true);
this.generateDelombokComment = unrollBoolean(preferences, "generateDelombokComment", "generate", "skip", true);
this.javaLangAsFqn = unrollBoolean(preferences, "javaLangAsFQN", "generate", "skip", true);
}
private static boolean unrollBoolean(Map<String, String> preferences, String name, String trueStr, String falseStr, boolean defaultVal) {
String v_ = preferences.get(name.toLowerCase());
if (v_ == null) return defaultVal;
if (trueStr.equalsIgnoreCase(v_)) return true;
if (falseStr.equalsIgnoreCase(v_)) return false;
throw new IllegalArgumentException("Legal values for '" + name + "' are '" + trueStr + "', or '" + falseStr + "'.");
}
public static Map<String, String> getKeysAndDescriptions() {
@@ -110,4 +115,20 @@ public final class FormatPreferences {
public boolean generateFinalParams() {
return generateFinalParams;
}
public boolean danceAroundIdeChecks() {
return danceAroundIdeChecks;
}
public boolean generateDelombokComment() {
return generateDelombokComment;
}
public boolean javaLangAsFqn() {
return javaLangAsFqn;
}
public boolean generateConstructorProperties() {
return generateConstructorProperties;
}
}