diff options
Diffstat (limited to 'src/lombok/eclipse')
18 files changed, 717 insertions, 723 deletions
diff --git a/src/lombok/eclipse/Eclipse.java b/src/lombok/eclipse/Eclipse.java index c96c9ce6..91c7a9f5 100644 --- a/src/lombok/eclipse/Eclipse.java +++ b/src/lombok/eclipse/Eclipse.java @@ -36,7 +36,6 @@ import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import lombok.core.AST.Kind; import lombok.core.AnnotationValues.AnnotationValue; -import lombok.eclipse.EclipseAST.Node; import org.eclipse.core.runtime.ILog; import org.eclipse.core.runtime.IStatus; @@ -107,7 +106,7 @@ public class Eclipse { */ public static void error(CompilationUnitDeclaration cud, String message, String bundleName, Throwable error) { Bundle bundle = Platform.getBundle(bundleName); - if ( bundle == null ) { + if (bundle == null) { System.err.printf("Can't find bundle %s while trying to report error:\n%s\n", bundleName, message); return; } @@ -115,7 +114,7 @@ public class Eclipse { ILog log = Platform.getLog(bundle); log.log(new Status(IStatus.ERROR, bundleName, message, error)); - if ( cud != null ) EclipseAST.addProblemToCompilationResult(cud, false, message + " - See error log.", 0, 0); + if (cud != null) EclipseAST.addProblemToCompilationResult(cud, false, message + " - See error log.", 0, 0); } /** @@ -125,7 +124,7 @@ public class Eclipse { public static String toQualifiedName(char[][] typeName) { StringBuilder sb = new StringBuilder(); boolean first = true; - for ( char[] c : typeName ) { + for (char[] c : typeName) { sb.append(first ? "" : ".").append(c); first = false; } @@ -148,10 +147,10 @@ public class Eclipse { * is complicated and there's no clone method on TypeParameter itself. This method can clone them. */ public static TypeParameter[] copyTypeParams(TypeParameter[] params, ASTNode source) { - if ( params == null ) return null; + if (params == null) return null; TypeParameter[] out = new TypeParameter[params.length]; int idx = 0; - for ( TypeParameter param : params ) { + for (TypeParameter param : params) { TypeParameter o = new TypeParameter(); setGeneratedBy(o, source); o.annotations = param.annotations; @@ -164,10 +163,10 @@ public class Eclipse { o.declarationEnd = param.declarationEnd; o.declarationSourceStart = param.declarationSourceStart; o.declarationSourceEnd = param.declarationSourceEnd; - if ( param.bounds != null ) { + if (param.bounds != null) { TypeReference[] b = new TypeReference[param.bounds.length]; int idx2 = 0; - for ( TypeReference ref : param.bounds ) b[idx2++] = copyType(ref, source); + for (TypeReference ref : param.bounds) b[idx2++] = copyType(ref, source); o.bounds = b; } out[idx++] = o; @@ -180,10 +179,10 @@ public class Eclipse { * {@link #copyType(TypeReference)}. */ public static TypeReference[] copyTypes(TypeReference[] refs, ASTNode source) { - if ( refs == null ) return null; + if (refs == null) return null; TypeReference[] outs = new TypeReference[refs.length]; int idx = 0; - for ( TypeReference ref : refs ) { + for (TypeReference ref : refs) { outs[idx++] = copyType(ref, source); } return outs; @@ -195,18 +194,18 @@ public class Eclipse { * method on TypeReference itself. This method can clone them. */ public static TypeReference copyType(TypeReference ref, ASTNode source) { - if ( ref instanceof ParameterizedQualifiedTypeReference ) { + if (ref instanceof ParameterizedQualifiedTypeReference) { ParameterizedQualifiedTypeReference iRef = (ParameterizedQualifiedTypeReference) ref; TypeReference[][] args = null; - if ( iRef.typeArguments != null ) { + if (iRef.typeArguments != null) { args = new TypeReference[iRef.typeArguments.length][]; int idx = 0; - for ( TypeReference[] inRefArray : iRef.typeArguments ) { - if ( inRefArray == null ) args[idx++] = null; + for (TypeReference[] inRefArray : iRef.typeArguments) { + if (inRefArray == null) args[idx++] = null; else { TypeReference[] outRefArray = new TypeReference[inRefArray.length]; int idx2 = 0; - for ( TypeReference inRef : inRefArray ) { + for (TypeReference inRef : inRefArray) { outRefArray[idx2++] = copyType(inRef, source); } args[idx++] = outRefArray; @@ -218,28 +217,28 @@ public class Eclipse { return typeRef; } - if ( ref instanceof ArrayQualifiedTypeReference ) { + if (ref instanceof ArrayQualifiedTypeReference) { ArrayQualifiedTypeReference iRef = (ArrayQualifiedTypeReference) ref; TypeReference typeRef = new ArrayQualifiedTypeReference(iRef.tokens, iRef.dimensions(), iRef.sourcePositions); setGeneratedBy(typeRef, source); return typeRef; } - if ( ref instanceof QualifiedTypeReference ) { + if (ref instanceof QualifiedTypeReference) { QualifiedTypeReference iRef = (QualifiedTypeReference) ref; TypeReference typeRef = new QualifiedTypeReference(iRef.tokens, iRef.sourcePositions); setGeneratedBy(typeRef, source); return typeRef; } - if ( ref instanceof ParameterizedSingleTypeReference ) { + if (ref instanceof ParameterizedSingleTypeReference) { ParameterizedSingleTypeReference iRef = (ParameterizedSingleTypeReference) ref; TypeReference[] args = null; - if ( iRef.typeArguments != null ) { + if (iRef.typeArguments != null) { args = new TypeReference[iRef.typeArguments.length]; int idx = 0; - for ( TypeReference inRef : iRef.typeArguments ) { - if ( inRef == null ) args[idx++] = null; + for (TypeReference inRef : iRef.typeArguments) { + if (inRef == null) args[idx++] = null; else args[idx++] = copyType(inRef, source); } } @@ -249,14 +248,14 @@ public class Eclipse { return typeRef; } - if ( ref instanceof ArrayTypeReference ) { + if (ref instanceof ArrayTypeReference) { ArrayTypeReference iRef = (ArrayTypeReference) ref; TypeReference typeRef = new ArrayTypeReference(iRef.token, iRef.dimensions(), (long)iRef.sourceStart << 32 | iRef.sourceEnd); setGeneratedBy(typeRef, source); return typeRef; } - if ( ref instanceof Wildcard ) { + if (ref instanceof Wildcard) { Wildcard wildcard = new Wildcard(((Wildcard)ref).kind); wildcard.sourceStart = ref.sourceStart; wildcard.sourceEnd = ref.sourceEnd; @@ -264,7 +263,7 @@ public class Eclipse { return wildcard; } - if ( ref instanceof SingleTypeReference ) { + if (ref instanceof SingleTypeReference) { SingleTypeReference iRef = (SingleTypeReference) ref; TypeReference typeRef = new SingleTypeReference(iRef.token, (long)iRef.sourceStart << 32 | iRef.sourceEnd); setGeneratedBy(typeRef, source); @@ -284,10 +283,10 @@ public class Eclipse { if (annotations2 == null) annotations2 = new Annotation[0]; Annotation[] outs = new Annotation[annotations1.length + annotations2.length]; int idx = 0; - for ( Annotation annotation : annotations1 ) { + for (Annotation annotation : annotations1) { outs[idx++] = copyAnnotation(annotation, source); } - for ( Annotation annotation : annotations2 ) { + for (Annotation annotation : annotations2) { outs[idx++] = copyAnnotation(annotation, source); } return outs; @@ -328,10 +327,10 @@ public class Eclipse { * * This is a guess, but a decent one. */ - public static boolean annotationTypeMatches(Class<? extends java.lang.annotation.Annotation> type, Node node) { - if ( node.getKind() != Kind.ANNOTATION ) return false; + public static boolean annotationTypeMatches(Class<? extends java.lang.annotation.Annotation> type, EclipseNode node) { + if (node.getKind() != Kind.ANNOTATION) return false; TypeReference typeRef = ((Annotation)node.get()).type; - if ( typeRef == null || typeRef.getTypeName() == null ) return false; + if (typeRef == null || typeRef.getTypeName() == null) return false; String typeName = toQualifiedName(typeRef.getTypeName()); TypeLibrary library = new TypeLibrary(); @@ -339,8 +338,8 @@ public class Eclipse { TypeResolver resolver = new TypeResolver(library, node.getPackageDeclaration(), node.getImportStatements()); Collection<String> typeMatches = resolver.findTypeMatches(node, typeName); - for ( String match : typeMatches ) { - if ( match.equals(type.getName()) ) return true; + for (String match : typeMatches) { + if (match.equals(type.getName())) return true; } return false; @@ -350,32 +349,32 @@ public class Eclipse { * Provides AnnotationValues with the data it needs to do its thing. */ public static <A extends java.lang.annotation.Annotation> AnnotationValues<A> - createAnnotation(Class<A> type, final Node annotationNode) { + createAnnotation(Class<A> type, final EclipseNode annotationNode) { final Annotation annotation = (Annotation) annotationNode.get(); Map<String, AnnotationValue> values = new HashMap<String, AnnotationValue>(); final MemberValuePair[] pairs = annotation.memberValuePairs(); - for ( Method m : type.getDeclaredMethods() ) { - if ( !Modifier.isPublic(m.getModifiers()) ) continue; + for (Method m : type.getDeclaredMethods()) { + if (!Modifier.isPublic(m.getModifiers())) continue; String name = m.getName(); List<String> raws = new ArrayList<String>(); List<Object> guesses = new ArrayList<Object>(); Expression fullExpression = null; Expression[] expressions = null; - if ( pairs != null ) for ( MemberValuePair pair : pairs ) { + if (pairs != null) for (MemberValuePair pair : pairs) { char[] n = pair.name; String mName = n == null ? "value" : new String(pair.name); - if ( mName.equals(name) ) fullExpression = pair.value; + if (mName.equals(name)) fullExpression = pair.value; } boolean isExplicit = fullExpression != null; - if ( isExplicit ) { - if ( fullExpression instanceof ArrayInitializer ) { + if (isExplicit) { + if (fullExpression instanceof ArrayInitializer) { expressions = ((ArrayInitializer)fullExpression).expressions; } else expressions = new Expression[] { fullExpression }; - if ( expressions != null ) for ( Expression ex : expressions ) { + if (expressions != null) for (Expression ex : expressions) { StringBuffer sb = new StringBuffer(); ex.print(0, sb); raws.add(sb.toString()); @@ -389,10 +388,10 @@ public class Eclipse { values.put(name, new AnnotationValue(annotationNode, raws, guesses, isExplicit) { @Override public void setError(String message, int valueIdx) { Expression ex; - if ( valueIdx == -1 ) ex = fullExpr; + if (valueIdx == -1) ex = fullExpr; else ex = exprs != null ? exprs[valueIdx] : null; - if ( ex == null ) ex = annotation; + if (ex == null) ex = annotation; int sourceStart = ex.sourceStart; int sourceEnd = ex.sourceEnd; @@ -402,10 +401,10 @@ public class Eclipse { @Override public void setWarning(String message, int valueIdx) { Expression ex; - if ( valueIdx == -1 ) ex = fullExpr; + if (valueIdx == -1) ex = fullExpr; else ex = exprs != null ? exprs[valueIdx] : null; - if ( ex == null ) ex = annotation; + if (ex == null) ex = annotation; int sourceStart = ex.sourceStart; int sourceEnd = ex.sourceEnd; @@ -419,9 +418,9 @@ public class Eclipse { } private static Object calculateValue(Expression e) { - if ( e instanceof Literal ) { + if (e instanceof Literal) { ((Literal)e).computeConstant(); - switch ( e.constant.typeID() ) { + switch (e.constant.typeID()) { case TypeIds.T_int: return e.constant.intValue(); case TypeIds.T_byte: return e.constant.byteValue(); case TypeIds.T_short: return e.constant.shortValue(); @@ -433,11 +432,11 @@ public class Eclipse { case TypeIds.T_JavaLangString: return e.constant.stringValue(); default: return null; } - } else if ( e instanceof ClassLiteralAccess ) { + } else if (e instanceof ClassLiteralAccess) { return Eclipse.toQualifiedName(((ClassLiteralAccess)e).type.getTypeName()); - } else if ( e instanceof SingleNameReference ) { + } else if (e instanceof SingleNameReference) { return new String(((SingleNameReference)e).token); - } else if ( e instanceof QualifiedNameReference ) { + } else if (e instanceof QualifiedNameReference) { String qName = Eclipse.toQualifiedName(((QualifiedNameReference)e).tokens); int idx = qName.lastIndexOf('.'); return idx == -1 ? qName : qName.substring(idx+1); @@ -451,7 +450,7 @@ public class Eclipse { static { try { generatedByField = ASTNode.class.getDeclaredField("$generatedBy"); - } catch ( Throwable t ) { + } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } @@ -459,7 +458,7 @@ public class Eclipse { public static ASTNode getGeneratedBy(ASTNode node) { try { return (ASTNode) generatedByField.get(node); - } catch ( Exception t ) { + } catch (Exception t) { throw Lombok.sneakyThrow(t); } } @@ -471,7 +470,7 @@ public class Eclipse { public static ASTNode setGeneratedBy(ASTNode node, ASTNode source) { try { generatedByField.set(node, source); - } catch ( Exception t ) { + } catch (Exception t) { throw Lombok.sneakyThrow(t); } diff --git a/src/lombok/eclipse/EclipseAST.java b/src/lombok/eclipse/EclipseAST.java index b70e2db6..e42e5de2 100644 --- a/src/lombok/eclipse/EclipseAST.java +++ b/src/lombok/eclipse/EclipseAST.java @@ -34,7 +34,6 @@ import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; -import org.eclipse.jdt.internal.compiler.ast.Clinit; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; import org.eclipse.jdt.internal.compiler.ast.ImportReference; @@ -50,7 +49,7 @@ import org.eclipse.jdt.internal.compiler.util.Util; * Wraps around Eclipse's internal AST view to add useful features as well as the ability to visit parents from children, * something Eclipse own AST system does not offer. */ -public class EclipseAST extends AST<ASTNode> { +public class EclipseAST extends AST<EclipseAST, EclipseNode, ASTNode> { /** * Creates a new EclipseAST of the provided Compilation Unit. * @@ -74,9 +73,9 @@ public class EclipseAST extends AST<ASTNode> { @Override public Collection<String> getImportStatements() { List<String> imports = new ArrayList<String>(); CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); - if ( cud.imports == null ) return imports; - for ( ImportReference imp : cud.imports ) { - if ( imp == null ) continue; + if (cud.imports == null) return imports; + for (ImportReference imp : cud.imports) { + if (imp == null) continue; imports.add(Eclipse.toQualifiedName(imp.getImportName())); } @@ -91,8 +90,8 @@ public class EclipseAST extends AST<ASTNode> { top().traverse(visitor); } - private void traverseChildren(EclipseASTVisitor visitor, Node node) { - for ( Node child : node.down() ) { + void traverseChildren(EclipseASTVisitor visitor, EclipseNode node) { + for (EclipseNode child : node.down()) { child.traverse(visitor); } } @@ -108,17 +107,7 @@ public class EclipseAST extends AST<ASTNode> { return completeParse; } - /** {@inheritDoc} */ - @Override public Node top() { - return (Node) super.top(); - } - - /** {@inheritDoc} */ - @Override public Node get(ASTNode node) { - return (Node) super.get(node); - } - - private class ParseProblem { + class ParseProblem { final boolean isWarning; final String message; final int sourceStart; @@ -138,16 +127,16 @@ public class EclipseAST extends AST<ASTNode> { } private void propagateProblems() { - if ( queuedProblems.isEmpty() ) return; + if (queuedProblems.isEmpty()) return; CompilationUnitDeclaration cud = (CompilationUnitDeclaration) top().get(); - if ( cud.compilationResult == null ) return; - for ( ParseProblem problem : queuedProblems ) problem.addToCompilationResult(); + if (cud.compilationResult == null) return; + for (ParseProblem problem : queuedProblems) problem.addToCompilationResult(); queuedProblems.clear(); } private final List<ParseProblem> queuedProblems = new ArrayList<ParseProblem>(); - private void addProblem(ParseProblem problem) { + void addProblem(ParseProblem problem) { queuedProblems.add(problem); propagateProblems(); } @@ -158,9 +147,9 @@ public class EclipseAST extends AST<ASTNode> { */ static void addProblemToCompilationResult(CompilationUnitDeclaration ast, boolean isWarning, String message, int sourceStart, int sourceEnd) { - if ( ast.compilationResult == null ) return; + if (ast.compilationResult == null) return; char[] fileNameArray = ast.getFileName(); - if ( fileNameArray == null ) fileNameArray = "(unknown).java".toCharArray(); + if (fileNameArray == null) fileNameArray = "(unknown).java".toCharArray(); int lineNumber = 0; int columnNumber = 1; CompilationResult result = ast.compilationResult; @@ -197,171 +186,6 @@ public class EclipseAST extends AST<ASTNode> { } } - /** - * Eclipse specific version of the AST.Node class. - */ - public final class Node extends AST<ASTNode>.Node { - /** - * See the {@link AST.Node} constructor for information. - */ - Node(ASTNode node, List<Node> children, Kind kind) { - super(node, children, kind); - } - - /** - * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. - */ - public void traverse(EclipseASTVisitor visitor) { - switch ( getKind() ) { - case COMPILATION_UNIT: - visitor.visitCompilationUnit(this, (CompilationUnitDeclaration)get()); - traverseChildren(visitor, this); - visitor.endVisitCompilationUnit(this, (CompilationUnitDeclaration)get()); - break; - case TYPE: - visitor.visitType(this, (TypeDeclaration)get()); - traverseChildren(visitor, this); - visitor.endVisitType(this, (TypeDeclaration)get()); - break; - case FIELD: - visitor.visitField(this, (FieldDeclaration)get()); - traverseChildren(visitor, this); - visitor.endVisitField(this, (FieldDeclaration)get()); - break; - case INITIALIZER: - visitor.visitInitializer(this, (Initializer)get()); - traverseChildren(visitor, this); - visitor.endVisitInitializer(this, (Initializer)get()); - break; - case METHOD: - if ( get() instanceof Clinit ) return; - visitor.visitMethod(this, (AbstractMethodDeclaration)get()); - traverseChildren(visitor, this); - visitor.endVisitMethod(this, (AbstractMethodDeclaration)get()); - break; - case ARGUMENT: - AbstractMethodDeclaration method = (AbstractMethodDeclaration)up().get(); - visitor.visitMethodArgument(this, (Argument)get(), method); - traverseChildren(visitor, this); - visitor.endVisitMethodArgument(this, (Argument)get(), method); - break; - case LOCAL: - visitor.visitLocal(this, (LocalDeclaration)get()); - traverseChildren(visitor, this); - visitor.endVisitLocal(this, (LocalDeclaration)get()); - break; - case ANNOTATION: - switch ( up().getKind() ) { - case TYPE: - visitor.visitAnnotationOnType((TypeDeclaration)up().get(), this, (Annotation)get()); - break; - case FIELD: - visitor.visitAnnotationOnField((FieldDeclaration)up().get(), this, (Annotation)get()); - break; - case METHOD: - visitor.visitAnnotationOnMethod((AbstractMethodDeclaration)up().get(), this, (Annotation)get()); - break; - case ARGUMENT: - visitor.visitAnnotationOnMethodArgument( - (Argument)parent.get(), - (AbstractMethodDeclaration)parent.directUp().get(), - this, (Annotation)get()); - break; - case LOCAL: - visitor.visitAnnotationOnLocal((LocalDeclaration)parent.get(), this, (Annotation)get()); - break; - default: - throw new AssertionError("Annotion not expected as child of a " + up().getKind()); - } - break; - case STATEMENT: - visitor.visitStatement(this, (Statement)get()); - traverseChildren(visitor, this); - visitor.endVisitStatement(this, (Statement)get()); - break; - default: - throw new AssertionError("Unexpected kind during node traversal: " + getKind()); - } - } - - /** {@inheritDoc} */ - @Override public String getName() { - final char[] n; - if ( node instanceof TypeDeclaration ) n = ((TypeDeclaration)node).name; - else if ( node instanceof FieldDeclaration ) n = ((FieldDeclaration)node).name; - else if ( node instanceof AbstractMethodDeclaration ) n = ((AbstractMethodDeclaration)node).selector; - else if ( node instanceof LocalDeclaration ) n = ((LocalDeclaration)node).name; - else n = null; - - return n == null ? null : new String(n); - } - - /** {@inheritDoc} */ - @Override public void addError(String message) { - this.addError(message, this.get().sourceStart, this.get().sourceEnd); - } - - /** Generate a compiler error that shows the wavy underline from-to the stated character positions. */ - public void addError(String message, int sourceStart, int sourceEnd) { - addProblem(new ParseProblem(false, message, sourceStart, sourceEnd)); - } - - /** {@inheritDoc} */ - @Override public void addWarning(String message) { - this.addWarning(message, this.get().sourceStart, this.get().sourceEnd); - } - - /** Generate a compiler warning that shows the wavy underline from-to the stated character positions. */ - public void addWarning(String message, int sourceStart, int sourceEnd) { - addProblem(new ParseProblem(true, message, sourceStart, sourceEnd)); - } - - /** {@inheritDoc} */ - @Override public Node up() { - return (Node) super.up(); - } - - /** {@inheritDoc} */ - @Override protected boolean calculateIsStructurallySignificant() { - if ( node instanceof TypeDeclaration ) return true; - if ( node instanceof AbstractMethodDeclaration ) return true; - if ( node instanceof FieldDeclaration ) return true; - if ( node instanceof LocalDeclaration ) return true; - if ( node instanceof CompilationUnitDeclaration ) return true; - return false; - } - - /** {@inheritDoc} */ - @Override public Node getNodeFor(ASTNode obj) { - return (Node) super.getNodeFor(obj); - } - - /** {@inheritDoc} */ - public Node directUp() { - return (Node) super.directUp(); - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override public Collection<Node> down() { - return (Collection<Node>) super.down(); - } - - /** {@inheritDoc} */ - @Override public Node top() { - return (Node) super.top(); - } - - /** - * Convenient shortcut to the owning EclipseAST object's isCompleteParse method. - * - * @see EclipseAST#isCompleteParse() - */ - public boolean isCompleteParse() { - return completeParse; - } - } - private final CompilationUnitDeclaration compilationUnitDeclaration; private boolean completeParse; @@ -370,15 +194,15 @@ public class EclipseAST extends AST<ASTNode> { } /** - * Call to move an EclipseAST generated for a diet parse to rebuild itself for the full parse - + * Call this method to move an EclipseAST generated for a diet parse to rebuild itself for the full parse - * with filled in method bodies and such. Also propagates problems and errors, which in diet parse * mode can't be reliably added to the problems/warnings view. */ public void reparse() { propagateProblems(); - if ( completeParse ) return; + if (completeParse) return; boolean newCompleteParse = isComplete(compilationUnitDeclaration); - if ( !newCompleteParse ) return; + if (!newCompleteParse) return; top().rebuild(); @@ -390,8 +214,8 @@ public class EclipseAST extends AST<ASTNode> { } /** {@inheritDoc} */ - @Override protected Node buildTree(ASTNode node, Kind kind) { - switch ( kind ) { + @Override protected EclipseNode buildTree(ASTNode node, Kind kind) { + switch (kind) { case COMPILATION_UNIT: return buildCompilationUnit((CompilationUnitDeclaration) node); case TYPE: @@ -415,126 +239,126 @@ public class EclipseAST extends AST<ASTNode> { } } - private Node buildCompilationUnit(CompilationUnitDeclaration top) { - if ( setAndGetAsHandled(top) ) return null; - List<Node> children = buildTypes(top.types); - return putInMap(new Node(top, children, Kind.COMPILATION_UNIT)); + private EclipseNode buildCompilationUnit(CompilationUnitDeclaration top) { + if (setAndGetAsHandled(top)) return null; + List<EclipseNode> children = buildTypes(top.types); + return putInMap(new EclipseNode(this, top, children, Kind.COMPILATION_UNIT)); } - private void addIfNotNull(Collection<Node> collection, Node n) { - if ( n != null ) collection.add(n); + private void addIfNotNull(Collection<EclipseNode> collection, EclipseNode n) { + if (n != null) collection.add(n); } - private List<Node> buildTypes(TypeDeclaration[] children) { - List<Node> childNodes = new ArrayList<Node>(); - if ( children != null ) for ( TypeDeclaration type : children ) addIfNotNull(childNodes, buildType(type)); + private List<EclipseNode> buildTypes(TypeDeclaration[] children) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + if (children != null) for (TypeDeclaration type : children) addIfNotNull(childNodes, buildType(type)); return childNodes; } - private Node buildType(TypeDeclaration type) { - if ( setAndGetAsHandled(type) ) return null; - List<Node> childNodes = new ArrayList<Node>(); + private EclipseNode buildType(TypeDeclaration type) { + if (setAndGetAsHandled(type)) return null; + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); childNodes.addAll(buildFields(type.fields)); childNodes.addAll(buildTypes(type.memberTypes)); childNodes.addAll(buildMethods(type.methods)); childNodes.addAll(buildAnnotations(type.annotations)); - return putInMap(new Node(type, childNodes, Kind.TYPE)); + return putInMap(new EclipseNode(this, type, childNodes, Kind.TYPE)); } - private Collection<Node> buildFields(FieldDeclaration[] children) { - List<Node> childNodes = new ArrayList<Node>(); - if ( children != null ) for ( FieldDeclaration child : children ) addIfNotNull(childNodes, buildField(child)); + private Collection<EclipseNode> buildFields(FieldDeclaration[] children) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + if (children != null) for (FieldDeclaration child : children) addIfNotNull(childNodes, buildField(child)); return childNodes; } private static <T> List<T> singleton(T item) { List<T> list = new ArrayList<T>(); - if ( item != null ) list.add(item); + if (item != null) list.add(item); return list; } - private Node buildField(FieldDeclaration field) { - if ( field instanceof Initializer ) return buildInitializer((Initializer)field); - if ( setAndGetAsHandled(field) ) return null; - List<Node> childNodes = new ArrayList<Node>(); + private EclipseNode buildField(FieldDeclaration field) { + if (field instanceof Initializer) return buildInitializer((Initializer)field); + if (setAndGetAsHandled(field)) return null; + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); addIfNotNull(childNodes, buildStatement(field.initialization)); childNodes.addAll(buildAnnotations(field.annotations)); - return putInMap(new Node(field, childNodes, Kind.FIELD)); + return putInMap(new EclipseNode(this, field, childNodes, Kind.FIELD)); } - private Node buildInitializer(Initializer initializer) { - if ( setAndGetAsHandled(initializer) ) return null; - return putInMap(new Node(initializer, singleton(buildStatement(initializer.block)), Kind.INITIALIZER)); + private EclipseNode buildInitializer(Initializer initializer) { + if (setAndGetAsHandled(initializer)) return null; + return putInMap(new EclipseNode(this, initializer, singleton(buildStatement(initializer.block)), Kind.INITIALIZER)); } - private Collection<Node> buildMethods(AbstractMethodDeclaration[] children) { - List<Node> childNodes = new ArrayList<Node>(); - if ( children != null ) for (AbstractMethodDeclaration method : children ) addIfNotNull(childNodes, buildMethod(method)); + private Collection<EclipseNode> buildMethods(AbstractMethodDeclaration[] children) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + if (children != null) for (AbstractMethodDeclaration method : children) addIfNotNull(childNodes, buildMethod(method)); return childNodes; } - private Node buildMethod(AbstractMethodDeclaration method) { - if ( setAndGetAsHandled(method) ) return null; - List<Node> childNodes = new ArrayList<Node>(); + private EclipseNode buildMethod(AbstractMethodDeclaration method) { + if (setAndGetAsHandled(method)) return null; + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); childNodes.addAll(buildArguments(method.arguments)); childNodes.addAll(buildStatements(method.statements)); childNodes.addAll(buildAnnotations(method.annotations)); - return putInMap(new Node(method, childNodes, Kind.METHOD)); + return putInMap(new EclipseNode(this, method, childNodes, Kind.METHOD)); } //Arguments are a kind of LocalDeclaration. They can definitely contain lombok annotations, so we care about them. - private Collection<Node> buildArguments(Argument[] children) { - List<Node> childNodes = new ArrayList<Node>(); - if ( children != null ) for ( LocalDeclaration local : children ) { + private Collection<EclipseNode> buildArguments(Argument[] children) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + if (children != null) for (LocalDeclaration local : children) { addIfNotNull(childNodes, buildLocal(local, Kind.ARGUMENT)); } return childNodes; } - private Node buildLocal(LocalDeclaration local, Kind kind) { - if ( setAndGetAsHandled(local) ) return null; - List<Node> childNodes = new ArrayList<Node>(); + private EclipseNode buildLocal(LocalDeclaration local, Kind kind) { + if (setAndGetAsHandled(local)) return null; + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); addIfNotNull(childNodes, buildStatement(local.initialization)); childNodes.addAll(buildAnnotations(local.annotations)); - return putInMap(new Node(local, childNodes, kind)); + return putInMap(new EclipseNode(this, local, childNodes, kind)); } - private Collection<Node> buildAnnotations(Annotation[] annotations) { - List<Node> elements = new ArrayList<Node>(); - if ( annotations != null ) for ( Annotation an : annotations ) addIfNotNull(elements, buildAnnotation(an)); + private Collection<EclipseNode> buildAnnotations(Annotation[] annotations) { + List<EclipseNode> elements = new ArrayList<EclipseNode>(); + if (annotations != null) for (Annotation an : annotations) addIfNotNull(elements, buildAnnotation(an)); return elements; } - private Node buildAnnotation(Annotation annotation) { - if ( annotation == null ) return null; - if ( setAndGetAsHandled(annotation) ) return null; - return putInMap(new Node(annotation, null, Kind.ANNOTATION)); + private EclipseNode buildAnnotation(Annotation annotation) { + if (annotation == null) return null; + if (setAndGetAsHandled(annotation)) return null; + return putInMap(new EclipseNode(this, annotation, null, Kind.ANNOTATION)); } - private Collection<Node> buildStatements(Statement[] children) { - List<Node> childNodes = new ArrayList<Node>(); - if ( children != null ) for ( Statement child : children ) addIfNotNull(childNodes, buildStatement(child)); + private Collection<EclipseNode> buildStatements(Statement[] children) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + if (children != null) for (Statement child : children) addIfNotNull(childNodes, buildStatement(child)); return childNodes; } - private Node buildStatement(Statement child) { - if ( child == null ) return null; - if ( child instanceof TypeDeclaration ) return buildType((TypeDeclaration)child); + private EclipseNode buildStatement(Statement child) { + if (child == null) return null; + if (child instanceof TypeDeclaration) return buildType((TypeDeclaration)child); - if ( child instanceof LocalDeclaration ) return buildLocal((LocalDeclaration)child, Kind.LOCAL); + if (child instanceof LocalDeclaration) return buildLocal((LocalDeclaration)child, Kind.LOCAL); - if ( setAndGetAsHandled(child) ) return null; + if (setAndGetAsHandled(child)) return null; return drill(child); } - private Node drill(Statement statement) { - List<Node> childNodes = new ArrayList<Node>(); - for ( FieldAccess fa : fieldsOf(statement.getClass()) ) childNodes.addAll(buildWithField(Node.class, statement, fa)); - return putInMap(new Node(statement, childNodes, Kind.STATEMENT)); + private EclipseNode drill(Statement statement) { + List<EclipseNode> childNodes = new ArrayList<EclipseNode>(); + for (FieldAccess fa : fieldsOf(statement.getClass())) childNodes.addAll(buildWithField(EclipseNode.class, statement, fa)); + return putInMap(new EclipseNode(this, statement, childNodes, Kind.STATEMENT)); } - /** For Eclipse, only Statement counts, as Expression is a subclass of it, eventhough this isn't + /** For Eclipse, only Statement counts, as Expression is a subclass of it, even though this isn't * entirely correct according to the JLS spec (only some expressions can be used as statements, not all of them). */ @Override protected Collection<Class<? extends ASTNode>> getStatementTypes() { return Collections.<Class<? extends ASTNode>>singleton(Statement.class); diff --git a/src/lombok/eclipse/EclipseASTAdapter.java b/src/lombok/eclipse/EclipseASTAdapter.java index bb185670..2062619c 100644 --- a/src/lombok/eclipse/EclipseASTAdapter.java +++ b/src/lombok/eclipse/EclipseASTAdapter.java @@ -21,8 +21,6 @@ */ package lombok.eclipse; -import lombok.eclipse.EclipseAST.Node; - import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; @@ -39,65 +37,65 @@ import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; */ public abstract class EclipseASTAdapter implements EclipseASTVisitor { /** {@inheritDoc} */ - public void visitCompilationUnit(Node top, CompilationUnitDeclaration unit) {} + public void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ - public void endVisitCompilationUnit(Node top, CompilationUnitDeclaration unit) {} + public void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit) {} /** {@inheritDoc} */ - public void visitType(Node typeNode, TypeDeclaration type) {} + public void visitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ - public void visitAnnotationOnType(TypeDeclaration type, Node annotationNode, Annotation annotation) {} + public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ - public void endVisitType(Node typeNode, TypeDeclaration type) {} + public void endVisitType(EclipseNode typeNode, TypeDeclaration type) {} /** {@inheritDoc} */ - public void visitInitializer(Node initializerNode, Initializer initializer) {} + public void visitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ - public void endVisitInitializer(Node initializerNode, Initializer initializer) {} + public void endVisitInitializer(EclipseNode initializerNode, Initializer initializer) {} /** {@inheritDoc} */ - public void visitField(Node fieldNode, FieldDeclaration field) {} + public void visitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ - public void visitAnnotationOnField(FieldDeclaration field, Node annotationNode, Annotation annotation) {} + public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ - public void endVisitField(Node fieldNode, FieldDeclaration field) {} + public void endVisitField(EclipseNode fieldNode, FieldDeclaration field) {} /** {@inheritDoc} */ - public void visitMethod(Node methodNode, AbstractMethodDeclaration method) {} + public void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ - public void visitAnnotationOnMethod(AbstractMethodDeclaration method, Node annotationNode, Annotation annotation) {} + public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ - public void endVisitMethod(Node methodNode, AbstractMethodDeclaration method) {} + public void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ - public void visitMethodArgument(Node argNode, Argument arg, AbstractMethodDeclaration method) {} + public void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ - public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, Node annotationNode, Annotation annotation) {} + public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ - public void endVisitMethodArgument(Node argNode, Argument arg, AbstractMethodDeclaration method) {} + public void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method) {} /** {@inheritDoc} */ - public void visitLocal(Node localNode, LocalDeclaration local) {} + public void visitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ - public void visitAnnotationOnLocal(LocalDeclaration local, Node annotationNode, Annotation annotation) {} + public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) {} /** {@inheritDoc} */ - public void endVisitLocal(Node localNode, LocalDeclaration local) {} + public void endVisitLocal(EclipseNode localNode, LocalDeclaration local) {} /** {@inheritDoc} */ - public void visitStatement(Node statementNode, Statement statement) {} + public void visitStatement(EclipseNode statementNode, Statement statement) {} /** {@inheritDoc} */ - public void endVisitStatement(Node statementNode, Statement statement) {} + public void endVisitStatement(EclipseNode statementNode, Statement statement) {} } diff --git a/src/lombok/eclipse/EclipseASTVisitor.java b/src/lombok/eclipse/EclipseASTVisitor.java index 39c785d1..3397e1cc 100644 --- a/src/lombok/eclipse/EclipseASTVisitor.java +++ b/src/lombok/eclipse/EclipseASTVisitor.java @@ -24,8 +24,6 @@ package lombok.eclipse; import java.io.PrintStream; import java.lang.reflect.Modifier; -import lombok.eclipse.EclipseAST.Node; - import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.Annotation; import org.eclipse.jdt.internal.compiler.ast.Argument; @@ -47,15 +45,15 @@ public interface EclipseASTVisitor { /** * Called at the very beginning and end. */ - void visitCompilationUnit(Node top, CompilationUnitDeclaration unit); - void endVisitCompilationUnit(Node top, CompilationUnitDeclaration unit); + void visitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); + void endVisitCompilationUnit(EclipseNode top, CompilationUnitDeclaration unit); /** * Called when visiting a type (a class, interface, annotation, enum, etcetera). */ - void visitType(Node typeNode, TypeDeclaration type); - void visitAnnotationOnType(TypeDeclaration type, Node annotationNode, Annotation annotation); - void endVisitType(Node typeNode, TypeDeclaration type); + void visitType(EclipseNode typeNode, TypeDeclaration type); + void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation); + void endVisitType(EclipseNode typeNode, TypeDeclaration type); /** * Called when visiting a field of a class. @@ -63,46 +61,46 @@ public interface EclipseASTVisitor { * which are a subclass of FieldDeclaration, those do NOT result in a call to this method. They result * in a call to the visitInitializer method. */ - void visitField(Node fieldNode, FieldDeclaration field); - void visitAnnotationOnField(FieldDeclaration field, Node annotationNode, Annotation annotation); - void endVisitField(Node fieldNode, FieldDeclaration field); + void visitField(EclipseNode fieldNode, FieldDeclaration field); + void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation); + void endVisitField(EclipseNode fieldNode, FieldDeclaration field); /** * Called for static and instance initializers. You can tell the difference via the modifier flag on the * ASTNode (8 for static, 0 for not static). The content is in the 'block', not in the 'initialization', * which would always be null for an initializer instance. */ - void visitInitializer(Node initializerNode, Initializer initializer); - void endVisitInitializer(Node initializerNode, Initializer initializer); + void visitInitializer(EclipseNode initializerNode, Initializer initializer); + void endVisitInitializer(EclipseNode initializerNode, Initializer initializer); /** * Called for both methods (MethodDeclaration) and constructors (ConstructorDeclaration), but not for * Clinit objects, which are a vestigial Eclipse thing that never contain anything. Static initializers * show up as 'Initializer', in the visitInitializer method, with modifier bit STATIC set. */ - void visitMethod(Node methodNode, AbstractMethodDeclaration method); - void visitAnnotationOnMethod(AbstractMethodDeclaration method, Node annotationNode, Annotation annotation); - void endVisitMethod(Node methodNode, AbstractMethodDeclaration method); + void visitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); + void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); + void endVisitMethod(EclipseNode methodNode, AbstractMethodDeclaration method); /** * Visits a method argument */ - void visitMethodArgument(Node argNode, Argument arg, AbstractMethodDeclaration method); - void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, Node annotationNode, Annotation annotation); - void endVisitMethodArgument(Node argNode, Argument arg, AbstractMethodDeclaration method); + void visitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); + void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation); + void endVisitMethodArgument(EclipseNode argNode, Argument arg, AbstractMethodDeclaration method); /** * Visits a local declaration - that is, something like 'int x = 10;' on the method level. */ - void visitLocal(Node localNode, LocalDeclaration local); - void visitAnnotationOnLocal(LocalDeclaration local, Node annotationNode, Annotation annotation); - void endVisitLocal(Node localNode, LocalDeclaration local); + void visitLocal(EclipseNode localNode, LocalDeclaration local); + void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation); + void endVisitLocal(EclipseNode localNode, LocalDeclaration local); /** * Visits a statement that isn't any of the other visit methods (e.g. TypeDeclaration). */ - void visitStatement(Node statementNode, Statement statement); - void endVisitStatement(Node statementNode, Statement statement); + void visitStatement(EclipseNode statementNode, Statement statement); + void endVisitStatement(EclipseNode statementNode, Statement statement); /** * Prints the structure of an AST. @@ -135,33 +133,33 @@ public interface EclipseASTVisitor { private void forcePrint(String text, Object... params) { StringBuilder sb = new StringBuilder(); - for ( int i = 0 ; i < indent ; i++ ) sb.append(" "); + for (int i = 0; i < indent; i++) sb.append(" "); out.printf(sb.append(text).append('\n').toString(), params); out.flush(); } private void print(String text, Object... params) { - if ( disablePrinting == 0 ) forcePrint(text, params); + if (disablePrinting == 0) forcePrint(text, params); } private String str(char[] c) { - if ( c == null ) return "(NULL)"; + if (c == null) return "(NULL)"; else return new String(c); } private String str(TypeReference type) { - if ( type == null ) return "(NULL)"; + if (type == null) return "(NULL)"; char[][] c = type.getTypeName(); StringBuilder sb = new StringBuilder(); boolean first = true; - for ( char[] d : c ) { + for (char[] d : c) { sb.append(first ? "" : ".").append(new String(d)); first = false; } return sb.toString(); } - public void visitCompilationUnit(Node node, CompilationUnitDeclaration unit) { + public void visitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { out.println("---------------------------------------------------------"); out.println(node.isCompleteParse() ? "COMPLETE" : "incomplete"); @@ -169,31 +167,31 @@ public interface EclipseASTVisitor { indent++; } - public void endVisitCompilationUnit(Node node, CompilationUnitDeclaration unit) { + public void endVisitCompilationUnit(EclipseNode node, CompilationUnitDeclaration unit) { indent--; print("</CUD>"); } - public void visitType(Node node, TypeDeclaration type) { + public void visitType(EclipseNode node, TypeDeclaration type) { print("<TYPE %s%s>", str(type.name), Eclipse.isGenerated(type) ? " (GENERATED)" : ""); indent++; - if ( printContent ) { + if (printContent) { print("%s", type); disablePrinting++; } } - public void visitAnnotationOnType(TypeDeclaration type, Node node, Annotation annotation) { + public void visitAnnotationOnType(TypeDeclaration type, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); } - public void endVisitType(Node node, TypeDeclaration type) { - if ( printContent ) disablePrinting--; + public void endVisitType(EclipseNode node, TypeDeclaration type) { + if (printContent) disablePrinting--; indent--; print("</TYPE %s>", str(type.name)); } - public void visitInitializer(Node node, Initializer initializer) { + public void visitInitializer(EclipseNode node, Initializer initializer) { Block block = initializer.block; boolean s = (block != null && block.statements != null); print("<%s INITIALIZER: %s%s>", @@ -201,95 +199,95 @@ public interface EclipseASTVisitor { s ? "filled" : "blank", Eclipse.isGenerated(initializer) ? " (GENERATED)" : ""); indent++; - if ( printContent ) { - if ( initializer.block != null ) print("%s", initializer.block); + if (printContent) { + if (initializer.block != null) print("%s", initializer.block); disablePrinting++; } } - public void endVisitInitializer(Node node, Initializer initializer) { - if ( printContent ) disablePrinting--; + public void endVisitInitializer(EclipseNode node, Initializer initializer) { + if (printContent) disablePrinting--; indent--; print("</%s INITIALIZER>", (initializer.modifiers & Modifier.STATIC) != 0 ? "static" : "instance"); } - public void visitField(Node node, FieldDeclaration field) { + public void visitField(EclipseNode node, FieldDeclaration field) { print("<FIELD%s %s %s = %s>", Eclipse.isGenerated(field) ? " (GENERATED)" : "", str(field.type), str(field.name), field.initialization); indent++; - if ( printContent ) { - if ( field.initialization != null ) print("%s", field.initialization); + if (printContent) { + if (field.initialization != null) print("%s", field.initialization); disablePrinting++; } } - public void visitAnnotationOnField(FieldDeclaration field, Node node, Annotation annotation) { + public void visitAnnotationOnField(FieldDeclaration field, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); } - public void endVisitField(Node node, FieldDeclaration field) { - if ( printContent ) disablePrinting--; + public void endVisitField(EclipseNode node, FieldDeclaration field) { + if (printContent) disablePrinting--; indent--; print("</FIELD %s %s>", str(field.type), str(field.name)); } - public void visitMethod(Node node, AbstractMethodDeclaration method) { + public void visitMethod(EclipseNode node, AbstractMethodDeclaration method) { String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; print("<%s %s: %s%s>", type, str(method.selector), method.statements != null ? "filled" : "blank", Eclipse.isGenerated(method) ? " (GENERATED)" : ""); indent++; - if ( printContent ) { - if ( method.statements != null ) print("%s", method); + if (printContent) { + if (method.statements != null) print("%s", method); disablePrinting++; } } - public void visitAnnotationOnMethod(AbstractMethodDeclaration method, Node node, Annotation annotation) { + public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { forcePrint("<ANNOTATION%s: %s />", Eclipse.isGenerated(method) ? " (GENERATED)" : "", annotation); } - public void endVisitMethod(Node node, AbstractMethodDeclaration method) { - if ( printContent ) disablePrinting--; + public void endVisitMethod(EclipseNode node, AbstractMethodDeclaration method) { + if (printContent) disablePrinting--; String type = method instanceof ConstructorDeclaration ? "CONSTRUCTOR" : "METHOD"; indent--; print("</%s %s>", type, str(method.selector)); } - public void visitMethodArgument(Node node, Argument arg, AbstractMethodDeclaration method) { + public void visitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { print("<METHODARG%s %s %s = %s>", Eclipse.isGenerated(arg) ? " (GENERATED)" : "", str(arg.type), str(arg.name), arg.initialization); indent++; } - public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, Node node, Annotation annotation) { + public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode node, Annotation annotation) { print("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); } - public void endVisitMethodArgument(Node node, Argument arg, AbstractMethodDeclaration method) { + public void endVisitMethodArgument(EclipseNode node, Argument arg, AbstractMethodDeclaration method) { indent--; print("</METHODARG %s %s>", str(arg.type), str(arg.name)); } - public void visitLocal(Node node, LocalDeclaration local) { + public void visitLocal(EclipseNode node, LocalDeclaration local) { print("<LOCAL%s %s %s = %s>", Eclipse.isGenerated(local) ? " (GENERATED)" : "", str(local.type), str(local.name), local.initialization); indent++; } - public void visitAnnotationOnLocal(LocalDeclaration local, Node node, Annotation annotation) { + public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode node, Annotation annotation) { print("<ANNOTATION%s: %s />", Eclipse.isGenerated(annotation) ? " (GENERATED)" : "", annotation); } - public void endVisitLocal(Node node, LocalDeclaration local) { + public void endVisitLocal(EclipseNode node, LocalDeclaration local) { indent--; print("</LOCAL %s %s>", str(local.type), str(local.name)); } - public void visitStatement(Node node, Statement statement) { + public void visitStatement(EclipseNode node, Statement statement) { print("<%s%s>", statement.getClass(), Eclipse.isGenerated(statement) ? " (GENERATED)" : ""); indent++; print("%s", statement); } - public void endVisitStatement(Node node, Statement statement) { + public void endVisitStatement(EclipseNode node, Statement statement) { indent--; print("</%s>", statement.getClass()); } diff --git a/src/lombok/eclipse/EclipseAnnotationHandler.java b/src/lombok/eclipse/EclipseAnnotationHandler.java index b5c84ebd..96626cca 100644 --- a/src/lombok/eclipse/EclipseAnnotationHandler.java +++ b/src/lombok/eclipse/EclipseAnnotationHandler.java @@ -50,5 +50,5 @@ public interface EclipseAnnotationHandler<T extends java.lang.annotation.Annotat * @return <code>true</code> if you don't want to be called again about this annotation during this * compile session (you've handled it), or <code>false</code> to indicate you aren't done yet. */ - boolean handle(AnnotationValues<T> annotation, org.eclipse.jdt.internal.compiler.ast.Annotation ast, EclipseAST.Node annotationNode); + boolean handle(AnnotationValues<T> annotation, org.eclipse.jdt.internal.compiler.ast.Annotation ast, EclipseNode annotationNode); } diff --git a/src/lombok/eclipse/EclipseNode.java b/src/lombok/eclipse/EclipseNode.java new file mode 100644 index 00000000..668e6a6e --- /dev/null +++ b/src/lombok/eclipse/EclipseNode.java @@ -0,0 +1,175 @@ +/* + * Copyright © 2009 Reinier Zwitserloot and Roel Spilker. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package lombok.eclipse; + +import java.util.List; + +import lombok.core.AST.Kind; + +import org.eclipse.jdt.internal.compiler.ast.ASTNode; +import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Annotation; +import org.eclipse.jdt.internal.compiler.ast.Argument; +import org.eclipse.jdt.internal.compiler.ast.Clinit; +import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; +import org.eclipse.jdt.internal.compiler.ast.FieldDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Initializer; +import org.eclipse.jdt.internal.compiler.ast.LocalDeclaration; +import org.eclipse.jdt.internal.compiler.ast.Statement; +import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; + +/** + * Eclipse specific version of the LombokNode class. + */ +public class EclipseNode extends lombok.core.LombokNode<EclipseAST, EclipseNode, ASTNode> { + /** {@inheritDoc} */ + EclipseNode(EclipseAST ast, ASTNode node, List<EclipseNode> children, Kind kind) { + super(ast, node, children, kind); + } + + /** + * Visits this node and all child nodes depth-first, calling the provided visitor's visit methods. + */ + public void traverse(EclipseASTVisitor visitor) { + switch (getKind()) { + case COMPILATION_UNIT: + visitor.visitCompilationUnit(this, (CompilationUnitDeclaration)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitCompilationUnit(this, (CompilationUnitDeclaration)get()); + break; + case TYPE: + visitor.visitType(this, (TypeDeclaration)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitType(this, (TypeDeclaration)get()); + break; + case FIELD: + visitor.visitField(this, (FieldDeclaration)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitField(this, (FieldDeclaration)get()); + break; + case INITIALIZER: + visitor.visitInitializer(this, (Initializer)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitInitializer(this, (Initializer)get()); + break; + case METHOD: + if (get() instanceof Clinit) return; + visitor.visitMethod(this, (AbstractMethodDeclaration)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitMethod(this, (AbstractMethodDeclaration)get()); + break; + case ARGUMENT: + AbstractMethodDeclaration method = (AbstractMethodDeclaration)up().get(); + visitor.visitMethodArgument(this, (Argument)get(), method); + ast.traverseChildren(visitor, this); + visitor.endVisitMethodArgument(this, (Argument)get(), method); + break; + case LOCAL: + visitor.visitLocal(this, (LocalDeclaration)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitLocal(this, (LocalDeclaration)get()); + break; + case ANNOTATION: + switch (up().getKind()) { + case TYPE: + visitor.visitAnnotationOnType((TypeDeclaration)up().get(), this, (Annotation)get()); + break; + case FIELD: + visitor.visitAnnotationOnField((FieldDeclaration)up().get(), this, (Annotation)get()); + break; + case METHOD: + visitor.visitAnnotationOnMethod((AbstractMethodDeclaration)up().get(), this, (Annotation)get()); + break; + case ARGUMENT: + visitor.visitAnnotationOnMethodArgument( + (Argument)parent.get(), + (AbstractMethodDeclaration)parent.directUp().get(), + this, (Annotation)get()); + break; + case LOCAL: + visitor.visitAnnotationOnLocal((LocalDeclaration)parent.get(), this, (Annotation)get()); + break; + default: + throw new AssertionError("Annotion not expected as child of a " + up().getKind()); + } + break; + case STATEMENT: + visitor.visitStatement(this, (Statement)get()); + ast.traverseChildren(visitor, this); + visitor.endVisitStatement(this, (Statement)get()); + break; + default: + throw new AssertionError("Unexpected kind during node traversal: " + getKind()); + } + } + + /** {@inheritDoc} */ + @Override public String getName() { + final char[] n; + if (node instanceof TypeDeclaration) n = ((TypeDeclaration)node).name; + else if (node instanceof FieldDeclaration) n = ((FieldDeclaration)node).name; + else if (node instanceof AbstractMethodDeclaration) n = ((AbstractMethodDeclaration)node).selector; + else if (node instanceof LocalDeclaration) n = ((LocalDeclaration)node).name; + else n = null; + + return n == null ? null : new String(n); + } + + /** {@inheritDoc} */ + @Override public void addError(String message) { + this.addError(message, this.get().sourceStart, this.get().sourceEnd); + } + + /** Generate a compiler error that shows the wavy underline from-to the stated character positions. */ + public void addError(String message, int sourceStart, int sourceEnd) { + ast.addProblem(ast.new ParseProblem(false, message, sourceStart, sourceEnd)); + } + + /** {@inheritDoc} */ + @Override public void addWarning(String message) { + this.addWarning(message, this.get().sourceStart, this.get().sourceEnd); + } + + /** Generate a compiler warning that shows the wavy underline from-to the stated character positions. */ + public void addWarning(String message, int sourceStart, int sourceEnd) { + ast.addProblem(ast.new ParseProblem(true, message, sourceStart, sourceEnd)); + } + + /** {@inheritDoc} */ + @Override protected boolean calculateIsStructurallySignificant() { + if (node instanceof TypeDeclaration) return true; + if (node instanceof AbstractMethodDeclaration) return true; + if (node instanceof FieldDeclaration) return true; + if (node instanceof LocalDeclaration) return true; + if (node instanceof CompilationUnitDeclaration) return true; + return false; + } + + /** + * Convenient shortcut to the owning EclipseAST object's isCompleteParse method. + * + * @see EclipseAST#isCompleteParse() + */ + public boolean isCompleteParse() { + return ast.isCompleteParse(); + } +} diff --git a/src/lombok/eclipse/HandlerLibrary.java b/src/lombok/eclipse/HandlerLibrary.java index ed8196f7..be0e0b14 100644 --- a/src/lombok/eclipse/HandlerLibrary.java +++ b/src/lombok/eclipse/HandlerLibrary.java @@ -37,7 +37,6 @@ import lombok.core.SpiLoadUtil; import lombok.core.TypeLibrary; import lombok.core.TypeResolver; import lombok.core.AnnotationValues.AnnotationValueDecodeFail; -import lombok.eclipse.EclipseAST.Node; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; @@ -67,7 +66,7 @@ public class HandlerLibrary { } public boolean handle(org.eclipse.jdt.internal.compiler.ast.Annotation annotation, - final Node annotationNode) { + final EclipseNode annotationNode) { AnnotationValues<T> annValues = Eclipse.createAnnotation(annotationClass, annotationNode); return handler.handle(annValues, annotation, annotationNode); } @@ -110,7 +109,7 @@ public class HandlerLibrary { Eclipse.error(null, "Can't load Lombok annotation handler for Eclipse: ", t); } } - } catch ( IOException e ) { + } catch (IOException e) { Lombok.sneakyThrow(e); } } @@ -121,7 +120,7 @@ public class HandlerLibrary { for (EclipseASTVisitor visitor : SpiLoadUtil.findServices(EclipseASTVisitor.class)) { lib.visitorHandlers.add(visitor); } - } catch ( Throwable t ) { + } catch (Throwable t) { throw Lombok.sneakyThrow(t); } } @@ -143,27 +142,27 @@ public class HandlerLibrary { * @param annotationNode The Lombok AST Node representing the Annotation AST Node. * @param annotation 'node.get()' - convenience parameter. */ - public boolean handle(CompilationUnitDeclaration ast, EclipseAST.Node annotationNode, + public boolean handle(CompilationUnitDeclaration ast, EclipseNode annotationNode, org.eclipse.jdt.internal.compiler.ast.Annotation annotation) { String pkgName = annotationNode.getPackageDeclaration(); Collection<String> imports = annotationNode.getImportStatements(); TypeResolver resolver = new TypeResolver(typeLibrary, pkgName, imports); TypeReference rawType = annotation.type; - if ( rawType == null ) return false; + if (rawType == null) return false; boolean handled = false; - for ( String fqn : resolver.findTypeMatches(annotationNode, toQualifiedName(annotation.type.getTypeName())) ) { + for (String fqn : resolver.findTypeMatches(annotationNode, toQualifiedName(annotation.type.getTypeName()))) { boolean isPrintAST = fqn.equals(PrintAST.class.getName()); - if ( isPrintAST == skipPrintAST ) continue; + if (isPrintAST == skipPrintAST) continue; AnnotationHandlerContainer<?> container = annotationHandlers.get(fqn); - if ( container == null ) continue; + if (container == null) continue; try { handled |= container.handle(annotation, annotationNode); - } catch ( AnnotationValueDecodeFail fail ) { + } catch (AnnotationValueDecodeFail fail) { fail.owner.setError(fail.getMessage(), fail.idx); - } catch ( Throwable t ) { + } catch (Throwable t) { Eclipse.error(ast, String.format("Lombok annotation handler %s failed", container.handler.getClass()), t); } } @@ -175,9 +174,9 @@ public class HandlerLibrary { * Will call all registered {@link EclipseASTVisitor} instances. */ public void callASTVisitors(EclipseAST ast) { - for ( EclipseASTVisitor visitor : visitorHandlers ) try { + for (EclipseASTVisitor visitor : visitorHandlers) try { ast.traverse(visitor); - } catch ( Throwable t ) { + } catch (Throwable t) { Eclipse.error((CompilationUnitDeclaration) ast.top().get(), String.format("Lombok visitor handler %s failed", visitor.getClass()), t); } diff --git a/src/lombok/eclipse/TransformEclipseAST.java b/src/lombok/eclipse/TransformEclipseAST.java index 6eac4196..6c0567c5 100644 --- a/src/lombok/eclipse/TransformEclipseAST.java +++ b/src/lombok/eclipse/TransformEclipseAST.java @@ -23,7 +23,6 @@ package lombok.eclipse; import java.lang.reflect.Field; -import lombok.eclipse.EclipseAST.Node; import lombok.patcher.Symbols; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; @@ -62,10 +61,10 @@ public class TransformEclipseAST { try { l = HandlerLibrary.load(); f = CompilationUnitDeclaration.class.getDeclaredField("$lombokAST"); - } catch ( Throwable t ) { + } catch (Throwable t) { try { Eclipse.error(null, "Problem initializing lombok", t); - } catch ( Throwable t2) { + } catch (Throwable t2) { System.err.println("Problem initializing lombok"); t.printStackTrace(); } @@ -125,19 +124,19 @@ public class TransformEclipseAST { } private static EclipseAST getCache(CompilationUnitDeclaration ast) { - if ( astCacheField == null ) return null; + if (astCacheField == null) return null; try { return (EclipseAST)astCacheField.get(ast); - } catch ( Exception e ) { + } catch (Exception e) { e.printStackTrace(); return null; } } private static void setCache(CompilationUnitDeclaration ast, EclipseAST cache) { - if ( astCacheField != null ) try { + if (astCacheField != null) try { astCacheField.set(ast, cache); - } catch ( Exception ignore ) { + } catch (Exception ignore) { ignore.printStackTrace(); } } @@ -159,39 +158,39 @@ public class TransformEclipseAST { } private static class AnnotationVisitor extends EclipseASTAdapter { - @Override public void visitAnnotationOnField(FieldDeclaration field, Node annotationNode, Annotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnField(FieldDeclaration field, EclipseNode annotationNode, Annotation annotation) { + if (annotationNode.isHandled()) return; CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); boolean handled = handlers.handle(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, Node annotationNode, Annotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnMethodArgument(Argument arg, AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { + if (annotationNode.isHandled()) return; CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); boolean handled = handlers.handle(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnLocal(LocalDeclaration local, Node annotationNode, Annotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnLocal(LocalDeclaration local, EclipseNode annotationNode, Annotation annotation) { + if (annotationNode.isHandled()) return; CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); boolean handled = handlers.handle(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnMethod(AbstractMethodDeclaration method, Node annotationNode, Annotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnMethod(AbstractMethodDeclaration method, EclipseNode annotationNode, Annotation annotation) { + if (annotationNode.isHandled()) return; CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); boolean handled = handlers.handle(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } - @Override public void visitAnnotationOnType(TypeDeclaration type, Node annotationNode, Annotation annotation) { - if ( annotationNode.isHandled() ) return; + @Override public void visitAnnotationOnType(TypeDeclaration type, EclipseNode annotationNode, Annotation annotation) { + if (annotationNode.isHandled()) return; CompilationUnitDeclaration top = (CompilationUnitDeclaration) annotationNode.top().get(); boolean handled = handlers.handle(top, annotationNode, annotation); - if ( handled ) annotationNode.setHandled(); + if (handled) annotationNode.setHandled(); } } } diff --git a/src/lombok/eclipse/handlers/HandleCleanup.java b/src/lombok/eclipse/handlers/HandleCleanup.java index 07c921ab..9cb23067 100644 --- a/src/lombok/eclipse/handlers/HandleCleanup.java +++ b/src/lombok/eclipse/handlers/HandleCleanup.java @@ -28,7 +28,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; @@ -51,37 +51,37 @@ import org.mangosdk.spi.ProviderFor; */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { - public boolean handle(AnnotationValues<Cleanup> annotation, Annotation ast, Node annotationNode) { + public boolean handle(AnnotationValues<Cleanup> annotation, Annotation ast, EclipseNode annotationNode) { String cleanupName = annotation.getInstance().value(); - if ( cleanupName.length() == 0 ) { + if (cleanupName.length() == 0) { annotationNode.addError("cleanupName cannot be the empty string."); return true; } - if ( annotationNode.up().getKind() != Kind.LOCAL ) { + if (annotationNode.up().getKind() != Kind.LOCAL) { annotationNode.addError("@Cleanup is legal only on local variable declarations."); return true; } LocalDeclaration decl = (LocalDeclaration)annotationNode.up().get(); - if ( decl.initialization == null ) { + if (decl.initialization == null) { annotationNode.addError("@Cleanup variable declarations need to be initialized."); return true; } - Node ancestor = annotationNode.up().directUp(); + EclipseNode ancestor = annotationNode.up().directUp(); ASTNode blockNode = ancestor.get(); final boolean isSwitch; final Statement[] statements; - if ( blockNode instanceof AbstractMethodDeclaration ) { + if (blockNode instanceof AbstractMethodDeclaration) { isSwitch = false; statements = ((AbstractMethodDeclaration)blockNode).statements; - } else if ( blockNode instanceof Block ) { + } else if (blockNode instanceof Block) { isSwitch = false; statements = ((Block)blockNode).statements; - } else if ( blockNode instanceof SwitchStatement ) { + } else if (blockNode instanceof SwitchStatement) { isSwitch = true; statements = ((SwitchStatement)blockNode).statements; } else { @@ -89,17 +89,17 @@ public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { return true; } - if ( statements == null ) { + if (statements == null) { annotationNode.addError("LOMBOK BUG: Parent block does not contain any statements."); return true; } int start = 0; - for ( ; start < statements.length ; start++ ) { - if ( statements[start] == decl ) break; + for (; start < statements.length ; start++) { + if (statements[start] == decl) break; } - if ( start == statements.length ) { + if (start == statements.length) { annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent."); return true; } @@ -107,10 +107,10 @@ public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { start++; //We start with try{} *AFTER* the var declaration. int end; - if ( isSwitch ) { + if (isSwitch) { end = start + 1; - for ( ; end < statements.length ; end++ ) { - if ( statements[end] instanceof CaseStatement ) { + for (; end < statements.length ; end++) { + if (statements[end] instanceof CaseStatement) { break; } } @@ -149,8 +149,8 @@ public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { Eclipse.setGeneratedBy(receiver, ast); unsafeClose.receiver = receiver; long nameSourcePosition = (long)ast.sourceStart << 32 | ast.sourceEnd; - if ( ast.memberValuePairs() != null ) for ( MemberValuePair pair : ast.memberValuePairs() ) { - if ( pair.name != null && new String(pair.name).equals("value") ) { + if (ast.memberValuePairs() != null) for (MemberValuePair pair : ast.memberValuePairs()) { + if (pair.name != null && new String(pair.name).equals("value")) { nameSourcePosition = (long)pair.value.sourceStart << 32 | pair.value.sourceEnd; break; } @@ -165,11 +165,11 @@ public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { tryStatement.catchArguments = null; tryStatement.catchBlocks = null; - if ( blockNode instanceof AbstractMethodDeclaration ) { + if (blockNode instanceof AbstractMethodDeclaration) { ((AbstractMethodDeclaration)blockNode).statements = newStatements; - } else if ( blockNode instanceof Block ) { + } else if (blockNode instanceof Block) { ((Block)blockNode).statements = newStatements; - } else if ( blockNode instanceof SwitchStatement ) { + } else if (blockNode instanceof SwitchStatement) { ((SwitchStatement)blockNode).statements = newStatements; } @@ -178,21 +178,21 @@ public class HandleCleanup implements EclipseAnnotationHandler<Cleanup> { return true; } - private void doAssignmentCheck(Node node, Statement[] tryBlock, char[] varName) { - for ( Statement statement : tryBlock ) doAssignmentCheck0(node, statement, varName); + private void doAssignmentCheck(EclipseNode node, Statement[] tryBlock, char[] varName) { + for (Statement statement : tryBlock) doAssignmentCheck0(node, statement, varName); } - private void doAssignmentCheck0(Node node, Statement statement, char[] varName) { - if ( statement instanceof Assignment ) + private void doAssignmentCheck0(EclipseNode node, Statement statement, char[] varName) { + if (statement instanceof Assignment) doAssignmentCheck0(node, ((Assignment)statement).expression, varName); - else if ( statement instanceof LocalDeclaration ) + else if (statement instanceof LocalDeclaration) doAssignmentCheck0(node, ((LocalDeclaration)statement).initialization, varName); - else if ( statement instanceof CastExpression ) + else if (statement instanceof CastExpression) doAssignmentCheck0(node, ((CastExpression)statement).expression, varName); - else if ( statement instanceof SingleNameReference ) { - if ( Arrays.equals(((SingleNameReference)statement).token, varName) ) { - Node problemNode = node.getNodeFor(statement); - if ( problemNode != null ) problemNode.addWarning( + else if (statement instanceof SingleNameReference) { + if (Arrays.equals(((SingleNameReference)statement).token, varName)) { + EclipseNode problemNode = node.getNodeFor(statement); + if (problemNode != null) problemNode.addWarning( "You're assigning an auto-cleanup variable to something else. This is a bad idea."); } } diff --git a/src/lombok/eclipse/handlers/HandleData.java b/src/lombok/eclipse/handlers/HandleData.java index 2761c20b..d760e1c6 100644 --- a/src/lombok/eclipse/handlers/HandleData.java +++ b/src/lombok/eclipse/handlers/HandleData.java @@ -36,7 +36,7 @@ import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.PKG.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.ASTNode; @@ -68,32 +68,32 @@ import org.mangosdk.spi.ProviderFor; */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleData implements EclipseAnnotationHandler<Data> { - public boolean handle(AnnotationValues<Data> annotation, Annotation ast, Node annotationNode) { + public boolean handle(AnnotationValues<Data> annotation, Annotation ast, EclipseNode annotationNode) { Data ann = annotation.getInstance(); - Node typeNode = annotationNode.up(); + EclipseNode typeNode = annotationNode.up(); TypeDeclaration typeDecl = null; - if ( typeNode.get() instanceof TypeDeclaration ) typeDecl = (TypeDeclaration) typeNode.get(); + if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; - if ( typeDecl == null || notAClass ) { + if (typeDecl == null || notAClass) { annotationNode.addError("@Data is only supported on a class."); return false; } - List<Node> nodesForConstructor = new ArrayList<Node>(); - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<EclipseNode> nodesForConstructor = new ArrayList<EclipseNode>(); + for (EclipseNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); //Skip static fields. - if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; + if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0) continue; boolean isFinal = (fieldDecl.modifiers & ClassFileConstants.AccFinal) != 0; boolean isNonNull = findAnnotations(fieldDecl, TransformationsUtil.NON_NULL_PATTERN).length != 0; - if ( (isFinal || isNonNull) && fieldDecl.initialization == null ) nodesForConstructor.add(child); + if ((isFinal || isNonNull) && fieldDecl.initialization == null) nodesForConstructor.add(child); new HandleGetter().generateGetterForField(child, annotationNode.get()); - if ( !isFinal ) new HandleSetter().generateSetterForField(child, annotationNode.get()); + if (!isFinal) new HandleSetter().generateSetterForField(child, annotationNode.get()); } new HandleToString().generateToStringForType(typeNode, annotationNode); @@ -102,17 +102,17 @@ public class HandleData implements EclipseAnnotationHandler<Data> { //Careful: Generate the public static constructor (if there is one) LAST, so that any attempt to //'find callers' on the annotation node will find callers of the constructor, which is by far the //most useful of the many methods built by @Data. This trick won't work for the non-static constructor, - //for whatever reason, though you can find callers of that one by focussing on the class name itself + //for whatever reason, though you can find callers of that one by focusing on the class name itself //and hitting 'find callers'. - if ( constructorExists(typeNode) == MemberExistsResult.NOT_EXISTS ) { + if (constructorExists(typeNode) == MemberExistsResult.NOT_EXISTS) { ConstructorDeclaration constructor = createConstructor( ann.staticConstructor().length() == 0, typeNode, nodesForConstructor, ast); injectMethod(typeNode, constructor); } - if ( ann.staticConstructor().length() > 0 ) { - if ( methodExists("of", typeNode) == MemberExistsResult.NOT_EXISTS ) { + if (ann.staticConstructor().length() > 0) { + if (methodExists("of", typeNode) == MemberExistsResult.NOT_EXISTS) { MethodDeclaration staticConstructor = createStaticConstructor( ann.staticConstructor(), typeNode, nodesForConstructor, ast); injectMethod(typeNode, staticConstructor); @@ -122,7 +122,8 @@ public class HandleData implements EclipseAnnotationHandler<Data> { return false; } - private ConstructorDeclaration createConstructor(boolean isPublic, Node type, Collection<Node> fields, ASTNode source) { + private ConstructorDeclaration createConstructor(boolean isPublic, + EclipseNode type, Collection<EclipseNode> fields, ASTNode source) { long p = (long)source.sourceStart << 32 | source.sourceEnd; ConstructorDeclaration constructor = new ConstructorDeclaration( @@ -145,7 +146,7 @@ public class HandleData implements EclipseAnnotationHandler<Data> { List<Statement> assigns = new ArrayList<Statement>(); List<Statement> nullChecks = new ArrayList<Statement>(); - for ( Node fieldNode : fields ) { + for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); FieldReference thisX = new FieldReference(("this." + new String(field.name)).toCharArray(), p); Eclipse.setGeneratedBy(thisX, source); @@ -178,7 +179,7 @@ public class HandleData implements EclipseAnnotationHandler<Data> { return constructor; } - private MethodDeclaration createStaticConstructor(String name, Node type, Collection<Node> fields, ASTNode source) { + private MethodDeclaration createStaticConstructor(String name, EclipseNode type, Collection<EclipseNode> fields, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; @@ -188,10 +189,10 @@ public class HandleData implements EclipseAnnotationHandler<Data> { constructor.modifiers = PKG.toModifier(AccessLevel.PUBLIC) | Modifier.STATIC; TypeDeclaration typeDecl = (TypeDeclaration) type.get(); - if ( typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0 ) { + if (typeDecl.typeParameters != null && typeDecl.typeParameters.length > 0) { TypeReference[] refs = new TypeReference[typeDecl.typeParameters.length]; int idx = 0; - for ( TypeParameter param : typeDecl.typeParameters ) { + for (TypeParameter param : typeDecl.typeParameters) { TypeReference typeRef = new SingleTypeReference(param.name, (long)param.sourceStart << 32 | param.sourceEnd); Eclipse.setGeneratedBy(typeRef, source); refs[idx++] = typeRef; @@ -214,7 +215,7 @@ public class HandleData implements EclipseAnnotationHandler<Data> { Eclipse.setGeneratedBy(statement, source); statement.type = copyType(constructor.returnType, source); - for ( Node fieldNode : fields ) { + for (EclipseNode fieldNode : fields) { FieldDeclaration field = (FieldDeclaration) fieldNode.get(); long fieldPos = (((long)field.sourceStart) << 32) | field.sourceEnd; SingleNameReference nameRef = new SingleNameReference(field.name, fieldPos); diff --git a/src/lombok/eclipse/handlers/HandleEqualsAndHashCode.java b/src/lombok/eclipse/handlers/HandleEqualsAndHashCode.java index 209c095c..847ea7d1 100644 --- a/src/lombok/eclipse/handlers/HandleEqualsAndHashCode.java +++ b/src/lombok/eclipse/handlers/HandleEqualsAndHashCode.java @@ -81,7 +81,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; /** * Handles the <code>EqualsAndHashCode</code> annotation for eclipse. @@ -91,23 +91,23 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA private static final Set<String> BUILT_IN_TYPES = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList( "byte", "short", "int", "long", "char", "boolean", "double", "float"))); - private void checkForBogusFieldNames(Node type, AnnotationValues<EqualsAndHashCode> annotation) { - if ( annotation.isExplicit("exclude") ) { - for ( int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, true) ) { + private void checkForBogusFieldNames(EclipseNode type, AnnotationValues<EqualsAndHashCode> annotation) { + if (annotation.isExplicit("exclude")) { + for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, true)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } - if ( annotation.isExplicit("of") ) { - for ( int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false) ) { + if (annotation.isExplicit("of")) { + for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } - public void generateEqualsAndHashCodeForType(Node typeNode, Node errorNode) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Eclipse.annotationTypeMatches(EqualsAndHashCode.class, child) ) { + public void generateEqualsAndHashCodeForType(EclipseNode typeNode, EclipseNode errorNode) { + for (EclipseNode child : typeNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Eclipse.annotationTypeMatches(EqualsAndHashCode.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -117,20 +117,21 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA generateMethods(typeNode, errorNode, null, null, null, false); } - @Override public boolean handle(AnnotationValues<EqualsAndHashCode> annotation, Annotation ast, Node annotationNode) { + @Override public boolean handle(AnnotationValues<EqualsAndHashCode> annotation, + Annotation ast, EclipseNode annotationNode) { EqualsAndHashCode ann = annotation.getInstance(); List<String> excludes = Arrays.asList(ann.exclude()); List<String> includes = Arrays.asList(ann.of()); - Node typeNode = annotationNode.up(); + EclipseNode 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 (!annotation.isExplicit("callSuper")) callSuper = null; + if (!annotation.isExplicit("exclude")) excludes = null; + if (!annotation.isExplicit("of")) includes = null; - if ( excludes != null && includes != null ) { + if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } @@ -138,70 +139,70 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA return generateMethods(typeNode, annotationNode, excludes, includes, callSuper, true); } - public boolean generateMethods(Node typeNode, Node errorNode, List<String> excludes, List<String> includes, + public boolean generateMethods(EclipseNode typeNode, EclipseNode errorNode, List<String> excludes, List<String> includes, Boolean callSuper, boolean whineIfExists) { assert excludes == null || includes == null; TypeDeclaration typeDecl = null; - if ( typeNode.get() instanceof TypeDeclaration ) typeDecl = (TypeDeclaration) typeNode.get(); + if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; - if ( typeDecl == null || notAClass ) { + if (typeDecl == null || notAClass) { errorNode.addError("@EqualsAndHashCode is only supported on a class."); return false; } boolean implicitCallSuper = callSuper == null; - if ( callSuper == null ) { + if (callSuper == null) { try { callSuper = ((Boolean)EqualsAndHashCode.class.getMethod("callSuper").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} } boolean isDirectDescendantOfObject = true; - if ( typeDecl.superclass != null ) { + if (typeDecl.superclass != null) { String p = typeDecl.superclass.toString(); isDirectDescendantOfObject = p.equals("Object") || p.equals("java.lang.Object"); } - if ( isDirectDescendantOfObject && callSuper ) { + if (isDirectDescendantOfObject && callSuper) { errorNode.addError("Generating equals/hashCode with a supercall to java.lang.Object is pointless."); return true; } - if ( !isDirectDescendantOfObject && !callSuper && implicitCallSuper ) { + if (!isDirectDescendantOfObject && !callSuper && implicitCallSuper) { errorNode.addWarning("Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.lang.Object. If this is intentional, add '@EqualsAndHashCode(callSuper=false)' to your type."); } - List<Node> nodesForEquality = new ArrayList<Node>(); - if ( includes != null ) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<EclipseNode> nodesForEquality = new ArrayList<EclipseNode>(); + if (includes != null) { + for (EclipseNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if ( includes.contains(new String(fieldDecl.name)) ) nodesForEquality.add(child); + if (includes.contains(new String(fieldDecl.name))) nodesForEquality.add(child); } } else { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + for (EclipseNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); //Skip static fields. - if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; + if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0) continue; //Skip transient fields. - if ( (fieldDecl.modifiers & ClassFileConstants.AccTransient) != 0 ) continue; + if ((fieldDecl.modifiers & ClassFileConstants.AccTransient) != 0) continue; //Skip excluded fields. - if ( excludes != null && excludes.contains(new String(fieldDecl.name)) ) continue; + if (excludes != null && excludes.contains(new String(fieldDecl.name))) continue; //Skip fields that start with $. - if ( fieldDecl.name.length > 0 && fieldDecl.name[0] == '$' ) continue; + if (fieldDecl.name.length > 0 && fieldDecl.name[0] == '$') continue; nodesForEquality.add(child); } } - switch ( methodExists("hashCode", typeNode) ) { + switch (methodExists("hashCode", typeNode)) { case NOT_EXISTS: MethodDeclaration hashCode = createHashCode(typeNode, nodesForEquality, callSuper, errorNode.get()); injectMethod(typeNode, hashCode); @@ -210,13 +211,13 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA break; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating hashCode(): A method with that name already exists"); } break; } - switch ( methodExists("equals", typeNode) ) { + switch (methodExists("equals", typeNode)) { case NOT_EXISTS: MethodDeclaration equals = createEquals(typeNode, nodesForEquality, callSuper, errorNode.get()); injectMethod(typeNode, equals); @@ -225,7 +226,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA break; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating equals(Object other): A method with that name already exists"); } break; @@ -234,7 +235,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA return true; } - private MethodDeclaration createHashCode(Node type, Collection<Node> fields, boolean callSuper, ASTNode source) { + private MethodDeclaration createHashCode(EclipseNode type, Collection<EclipseNode> fields, boolean callSuper, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; @@ -263,7 +264,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA /* final int PRIME = 31; */ { /* Without fields, PRIME isn't used, and that would trigger a 'local variable not used' warning. */ - if ( !isEmpty || callSuper ) { + if (!isEmpty || callSuper) { LocalDeclaration primeDecl = new LocalDeclaration(PRIME, pS, pE); Eclipse.setGeneratedBy(primeDecl, source); primeDecl.modifiers |= Modifier.FINAL; @@ -287,7 +288,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA statements.add(resultDecl); } - if ( callSuper ) { + if (callSuper) { MessageSend callToSuper = new MessageSend(); Eclipse.setGeneratedBy(callToSuper, source); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; @@ -298,11 +299,11 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA } int tempCounter = 0; - for ( Node field : fields ) { + for (EclipseNode field : fields) { FieldDeclaration f = (FieldDeclaration) field.get(); char[] token = f.type.getLastToken(); - if ( f.type.dimensions() == 0 && token != null ) { - if ( Arrays.equals(TypeConstants.FLOAT, token) ) { + if (f.type.dimensions() == 0 && token != null) { + if (Arrays.equals(TypeConstants.FLOAT, token)) { /* Float.floatToIntBits(fieldName) */ MessageSend floatToIntBits = new MessageSend(); floatToIntBits.sourceStart = pS; floatToIntBits.sourceEnd = pE; @@ -311,7 +312,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA floatToIntBits.selector = "floatToIntBits".toCharArray(); floatToIntBits.arguments = new Expression[] { generateFieldReference(f.name, source) }; intoResult.add(floatToIntBits); - } else if ( Arrays.equals(TypeConstants.DOUBLE, token) ) { + } else if (Arrays.equals(TypeConstants.DOUBLE, token)) { /* longToIntForHashCode(Double.doubleToLongBits(fieldName)) */ MessageSend doubleToLongBits = new MessageSend(); doubleToLongBits.sourceStart = pS; doubleToLongBits.sourceEnd = pE; @@ -333,7 +334,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA SingleNameReference copy2 = new SingleNameReference(tempName, p); Eclipse.setGeneratedBy(copy2, source); intoResult.add(longToIntForHashCode(copy1, copy2, source)); - } else if ( Arrays.equals(TypeConstants.BOOLEAN, token) ) { + } else if (Arrays.equals(TypeConstants.BOOLEAN, token)) { /* booleanField ? 1231 : 1237 */ IntLiteral int1231 = new IntLiteral("1231".toCharArray(), pS, pE); Eclipse.setGeneratedBy(int1231, source); @@ -343,9 +344,9 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA generateFieldReference(f.name, source), int1231, int1237); Eclipse.setGeneratedBy(int1231or1237, source); intoResult.add(int1231or1237); - } else if ( Arrays.equals(TypeConstants.LONG, token) ) { + } else if (Arrays.equals(TypeConstants.LONG, token)) { intoResult.add(longToIntForHashCode(generateFieldReference(f.name, source), generateFieldReference(f.name, source), source)); - } else if ( BUILT_IN_TYPES.contains(new String(token)) ) { + } else if (BUILT_IN_TYPES.contains(new String(token))) { intoResult.add(generateFieldReference(f.name, source)); } else /* objects */ { /* this.fieldName == null ? 0 : this.fieldName.hashCode() */ @@ -366,13 +367,13 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA Eclipse.setGeneratedBy(nullOrHashCode, source); intoResult.add(nullOrHashCode); } - } else if ( f.type.dimensions() > 0 && token != null ) { + } else if (f.type.dimensions() > 0 && token != null) { /* Arrays.deepHashCode(array) //just hashCode for simple arrays */ MessageSend arraysHashCodeCall = new MessageSend(); arraysHashCodeCall.sourceStart = pS; arraysHashCodeCall.sourceEnd = pE; Eclipse.setGeneratedBy(arraysHashCodeCall, source); arraysHashCodeCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); - if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token)) ) { + if (f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysHashCodeCall.selector = "deepHashCode".toCharArray(); } else { arraysHashCodeCall.selector = "hashCode".toCharArray(); @@ -384,7 +385,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA /* fold each intoResult entry into: result = result * PRIME + (item); */ { - for ( Expression ex : intoResult ) { + for (Expression ex : intoResult) { SingleNameReference resultRef = new SingleNameReference(RESULT, p); Eclipse.setGeneratedBy(resultRef, source); SingleNameReference primeRef = new SingleNameReference(PRIME, p); @@ -415,7 +416,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA return method; } - private MethodDeclaration createEquals(Node type, Collection<Node> fields, boolean callSuper, ASTNode source) { + private MethodDeclaration createEquals(EclipseNode type, Collection<EclipseNode> fields, boolean callSuper, ASTNode source) { int pS = source.sourceStart; int pE = source.sourceEnd; long p = (long)pS << 32 | pE; @@ -441,7 +442,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA List<Statement> statements = new ArrayList<Statement>(); - /* if ( o == this ) return true; */ { + /* if (o == this) return true; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); Eclipse.setGeneratedBy(oRef, source); ThisReference thisRef = new ThisReference(pS, pE); @@ -458,7 +459,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA statements.add(ifOtherEqualsThis); } - /* if ( o == null ) return false; */ { + /* if (o == null) return false; */ { SingleNameReference oRef = new SingleNameReference(new char[] { 'o' }, p); Eclipse.setGeneratedBy(oRef, source); NullLiteral nullLiteral = new NullLiteral(pS, pE); @@ -475,7 +476,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA statements.add(ifOtherEqualsNull); } - /* if ( o.getClass() != getClass() ) return false; */ { + /* if (o.getClass() != getClass()) return false; */ { MessageSend otherGetClass = new MessageSend(); otherGetClass.sourceStart = pS; otherGetClass.sourceEnd = pE; Eclipse.setGeneratedBy(otherGetClass, source); @@ -501,8 +502,8 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA char[] otherN = "other".toCharArray(); - /* if ( !super.equals(o) ) return false; */ - if ( callSuper ) { + /* if (!super.equals(o)) return false; */ + if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; Eclipse.setGeneratedBy(callToSuper, source); @@ -525,19 +526,19 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA TypeDeclaration typeDecl = (TypeDeclaration)type.get(); /* MyType<?> other = (MyType<?>) o; */ { - if ( !fields.isEmpty() ) { + if (!fields.isEmpty()) { LocalDeclaration other = new LocalDeclaration(otherN, pS, pE); Eclipse.setGeneratedBy(other, source); char[] typeName = typeDecl.name; Expression targetType; - if ( typeDecl.typeParameters == null || typeDecl.typeParameters.length == 0 ) { + if (typeDecl.typeParameters == null || typeDecl.typeParameters.length == 0) { targetType = new SingleNameReference(((TypeDeclaration)type.get()).name, p); Eclipse.setGeneratedBy(targetType, source); other.type = new SingleTypeReference(typeName, p); Eclipse.setGeneratedBy(other.type, source); } else { TypeReference[] typeArgs = new TypeReference[typeDecl.typeParameters.length]; - for ( int i = 0 ; i < typeArgs.length ; i++ ) { + for (int i = 0; i < typeArgs.length; i++) { typeArgs[i] = new Wildcard(Wildcard.UNBOUND); typeArgs[i].sourceStart = pS; typeArgs[i].sourceEnd = pE; Eclipse.setGeneratedBy(typeArgs[i], source); @@ -555,15 +556,15 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA } } - for ( Node field : fields ) { + for (EclipseNode field : fields) { FieldDeclaration f = (FieldDeclaration) field.get(); char[] token = f.type.getLastToken(); - if ( f.type.dimensions() == 0 && token != null ) { - if ( Arrays.equals(TypeConstants.FLOAT, token) ) { + if (f.type.dimensions() == 0 && token != null) { + if (Arrays.equals(TypeConstants.FLOAT, token)) { statements.add(generateCompareFloatOrDouble(otherN, "Float".toCharArray(), f.name, source)); - } else if ( Arrays.equals(TypeConstants.DOUBLE, token) ) { + } else if (Arrays.equals(TypeConstants.DOUBLE, token)) { statements.add(generateCompareFloatOrDouble(otherN, "Double".toCharArray(), f.name, source)); - } else if ( BUILT_IN_TYPES.contains(new String(token)) ) { + } else if (BUILT_IN_TYPES.contains(new String(token))) { NameReference fieldRef = new SingleNameReference(f.name, p); Eclipse.setGeneratedBy(fieldRef, source); EqualExpression fieldsNotEqual = new EqualExpression(fieldRef, @@ -608,12 +609,12 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA Eclipse.setGeneratedBy(ifStatement, source); statements.add(ifStatement); } - } else if ( f.type.dimensions() > 0 && token != null ) { + } else if (f.type.dimensions() > 0 && token != null) { MessageSend arraysEqualCall = new MessageSend(); arraysEqualCall.sourceStart = pS; arraysEqualCall.sourceEnd = pE; Eclipse.setGeneratedBy(arraysEqualCall, source); arraysEqualCall.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); - if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token)) ) { + if (f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(token))) { arraysEqualCall.selector = "deepEquals".toCharArray(); } else { arraysEqualCall.selector = "equals".toCharArray(); @@ -648,7 +649,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA private IfStatement generateCompareFloatOrDouble(char[] otherN, char[] floatOrDouble, char[] fieldName, ASTNode source) { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; - /* if ( Float.compare(fieldName, other.fieldName) != 0 ) return false */ + /* if (Float.compare(fieldName, other.fieldName) != 0) return false */ MessageSend floatCompare = new MessageSend(); floatCompare.sourceStart = pS; floatCompare.sourceEnd = pE; Eclipse.setGeneratedBy(floatCompare, source); @@ -707,7 +708,7 @@ public class HandleEqualsAndHashCode implements EclipseAnnotationHandler<EqualsA NameReference ref; - if ( varNames.length > 1 ) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); + if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); Eclipse.setGeneratedBy(ref, source); return ref; diff --git a/src/lombok/eclipse/handlers/HandleGetter.java b/src/lombok/eclipse/handlers/HandleGetter.java index 9760fe01..ad9f59f7 100644 --- a/src/lombok/eclipse/handlers/HandleGetter.java +++ b/src/lombok/eclipse/handlers/HandleGetter.java @@ -30,7 +30,7 @@ import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -62,10 +62,10 @@ public class HandleGetter implements EclipseAnnotationHandler<Getter> { * If not, the getter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ - public void generateGetterForField(Node fieldNode, ASTNode pos) { - for ( Node child : fieldNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( annotationTypeMatches(Getter.class, child) ) { + public void generateGetterForField(EclipseNode fieldNode, ASTNode pos) { + for (EclipseNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (annotationTypeMatches(Getter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -75,16 +75,17 @@ public class HandleGetter implements EclipseAnnotationHandler<Getter> { createGetterForField(AccessLevel.PUBLIC, fieldNode, fieldNode, pos, false); } - public boolean handle(AnnotationValues<Getter> annotation, Annotation ast, Node annotationNode) { - Node fieldNode = annotationNode.up(); + public boolean handle(AnnotationValues<Getter> annotation, Annotation ast, EclipseNode annotationNode) { + EclipseNode fieldNode = annotationNode.up(); AccessLevel level = annotation.getInstance().value(); - if ( level == AccessLevel.NONE ) return true; + if (level == AccessLevel.NONE) return true; return createGetterForField(level, fieldNode, annotationNode, annotationNode.get(), true); } - private boolean createGetterForField(AccessLevel level, Node fieldNode, Node errorNode, ASTNode source, boolean whineIfExists) { - if ( fieldNode.getKind() != Kind.FIELD ) { + private boolean createGetterForField(AccessLevel level, + EclipseNode fieldNode, EclipseNode errorNode, ASTNode source, boolean whineIfExists) { + if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Getter is only supported on a field."); return true; } @@ -97,14 +98,14 @@ public class HandleGetter implements EclipseAnnotationHandler<Getter> { int modifier = toModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); - for ( String altName : TransformationsUtil.toAllGetterNames(fieldName, isBoolean) ) { - switch ( methodExists(altName, fieldNode) ) { + for (String altName : TransformationsUtil.toAllGetterNames(fieldName, isBoolean)) { + switch (methodExists(altName, fieldNode)) { case EXISTS_BY_LOMBOK: return true; case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { String altNameExpl = ""; - if ( !altName.equals(getterName) ) altNameExpl = String.format(" (%s)", altName); + if (!altName.equals(getterName)) altNameExpl = String.format(" (%s)", altName); errorNode.addWarning( String.format("Not generating %s(): A method with that name already exists%s", getterName, altNameExpl)); } diff --git a/src/lombok/eclipse/handlers/HandlePrintAST.java b/src/lombok/eclipse/handlers/HandlePrintAST.java index 2f2b38d4..3e1df93d 100644 --- a/src/lombok/eclipse/handlers/HandlePrintAST.java +++ b/src/lombok/eclipse/handlers/HandlePrintAST.java @@ -33,21 +33,21 @@ import lombok.core.AnnotationValues; import lombok.core.PrintAST; import lombok.eclipse.EclipseASTVisitor; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; /** * Handles the <code>lombok.core.PrintAST</code> annotation for eclipse. */ @ProviderFor(EclipseAnnotationHandler.class) public class HandlePrintAST implements EclipseAnnotationHandler<PrintAST> { - public boolean handle(AnnotationValues<PrintAST> annotation, Annotation ast, Node annotationNode) { - if ( !annotationNode.isCompleteParse() ) return false; + public boolean handle(AnnotationValues<PrintAST> annotation, Annotation ast, EclipseNode annotationNode) { + if (!annotationNode.isCompleteParse()) return false; PrintStream stream = System.out; String fileName = annotation.getInstance().outfile(); - if ( fileName.length() > 0 ) try { + if (fileName.length() > 0) try { stream = new PrintStream(new File(fileName)); - } catch ( FileNotFoundException e ) { + } catch (FileNotFoundException e) { Lombok.sneakyThrow(e); } diff --git a/src/lombok/eclipse/handlers/HandleSetter.java b/src/lombok/eclipse/handlers/HandleSetter.java index f804eefc..0ef3c44b 100644 --- a/src/lombok/eclipse/handlers/HandleSetter.java +++ b/src/lombok/eclipse/handlers/HandleSetter.java @@ -33,7 +33,7 @@ import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -69,10 +69,10 @@ public class HandleSetter implements EclipseAnnotationHandler<Setter> { * If not, the setter is still generated if it isn't already there, though there will not * be a warning if its already there. The default access level is used. */ - public void generateSetterForField(Node fieldNode, ASTNode pos) { - for ( Node child : fieldNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( annotationTypeMatches(Setter.class, child) ) { + public void generateSetterForField(EclipseNode fieldNode, ASTNode pos) { + for (EclipseNode child : fieldNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (annotationTypeMatches(Setter.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -82,17 +82,18 @@ public class HandleSetter implements EclipseAnnotationHandler<Setter> { createSetterForField(AccessLevel.PUBLIC, fieldNode, fieldNode, pos, false); } - public boolean handle(AnnotationValues<Setter> annotation, Annotation ast, Node annotationNode) { - Node fieldNode = annotationNode.up(); - if ( fieldNode.getKind() != Kind.FIELD ) return false; + public boolean handle(AnnotationValues<Setter> annotation, Annotation ast, EclipseNode annotationNode) { + EclipseNode fieldNode = annotationNode.up(); + if (fieldNode.getKind() != Kind.FIELD) return false; AccessLevel level = annotation.getInstance().value(); - if ( level == AccessLevel.NONE ) return true; + if (level == AccessLevel.NONE) return true; return createSetterForField(level, fieldNode, annotationNode, annotationNode.get(), true); } - private boolean createSetterForField(AccessLevel level, Node fieldNode, Node errorNode, ASTNode pos, boolean whineIfExists) { - if ( fieldNode.getKind() != Kind.FIELD ) { + private boolean createSetterForField(AccessLevel level, + EclipseNode fieldNode, EclipseNode errorNode, ASTNode pos, boolean whineIfExists) { + if (fieldNode.getKind() != Kind.FIELD) { errorNode.addError("@Setter is only supported on a field."); return true; } @@ -102,11 +103,11 @@ public class HandleSetter implements EclipseAnnotationHandler<Setter> { int modifier = toModifier(level) | (field.modifiers & ClassFileConstants.AccStatic); - switch ( methodExists(setterName, fieldNode) ) { + switch (methodExists(setterName, fieldNode)) { case EXISTS_BY_LOMBOK: return true; case EXISTS_BY_USER: - if ( whineIfExists ) errorNode.addWarning( + if (whineIfExists) errorNode.addWarning( String.format("Not generating %s(%s %s): A method with that name already exists", setterName, field.type, new String(field.name))); return true; @@ -115,7 +116,6 @@ public class HandleSetter implements EclipseAnnotationHandler<Setter> { //continue with creating the setter } - MethodDeclaration method = generateSetter((TypeDeclaration) fieldNode.up().get(), field, setterName, modifier, pos); injectMethod(fieldNode.up(), method); diff --git a/src/lombok/eclipse/handlers/HandleSneakyThrows.java b/src/lombok/eclipse/handlers/HandleSneakyThrows.java index 75dad780..5cb5dca7 100644 --- a/src/lombok/eclipse/handlers/HandleSneakyThrows.java +++ b/src/lombok/eclipse/handlers/HandleSneakyThrows.java @@ -29,7 +29,7 @@ import lombok.SneakyThrows; import lombok.core.AnnotationValues; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; @@ -69,35 +69,35 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows } } - @Override public boolean handle(AnnotationValues<SneakyThrows> annotation, Annotation source, Node annotationNode) { + @Override public boolean handle(AnnotationValues<SneakyThrows> annotation, Annotation source, EclipseNode annotationNode) { List<String> exceptionNames = annotation.getRawExpressions("value"); List<DeclaredException> exceptions = new ArrayList<DeclaredException>(); MemberValuePair[] memberValuePairs = source.memberValuePairs(); - if ( memberValuePairs == null || memberValuePairs.length == 0 ) { + if (memberValuePairs == null || memberValuePairs.length == 0) { exceptions.add(new DeclaredException("java.lang.Throwable", source)); } else { Expression arrayOrSingle = memberValuePairs[0].value; final Expression[] exceptionNameNodes; - if ( arrayOrSingle instanceof ArrayInitializer ) { + if (arrayOrSingle instanceof ArrayInitializer) { exceptionNameNodes = ((ArrayInitializer)arrayOrSingle).expressions; } else exceptionNameNodes = new Expression[] { arrayOrSingle }; - if ( exceptionNames.size() != exceptionNameNodes.length ) { + if (exceptionNames.size() != exceptionNameNodes.length) { annotationNode.addError( "LOMBOK BUG: The number of exception classes in the annotation isn't the same pre- and post- guessing."); } int idx = 0; - for ( String exceptionName : exceptionNames ) { - if ( exceptionName.endsWith(".class") ) exceptionName = exceptionName.substring(0, exceptionName.length() - 6); + for (String exceptionName : exceptionNames) { + if (exceptionName.endsWith(".class")) exceptionName = exceptionName.substring(0, exceptionName.length() - 6); exceptions.add(new DeclaredException(exceptionName, exceptionNameNodes[idx++])); } } - Node owner = annotationNode.up(); - switch ( owner.getKind() ) { + EclipseNode owner = annotationNode.up(); + switch (owner.getKind()) { // case FIELD: // return handleField(annotationNode, (FieldDeclaration)owner.get(), exceptions); case METHOD: @@ -109,7 +109,7 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows } // private boolean handleField(Node annotation, FieldDeclaration field, List<DeclaredException> exceptions) { -// if ( field.initialization == null ) { +// if (field.initialization == null) { // annotation.addError("@SneakyThrows can only be used on fields with an initialization statement."); // return true; // } @@ -119,7 +119,7 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows // new SingleNameReference(field.name, 0), expression, 0)}; // field.initialization = null; // -// for ( DeclaredException exception : exceptions ) { +// for (DeclaredException exception : exceptions) { // content = new Statement[] { buildTryCatchBlock(content, exception) }; // } // @@ -140,17 +140,17 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows // return true; // } - private boolean handleMethod(Node annotation, AbstractMethodDeclaration method, List<DeclaredException> exceptions) { - if ( method.isAbstract() ) { + private boolean handleMethod(EclipseNode annotation, AbstractMethodDeclaration method, List<DeclaredException> exceptions) { + if (method.isAbstract()) { annotation.addError("@SneakyThrows can only be used on concrete methods."); return true; } - if ( method.statements == null ) return false; + if (method.statements == null) return false; Statement[] contents = method.statements; - for ( DeclaredException exception : exceptions ) { + for (DeclaredException exception : exceptions) { contents = new Statement[] { buildTryCatchBlock(contents, exception, exception.node) }; } @@ -171,7 +171,7 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows Eclipse.setGeneratedBy(tryStatement.tryBlock, source); tryStatement.tryBlock.statements = contents; TypeReference typeReference; - if ( exception.exceptionName.indexOf('.') == -1 ) { + if (exception.exceptionName.indexOf('.') == -1) { typeReference = new SingleTypeReference(exception.exceptionName.toCharArray(), p); typeReference.statementEnd = pE; } else { @@ -179,7 +179,7 @@ public class HandleSneakyThrows implements EclipseAnnotationHandler<SneakyThrows char[][] elems = new char[x.length][]; long[] poss = new long[x.length]; int start = pS; - for ( int i = 0 ; i < x.length ; i++ ) { + for (int i = 0; i < x.length; i++) { elems[i] = x[i].trim().toCharArray(); int end = start + x[i].length(); poss[i] = (long)start << 32 | end; diff --git a/src/lombok/eclipse/handlers/HandleSynchronized.java b/src/lombok/eclipse/handlers/HandleSynchronized.java index 7a573198..5f1d0864 100644 --- a/src/lombok/eclipse/handlers/HandleSynchronized.java +++ b/src/lombok/eclipse/handlers/HandleSynchronized.java @@ -30,7 +30,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import lombok.eclipse.handlers.PKG.MemberExistsResult; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -57,31 +57,31 @@ public class HandleSynchronized implements EclipseAnnotationHandler<Synchronized private static final char[] INSTANCE_LOCK_NAME = "$lock".toCharArray(); private static final char[] STATIC_LOCK_NAME = "$LOCK".toCharArray(); - @Override public boolean handle(AnnotationValues<Synchronized> annotation, Annotation source, Node annotationNode) { + @Override public boolean handle(AnnotationValues<Synchronized> annotation, Annotation source, EclipseNode annotationNode) { int p1 = source.sourceStart -1; int p2 = source.sourceStart -2; long pos = (((long)p1) << 32) | p2; - Node methodNode = annotationNode.up(); - if ( methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof MethodDeclaration) ) { + EclipseNode methodNode = annotationNode.up(); + if (methodNode == null || methodNode.getKind() != Kind.METHOD || !(methodNode.get() instanceof MethodDeclaration)) { annotationNode.addError("@Synchronized is legal only on methods."); return true; } MethodDeclaration method = (MethodDeclaration)methodNode.get(); - if ( method.isAbstract() ) { + if (method.isAbstract()) { annotationNode.addError("@Synchronized is legal only on concrete methods."); return true; } char[] lockName = annotation.getInstance().value().toCharArray(); boolean autoMake = false; - if ( lockName.length == 0 ) { + if (lockName.length == 0) { autoMake = true; lockName = method.isStatic() ? STATIC_LOCK_NAME : INSTANCE_LOCK_NAME; } - if ( fieldExists(new String(lockName), methodNode) == MemberExistsResult.NOT_EXISTS ) { - if ( !autoMake ) { + if (fieldExists(new String(lockName), methodNode) == MemberExistsResult.NOT_EXISTS) { + if (!autoMake) { annotationNode.addError("The field " + new String(lockName) + " does not exist."); return true; } @@ -104,13 +104,13 @@ public class HandleSynchronized implements EclipseAnnotationHandler<Synchronized injectField(annotationNode.up().up(), fieldDecl); } - if ( method.statements == null ) return false; + if (method.statements == null) return false; Block block = new Block(0); Eclipse.setGeneratedBy(block, source); block.statements = method.statements; Expression lockVariable; - if ( method.isStatic() ) lockVariable = new QualifiedNameReference(new char[][] { + if (method.isStatic()) lockVariable = new QualifiedNameReference(new char[][] { methodNode.up().getName().toCharArray(), lockName }, new long[] { pos, pos }, p1, p2); else { lockVariable = new FieldReference(lockName, pos); diff --git a/src/lombok/eclipse/handlers/HandleToString.java b/src/lombok/eclipse/handlers/HandleToString.java index 5a840e1f..263a588c 100644 --- a/src/lombok/eclipse/handlers/HandleToString.java +++ b/src/lombok/eclipse/handlers/HandleToString.java @@ -37,7 +37,7 @@ import lombok.core.AnnotationValues; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; import lombok.eclipse.EclipseAnnotationHandler; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.Annotation; @@ -68,24 +68,23 @@ import org.mangosdk.spi.ProviderFor; */ @ProviderFor(EclipseAnnotationHandler.class) public class HandleToString implements EclipseAnnotationHandler<ToString> { - private void checkForBogusFieldNames(Node type, AnnotationValues<ToString> annotation) { - if ( annotation.isExplicit("exclude") ) { - for ( int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, false) ) { + private void checkForBogusFieldNames(EclipseNode type, AnnotationValues<ToString> annotation) { + if (annotation.isExplicit("exclude")) { + for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().exclude()), type, true, false)) { annotation.setWarning("exclude", "This field does not exist, or would have been excluded anyway.", i); } } - if ( annotation.isExplicit("of") ) { - for ( int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false) ) { + if (annotation.isExplicit("of")) { + for (int i : createListOfNonExistentFields(Arrays.asList(annotation.getInstance().of()), type, false, false)) { annotation.setWarning("of", "This field does not exist.", i); } } } - - public void generateToStringForType(Node typeNode, Node errorNode) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() == Kind.ANNOTATION ) { - if ( Eclipse.annotationTypeMatches(ToString.class, child) ) { + public void generateToStringForType(EclipseNode typeNode, EclipseNode errorNode) { + for (EclipseNode child : typeNode.down()) { + if (child.getKind() == Kind.ANNOTATION) { + if (Eclipse.annotationTypeMatches(ToString.class, child)) { //The annotation will make it happen, so we can skip it. return; } @@ -95,22 +94,22 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { boolean includeFieldNames = true; try { includeFieldNames = ((Boolean)ToString.class.getMethod("includeFieldNames").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} generateToString(typeNode, errorNode, null, null, includeFieldNames, null, false); } - public boolean handle(AnnotationValues<ToString> annotation, Annotation ast, Node annotationNode) { + public boolean handle(AnnotationValues<ToString> annotation, Annotation ast, EclipseNode annotationNode) { ToString ann = annotation.getInstance(); List<String> excludes = Arrays.asList(ann.exclude()); List<String> includes = Arrays.asList(ann.of()); - Node typeNode = annotationNode.up(); + EclipseNode typeNode = annotationNode.up(); Boolean callSuper = ann.callSuper(); - if ( !annotation.isExplicit("callSuper") ) callSuper = null; - if ( !annotation.isExplicit("exclude") ) excludes = null; - if ( !annotation.isExplicit("of") ) includes = null; + if (!annotation.isExplicit("callSuper")) callSuper = null; + if (!annotation.isExplicit("exclude")) excludes = null; + if (!annotation.isExplicit("of")) includes = null; - if ( excludes != null && includes != null ) { + if (excludes != null && includes != null) { excludes = null; annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored."); } @@ -120,48 +119,48 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { return generateToString(typeNode, annotationNode, excludes, includes, ann.includeFieldNames(), callSuper, true); } - public boolean generateToString(Node typeNode, Node errorNode, List<String> excludes, List<String> includes, + public boolean generateToString(EclipseNode typeNode, EclipseNode errorNode, List<String> excludes, List<String> includes, boolean includeFieldNames, Boolean callSuper, boolean whineIfExists) { TypeDeclaration typeDecl = null; - if ( typeNode.get() instanceof TypeDeclaration ) typeDecl = (TypeDeclaration) typeNode.get(); + if (typeNode.get() instanceof TypeDeclaration) typeDecl = (TypeDeclaration) typeNode.get(); int modifiers = typeDecl == null ? 0 : typeDecl.modifiers; boolean notAClass = (modifiers & (ClassFileConstants.AccInterface | ClassFileConstants.AccAnnotation | ClassFileConstants.AccEnum)) != 0; - if ( typeDecl == null || notAClass ) { + if (typeDecl == null || notAClass) { errorNode.addError("@ToString is only supported on a class."); return false; } - if ( callSuper == null ) { + if (callSuper == null) { try { callSuper = ((Boolean)ToString.class.getMethod("callSuper").getDefaultValue()).booleanValue(); - } catch ( Exception ignore ) {} + } catch (Exception ignore) {} } - List<Node> nodesForToString = new ArrayList<Node>(); - if ( includes != null ) { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + List<EclipseNode> nodesForToString = new ArrayList<EclipseNode>(); + if (includes != null) { + for (EclipseNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); - if ( includes.contains(new String(fieldDecl.name)) ) nodesForToString.add(child); + if (includes.contains(new String(fieldDecl.name))) nodesForToString.add(child); } } else { - for ( Node child : typeNode.down() ) { - if ( child.getKind() != Kind.FIELD ) continue; + for (EclipseNode child : typeNode.down()) { + if (child.getKind() != Kind.FIELD) continue; FieldDeclaration fieldDecl = (FieldDeclaration) child.get(); //Skip static fields. - if ( (fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0 ) continue; + if ((fieldDecl.modifiers & ClassFileConstants.AccStatic) != 0) continue; //Skip excluded fields. - if ( excludes != null && excludes.contains(new String(fieldDecl.name)) ) continue; + if (excludes != null && excludes.contains(new String(fieldDecl.name))) continue; //Skip fields that start with $ - if ( fieldDecl.name.length > 0 && fieldDecl.name[0] == '$' ) continue; + if (fieldDecl.name.length > 0 && fieldDecl.name[0] == '$') continue; nodesForToString.add(child); } } - switch ( methodExists("toString", typeNode) ) { + switch (methodExists("toString", typeNode)) { case NOT_EXISTS: MethodDeclaration toString = createToString(typeNode, nodesForToString, includeFieldNames, callSuper, errorNode.get()); injectMethod(typeNode, toString); @@ -170,14 +169,15 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { return true; default: case EXISTS_BY_USER: - if ( whineIfExists ) { + if (whineIfExists) { errorNode.addWarning("Not generating toString(): A method with that name already exists"); } return true; } } - private MethodDeclaration createToString(Node type, Collection<Node> fields, boolean includeFieldNames, boolean callSuper, ASTNode source) { + private MethodDeclaration createToString(EclipseNode type, Collection<EclipseNode> fields, + boolean includeFieldNames, boolean callSuper, ASTNode source) { TypeDeclaration typeDeclaration = (TypeDeclaration)type.get(); char[] rawTypeName = typeDeclaration.name; String typeName = rawTypeName == null ? "" : new String(rawTypeName); @@ -190,11 +190,11 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { char[] prefix; - if ( callSuper ) { + if (callSuper) { prefix = (typeName + "(super=").toCharArray(); - } else if ( fields.isEmpty() ) { + } else if (fields.isEmpty()) { prefix = (typeName + "()").toCharArray(); - } else if ( includeFieldNames ) { + } else if (includeFieldNames) { prefix = (typeName + "(" + new String(((FieldDeclaration)fields.iterator().next().get()).name) + "=").toCharArray(); } else { prefix = (typeName + "(").toCharArray(); @@ -204,7 +204,7 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { Expression current = new StringLiteral(prefix, pS, pE, 0); Eclipse.setGeneratedBy(current, source); - if ( callSuper ) { + if (callSuper) { MessageSend callToSuper = new MessageSend(); callToSuper.sourceStart = pS; callToSuper.sourceEnd = pE; Eclipse.setGeneratedBy(callToSuper, source); @@ -216,18 +216,18 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { first = false; } - for ( Node field : fields ) { + for (EclipseNode field : fields) { FieldDeclaration f = (FieldDeclaration)field.get(); - if ( f.name == null || f.type == null ) continue; + if (f.name == null || f.type == null) continue; Expression ex; - if ( f.type.dimensions() > 0 ) { + if (f.type.dimensions() > 0) { MessageSend arrayToString = new MessageSend(); arrayToString.sourceStart = pS; arrayToString.sourceEnd = pE; arrayToString.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray()); arrayToString.arguments = new Expression[] { new SingleNameReference(f.name, p) }; Eclipse.setGeneratedBy(arrayToString.arguments[0], source); - if ( f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(f.type.getLastToken())) ) { + if (f.type.dimensions() > 1 || !BUILT_IN_TYPES.contains(new String(f.type.getLastToken()))) { arrayToString.selector = "deepToString".toCharArray(); } else { arrayToString.selector = "toString".toCharArray(); @@ -241,7 +241,7 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { } Eclipse.setGeneratedBy(ex, source); - if ( first ) { + if (first) { current = new BinaryExpression(current, ex, PLUS); current.sourceStart = pS; current.sourceEnd = pE; Eclipse.setGeneratedBy(current, source); @@ -250,7 +250,7 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { } StringLiteral fieldNameLiteral; - if ( includeFieldNames ) { + if (includeFieldNames) { char[] namePlusEqualsSign = (infixS + new String(f.name) + "=").toCharArray(); fieldNameLiteral = new StringLiteral(namePlusEqualsSign, pS, pE, 0); } else { @@ -262,7 +262,7 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { current = new BinaryExpression(current, ex, PLUS); Eclipse.setGeneratedBy(current, source); } - if ( !first ) { + if (!first) { StringLiteral suffixLiteral = new StringLiteral(suffix, pS, pE, 0); Eclipse.setGeneratedBy(suffixLiteral, source); current = new BinaryExpression(current, suffixLiteral, PLUS); @@ -296,7 +296,7 @@ public class HandleToString implements EclipseAnnotationHandler<ToString> { int pS = source.sourceStart, pE = source.sourceEnd; long p = (long)pS << 32 | pE; NameReference ref; - if ( varNames.length > 1 ) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); + if (varNames.length > 1) ref = new QualifiedNameReference(varNames, new long[varNames.length], pS, pE); else ref = new SingleNameReference(varNames[0], p); Eclipse.setGeneratedBy(ref, source); return ref; diff --git a/src/lombok/eclipse/handlers/PKG.java b/src/lombok/eclipse/handlers/PKG.java index 6bc4499d..65145262 100644 --- a/src/lombok/eclipse/handlers/PKG.java +++ b/src/lombok/eclipse/handlers/PKG.java @@ -32,8 +32,7 @@ import lombok.AccessLevel; import lombok.core.TransformationsUtil; import lombok.core.AST.Kind; import lombok.eclipse.Eclipse; -import lombok.eclipse.EclipseAST; -import lombok.eclipse.EclipseAST.Node; +import lombok.eclipse.EclipseNode; import org.eclipse.jdt.internal.compiler.ast.ASTNode; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; @@ -66,7 +65,7 @@ class PKG { } static int toModifier(AccessLevel value) { - switch ( value ) { + switch (value) { case MODULE: case PACKAGE: return 0; @@ -83,8 +82,8 @@ class PKG { static boolean nameEquals(char[][] typeName, String string) { StringBuilder sb = new StringBuilder(); boolean first = true; - for ( char[] elem : typeName ) { - if ( first ) first = false; + for (char[] elem : typeName) { + if (first) first = false; else sb.append('.'); sb.append(elem); } @@ -96,19 +95,19 @@ class PKG { NOT_EXISTS, EXISTS_BY_USER, EXISTS_BY_LOMBOK; } - static MemberExistsResult fieldExists(String fieldName, EclipseAST.Node node) { - while ( node != null && !(node.get() instanceof TypeDeclaration) ) { + static MemberExistsResult fieldExists(String fieldName, EclipseNode node) { + while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } - if ( node != null && node.get() instanceof TypeDeclaration ) { + if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); - if ( typeDecl.fields != null ) for ( FieldDeclaration def : typeDecl.fields ) { + if (typeDecl.fields != null) for (FieldDeclaration def : typeDecl.fields) { char[] fName = def.name; - if ( fName == null ) continue; - if ( fieldName.equals(new String(fName)) ) { - EclipseAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (fName == null) continue; + if (fieldName.equals(new String(fName))) { + EclipseNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -117,19 +116,19 @@ class PKG { return MemberExistsResult.NOT_EXISTS; } - static MemberExistsResult methodExists(String methodName, EclipseAST.Node node) { - while ( node != null && !(node.get() instanceof TypeDeclaration) ) { + static MemberExistsResult methodExists(String methodName, EclipseNode node) { + while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } - if ( node != null && node.get() instanceof TypeDeclaration ) { + if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); - if ( typeDecl.methods != null ) for ( AbstractMethodDeclaration def : typeDecl.methods ) { + if (typeDecl.methods != null) for (AbstractMethodDeclaration def : typeDecl.methods) { char[] mName = def.selector; - if ( mName == null ) continue; - if ( methodName.equals(new String(mName)) ) { - EclipseAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (mName == null) continue; + if (methodName.equals(new String(mName))) { + EclipseNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -138,18 +137,18 @@ class PKG { return MemberExistsResult.NOT_EXISTS; } - static MemberExistsResult constructorExists(EclipseAST.Node node) { - while ( node != null && !(node.get() instanceof TypeDeclaration) ) { + static MemberExistsResult constructorExists(EclipseNode node) { + while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } - if ( node != null && node.get() instanceof TypeDeclaration ) { + if (node != null && node.get() instanceof TypeDeclaration) { TypeDeclaration typeDecl = (TypeDeclaration)node.get(); - if ( typeDecl.methods != null ) for ( AbstractMethodDeclaration def : typeDecl.methods ) { - if ( def instanceof ConstructorDeclaration ) { - if ( (def.bits & ASTNode.IsDefaultConstructor) != 0 ) continue; - EclipseAST.Node existing = node.getNodeFor(def); - if ( existing == null || !existing.isHandled() ) return MemberExistsResult.EXISTS_BY_USER; + if (typeDecl.methods != null) for (AbstractMethodDeclaration def : typeDecl.methods) { + if (def instanceof ConstructorDeclaration) { + if ((def.bits & ASTNode.IsDefaultConstructor) != 0) continue; + EclipseNode existing = node.getNodeFor(def); + if (existing == null || !existing.isHandled()) return MemberExistsResult.EXISTS_BY_USER; return MemberExistsResult.EXISTS_BY_LOMBOK; } } @@ -158,17 +157,17 @@ class PKG { return MemberExistsResult.NOT_EXISTS; } - static EclipseAST.Node getExistingLombokConstructor(EclipseAST.Node node) { - while ( node != null && !(node.get() instanceof TypeDeclaration) ) { + static EclipseNode getExistingLombokConstructor(EclipseNode node) { + while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } - if ( node.get() instanceof TypeDeclaration ) { - for ( AbstractMethodDeclaration def : ((TypeDeclaration)node.get()).methods ) { - if ( def instanceof ConstructorDeclaration ) { - if ( (def.bits & ASTNode.IsDefaultConstructor) != 0 ) continue; - EclipseAST.Node existing = node.getNodeFor(def); - if ( existing.isHandled() ) return existing; + if (node.get() instanceof TypeDeclaration) { + for (AbstractMethodDeclaration def : ((TypeDeclaration)node.get()).methods) { + if (def instanceof ConstructorDeclaration) { + if ((def.bits & ASTNode.IsDefaultConstructor) != 0) continue; + EclipseNode existing = node.getNodeFor(def); + if (existing.isHandled()) return existing; } } } @@ -176,18 +175,18 @@ class PKG { return null; } - static EclipseAST.Node getExistingLombokMethod(String methodName, EclipseAST.Node node) { - while ( node != null && !(node.get() instanceof TypeDeclaration) ) { + static EclipseNode getExistingLombokMethod(String methodName, EclipseNode node) { + while (node != null && !(node.get() instanceof TypeDeclaration)) { node = node.up(); } - if ( node.get() instanceof TypeDeclaration ) { - for ( AbstractMethodDeclaration def : ((TypeDeclaration)node.get()).methods ) { + if (node.get() instanceof TypeDeclaration) { + for (AbstractMethodDeclaration def : ((TypeDeclaration)node.get()).methods) { char[] mName = def.selector; - if ( mName == null ) continue; - if ( methodName.equals(new String(mName)) ) { - EclipseAST.Node existing = node.getNodeFor(def); - if ( existing.isHandled() ) return existing; + if (mName == null) continue; + if (methodName.equals(new String(mName))) { + EclipseNode existing = node.getNodeFor(def); + if (existing.isHandled()) return existing; } } } @@ -195,10 +194,10 @@ class PKG { return null; } - static void injectField(EclipseAST.Node type, FieldDeclaration field) { + static void injectField(EclipseNode type, FieldDeclaration field) { TypeDeclaration parent = (TypeDeclaration) type.get(); - if ( parent.fields == null ) { + if (parent.fields == null) { parent.fields = new FieldDeclaration[1]; parent.fields[0] = field; } else { @@ -211,27 +210,27 @@ class PKG { type.add(field, Kind.FIELD).recursiveSetHandled(); } - static void injectMethod(EclipseAST.Node type, AbstractMethodDeclaration method) { + static void injectMethod(EclipseNode type, AbstractMethodDeclaration method) { TypeDeclaration parent = (TypeDeclaration) type.get(); - if ( parent.methods == null ) { + if (parent.methods == null) { parent.methods = new AbstractMethodDeclaration[1]; parent.methods[0] = method; } else { boolean injectionComplete = false; - if ( method instanceof ConstructorDeclaration ) { - for ( int i = 0 ; i < parent.methods.length ; i++ ) { - if ( parent.methods[i] instanceof ConstructorDeclaration && - (parent.methods[i].bits & ASTNode.IsDefaultConstructor) != 0 ) { - EclipseAST.Node tossMe = type.getNodeFor(parent.methods[i]); + if (method instanceof ConstructorDeclaration) { + for (int i = 0 ; i < parent.methods.length ; i++) { + if (parent.methods[i] instanceof ConstructorDeclaration && + (parent.methods[i].bits & ASTNode.IsDefaultConstructor) != 0) { + EclipseNode tossMe = type.getNodeFor(parent.methods[i]); parent.methods[i] = method; - if ( tossMe != null ) tossMe.up().removeChild(tossMe); + if (tossMe != null) tossMe.up().removeChild(tossMe); injectionComplete = true; break; } } } - if ( !injectionComplete ) { + if (!injectionComplete) { AbstractMethodDeclaration[] newArray = new AbstractMethodDeclaration[parent.methods.length + 1]; System.arraycopy(parent.methods, 0, newArray, 0, parent.methods.length); newArray[parent.methods.length] = method; @@ -244,13 +243,13 @@ class PKG { static Annotation[] findAnnotations(FieldDeclaration field, Pattern namePattern) { List<Annotation> result = new ArrayList<Annotation>(); - if ( field.annotations == null ) return new Annotation[0]; + if (field.annotations == null) return new Annotation[0]; for (Annotation annotation : field.annotations) { TypeReference typeRef = annotation.type; - if ( typeRef != null && typeRef.getTypeName()!= null ) { + if (typeRef != null && typeRef.getTypeName()!= null) { char[][] typeName = typeRef.getTypeName(); String suspect = new String(typeName[typeName.length - 1]); - if ( namePattern.matcher(suspect).matches() ) { + if (namePattern.matcher(suspect).matches()) { result.add(annotation); } } @@ -294,24 +293,24 @@ class PKG { return ann; } - static List<Integer> createListOfNonExistentFields(List<String> list, Node type, boolean excludeStandard, boolean excludeTransient) { + static List<Integer> createListOfNonExistentFields(List<String> list, EclipseNode type, boolean excludeStandard, boolean excludeTransient) { boolean[] matched = new boolean[list.size()]; - for ( Node child : type.down() ) { - if ( list.isEmpty() ) break; - if ( child.getKind() != Kind.FIELD ) continue; - if ( excludeStandard ) { - if ( (((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccStatic) != 0 ) continue; - if ( child.getName().startsWith("$") ) continue; + for (EclipseNode child : type.down()) { + if (list.isEmpty()) break; + if (child.getKind() != Kind.FIELD) continue; + if (excludeStandard) { + if ((((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccStatic) != 0) continue; + if (child.getName().startsWith("$")) continue; } - if ( excludeTransient && (((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccTransient) != 0 ) continue; + if (excludeTransient && (((FieldDeclaration)child.get()).modifiers & ClassFileConstants.AccTransient) != 0) continue; int idx = list.indexOf(child.getName()); - if ( idx > -1 ) matched[idx] = true; + if (idx > -1) matched[idx] = true; } List<Integer> problematic = new ArrayList<Integer>(); - for ( int i = 0 ; i < list.size() ; i++ ) { - if ( !matched[i] ) problematic.add(i); + for (int i = 0 ; i < list.size() ; i++) { + if (!matched[i]) problematic.add(i); } return problematic; |