diff --git a/org.eclipse.jdt.astview.feature/feature.xml b/org.eclipse.jdt.astview.feature/feature.xml index f5969b125e..99b1ca0347 100644 --- a/org.eclipse.jdt.astview.feature/feature.xml +++ b/org.eclipse.jdt.astview.feature/feature.xml @@ -2,12 +2,12 @@ - AST View for JDT 3.7.1, 3.8, and later + AST View for JDT 4.4 and later @@ -19,8 +19,8 @@ - - + + diff --git a/org.eclipse.jdt.astview.feature/pom.xml b/org.eclipse.jdt.astview.feature/pom.xml index 3d23dc962a..a6ae0766a8 100644 --- a/org.eclipse.jdt.astview.feature/pom.xml +++ b/org.eclipse.jdt.astview.feature/pom.xml @@ -18,6 +18,6 @@ org.eclipse.jdt.feature org.eclipse.jdt.astview.feature - 1.1.100-SNAPSHOT + 1.1.9-SNAPSHOT eclipse-feature diff --git a/org.eclipse.jdt.astview/META-INF/MANIFEST.MF b/org.eclipse.jdt.astview/META-INF/MANIFEST.MF index c7f9b6a700..46b6534fc8 100644 --- a/org.eclipse.jdt.astview/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.astview/META-INF/MANIFEST.MF @@ -2,16 +2,16 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.astview; singleton:=true -Bundle-Version: 1.1.8.qualifier -Eclipse-SourceReferences: scm:git:git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git;path="org.eclipse.jdt.astview";tag=R1_1_8 +Bundle-Version: 1.1.9.qualifier +Eclipse-SourceReferences: scm:git:git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git;path="org.eclipse.jdt.astview";tag=R4_4 Bundle-Activator: org.eclipse.jdt.astview.ASTViewPlugin Bundle-Vendor: %providerName Bundle-Localization: plugin Export-Package: org.eclipse.jdt.astview;x-internal:=true, org.eclipse.jdt.astview.views;x-internal:=true Require-Bundle: org.eclipse.core.runtime, - org.eclipse.jdt.core;bundle-version="[3.7.1,4.0.0)", - org.eclipse.jdt.ui;bundle-version="[3.7.1,4.0.0)", + org.eclipse.jdt.core;bundle-version="[3.10.0,4.0.0)", + org.eclipse.jdt.ui;bundle-version="[3.10.0,4.0.0)", org.eclipse.ui.ide, org.eclipse.ui.views, org.eclipse.jface.text, diff --git a/org.eclipse.jdt.astview/pom.xml b/org.eclipse.jdt.astview/pom.xml index 6985df321e..5f237e0f62 100644 --- a/org.eclipse.jdt.astview/pom.xml +++ b/org.eclipse.jdt.astview/pom.xml @@ -18,6 +18,6 @@ org.eclipse.jdt org.eclipse.jdt.astview - 1.1.8-SNAPSHOT + 1.1.9-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/GenericVisitor.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/GenericVisitor.java deleted file mode 100644 index 38ee08f48b..0000000000 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/GenericVisitor.java +++ /dev/null @@ -1,765 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.astview; - -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; -import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayAccess; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.AssertStatement; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BlockComment; -import org.eclipse.jdt.core.dom.BooleanLiteral; -import org.eclipse.jdt.core.dom.BreakStatement; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CatchClause; -import org.eclipse.jdt.core.dom.CharacterLiteral; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ConditionalExpression; -import org.eclipse.jdt.core.dom.ConstructorInvocation; -import org.eclipse.jdt.core.dom.ContinueStatement; -import org.eclipse.jdt.core.dom.DoStatement; -import org.eclipse.jdt.core.dom.EmptyStatement; -import org.eclipse.jdt.core.dom.EnhancedForStatement; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IfStatement; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.InfixExpression; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.InstanceofExpression; -import org.eclipse.jdt.core.dom.Javadoc; -import org.eclipse.jdt.core.dom.LabeledStatement; -import org.eclipse.jdt.core.dom.LineComment; -import org.eclipse.jdt.core.dom.MarkerAnnotation; -import org.eclipse.jdt.core.dom.MemberRef; -import org.eclipse.jdt.core.dom.MemberValuePair; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodRef; -import org.eclipse.jdt.core.dom.MethodRefParameter; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.NormalAnnotation; -import org.eclipse.jdt.core.dom.NullLiteral; -import org.eclipse.jdt.core.dom.NumberLiteral; -import org.eclipse.jdt.core.dom.PackageDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PostfixExpression; -import org.eclipse.jdt.core.dom.PrefixExpression; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.ReturnStatement; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleMemberAnnotation; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.SynchronizedStatement; -import org.eclipse.jdt.core.dom.TagElement; -import org.eclipse.jdt.core.dom.TextElement; -import org.eclipse.jdt.core.dom.ThisExpression; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.TryStatement; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.TypeDeclarationStatement; -import org.eclipse.jdt.core.dom.TypeLiteral; -import org.eclipse.jdt.core.dom.TypeParameter; -import org.eclipse.jdt.core.dom.UnionType; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; -import org.eclipse.jdt.core.dom.WhileStatement; -import org.eclipse.jdt.core.dom.WildcardType; - -public class GenericVisitor extends ASTVisitor { - - public GenericVisitor() { - super(); - } - - /** - * @param visitJavadocTags true if doc comment tags are - * to be visited by default, and false otherwise - * @see Javadoc#tags() - * @see #visit(Javadoc) - * @since 3.0 - */ - public GenericVisitor(boolean visitJavadocTags) { - super(visitJavadocTags); - } - - //---- Hooks for subclasses ------------------------------------------------- - - protected boolean visitNode(ASTNode node) { - return true; - } - - protected void endVisitNode(ASTNode node) { - // do nothing - } - - public boolean visit(AnonymousClassDeclaration node) { - return visitNode(node); - } - public boolean visit(ArrayAccess node) { - return visitNode(node); - } - public boolean visit(ArrayCreation node) { - return visitNode(node); - } - public boolean visit(ArrayInitializer node) { - return visitNode(node); - } - public boolean visit(ArrayType node) { - return visitNode(node); - } - public boolean visit(AssertStatement node) { - return visitNode(node); - } - public boolean visit(Assignment node) { - return visitNode(node); - } - public boolean visit(Block node) { - return visitNode(node); - } - public boolean visit(BooleanLiteral node) { - return visitNode(node); - } - public boolean visit(BreakStatement node) { - return visitNode(node); - } - public boolean visit(CastExpression node) { - return visitNode(node); - } - public boolean visit(CatchClause node) { - return visitNode(node); - } - public boolean visit(CharacterLiteral node) { - return visitNode(node); - } - public boolean visit(ClassInstanceCreation node) { - return visitNode(node); - } - public boolean visit(CompilationUnit node) { - return visitNode(node); - } - public boolean visit(ConditionalExpression node) { - return visitNode(node); - } - public boolean visit(ConstructorInvocation node) { - return visitNode(node); - } - public boolean visit(ContinueStatement node) { - return visitNode(node); - } - public boolean visit(DoStatement node) { - return visitNode(node); - } - public boolean visit(EmptyStatement node) { - return visitNode(node); - } - public boolean visit(ExpressionStatement node) { - return visitNode(node); - } - public boolean visit(FieldAccess node) { - return visitNode(node); - } - public boolean visit(FieldDeclaration node) { - return visitNode(node); - } - public boolean visit(ForStatement node) { - return visitNode(node); - } - public boolean visit(IfStatement node) { - return visitNode(node); - } - public boolean visit(ImportDeclaration node) { - return visitNode(node); - } - public boolean visit(InfixExpression node) { - return visitNode(node); - } - public boolean visit(InstanceofExpression node) { - return visitNode(node); - } - public boolean visit(Initializer node) { - return visitNode(node); - } - public boolean visit(Javadoc node) { - if (super.visit(node)) - return visitNode(node); - else - return false; - } - public boolean visit(LabeledStatement node) { - return visitNode(node); - } - public boolean visit(MethodDeclaration node) { - return visitNode(node); - } - public boolean visit(MethodInvocation node) { - return visitNode(node); - } - public boolean visit(NullLiteral node) { - return visitNode(node); - } - public boolean visit(NumberLiteral node) { - return visitNode(node); - } - public boolean visit(PackageDeclaration node) { - return visitNode(node); - } - public boolean visit(ParenthesizedExpression node) { - return visitNode(node); - } - public boolean visit(PostfixExpression node) { - return visitNode(node); - } - public boolean visit(PrefixExpression node) { - return visitNode(node); - } - public boolean visit(PrimitiveType node) { - return visitNode(node); - } - public boolean visit(QualifiedName node) { - return visitNode(node); - } - public boolean visit(ReturnStatement node) { - return visitNode(node); - } - public boolean visit(SimpleName node) { - return visitNode(node); - } - public boolean visit(SimpleType node) { - return visitNode(node); - } - public boolean visit(StringLiteral node) { - return visitNode(node); - } - public boolean visit(SuperConstructorInvocation node) { - return visitNode(node); - } - public boolean visit(SuperFieldAccess node) { - return visitNode(node); - } - public boolean visit(SuperMethodInvocation node) { - return visitNode(node); - } - public boolean visit(SwitchCase node) { - return visitNode(node); - } - public boolean visit(SwitchStatement node) { - return visitNode(node); - } - public boolean visit(SynchronizedStatement node) { - return visitNode(node); - } - public boolean visit(ThisExpression node) { - return visitNode(node); - } - public boolean visit(ThrowStatement node) { - return visitNode(node); - } - public boolean visit(TryStatement node) { - return visitNode(node); - } - public boolean visit(TypeDeclaration node) { - return visitNode(node); - } - public boolean visit(TypeDeclarationStatement node) { - return visitNode(node); - } - public boolean visit(TypeLiteral node) { - return visitNode(node); - } - public boolean visit(UnionType node) { - return visitNode(node); - } - public boolean visit(SingleVariableDeclaration node) { - return visitNode(node); - } - public boolean visit(VariableDeclarationExpression node) { - return visitNode(node); - } - public boolean visit(VariableDeclarationStatement node) { - return visitNode(node); - } - public boolean visit(VariableDeclarationFragment node) { - return visitNode(node); - } - public boolean visit(WhileStatement node) { - return visitNode(node); - } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) - */ - public boolean visit(AnnotationTypeDeclaration node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) - */ - public boolean visit(AnnotationTypeMemberDeclaration node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.BlockComment) - */ - public boolean visit(BlockComment node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnhancedForStatement) - */ - public boolean visit(EnhancedForStatement node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumConstantDeclaration) - */ - public boolean visit(EnumConstantDeclaration node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumDeclaration) - */ - public boolean visit(EnumDeclaration node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.LineComment) - */ - public boolean visit(LineComment node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MarkerAnnotation) - */ - public boolean visit(MarkerAnnotation node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberRef) - */ - public boolean visit(MemberRef node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberValuePair) - */ - public boolean visit(MemberValuePair node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRef) - */ - public boolean visit(MethodRef node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRefParameter) - */ - public boolean visit(MethodRefParameter node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Modifier) - */ - public boolean visit(Modifier node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.NormalAnnotation) - */ - public boolean visit(NormalAnnotation node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ParameterizedType) - */ - public boolean visit(ParameterizedType node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.QualifiedType) - */ - public boolean visit(QualifiedType node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.SingleMemberAnnotation) - */ - public boolean visit(SingleMemberAnnotation node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TagElement) - */ - public boolean visit(TagElement node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TextElement) - */ - public boolean visit(TextElement node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TypeParameter) - */ - public boolean visit(TypeParameter node) { - return visitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.WildcardType) - */ - public boolean visit(WildcardType node) { - return visitNode(node); - } - - public void endVisit(AnonymousClassDeclaration node) { - endVisitNode(node); - } - public void endVisit(ArrayAccess node) { - endVisitNode(node); - } - public void endVisit(ArrayCreation node) { - endVisitNode(node); - } - public void endVisit(ArrayInitializer node) { - endVisitNode(node); - } - public void endVisit(ArrayType node) { - endVisitNode(node); - } - public void endVisit(AssertStatement node) { - endVisitNode(node); - } - public void endVisit(Assignment node) { - endVisitNode(node); - } - public void endVisit(Block node) { - endVisitNode(node); - } - public void endVisit(BooleanLiteral node) { - endVisitNode(node); - } - public void endVisit(BreakStatement node) { - endVisitNode(node); - } - public void endVisit(CastExpression node) { - endVisitNode(node); - } - public void endVisit(CatchClause node) { - endVisitNode(node); - } - public void endVisit(CharacterLiteral node) { - endVisitNode(node); - } - public void endVisit(ClassInstanceCreation node) { - endVisitNode(node); - } - public void endVisit(CompilationUnit node) { - endVisitNode(node); - } - public void endVisit(ConditionalExpression node) { - endVisitNode(node); - } - public void endVisit(ConstructorInvocation node) { - endVisitNode(node); - } - public void endVisit(ContinueStatement node) { - endVisitNode(node); - } - public void endVisit(DoStatement node) { - endVisitNode(node); - } - public void endVisit(EmptyStatement node) { - endVisitNode(node); - } - public void endVisit(ExpressionStatement node) { - endVisitNode(node); - } - public void endVisit(FieldAccess node) { - endVisitNode(node); - } - public void endVisit(FieldDeclaration node) { - endVisitNode(node); - } - public void endVisit(ForStatement node) { - endVisitNode(node); - } - public void endVisit(IfStatement node) { - endVisitNode(node); - } - public void endVisit(ImportDeclaration node) { - endVisitNode(node); - } - public void endVisit(InfixExpression node) { - endVisitNode(node); - } - public void endVisit(InstanceofExpression node) { - endVisitNode(node); - } - public void endVisit(Initializer node) { - endVisitNode(node); - } - public void endVisit(Javadoc node) { - endVisitNode(node); - } - public void endVisit(LabeledStatement node) { - endVisitNode(node); - } - public void endVisit(MethodDeclaration node) { - endVisitNode(node); - } - public void endVisit(MethodInvocation node) { - endVisitNode(node); - } - public void endVisit(NullLiteral node) { - endVisitNode(node); - } - public void endVisit(NumberLiteral node) { - endVisitNode(node); - } - public void endVisit(PackageDeclaration node) { - endVisitNode(node); - } - public void endVisit(ParenthesizedExpression node) { - endVisitNode(node); - } - public void endVisit(PostfixExpression node) { - endVisitNode(node); - } - public void endVisit(PrefixExpression node) { - endVisitNode(node); - } - public void endVisit(PrimitiveType node) { - endVisitNode(node); - } - public void endVisit(QualifiedName node) { - endVisitNode(node); - } - public void endVisit(ReturnStatement node) { - endVisitNode(node); - } - public void endVisit(SimpleName node) { - endVisitNode(node); - } - public void endVisit(SimpleType node) { - endVisitNode(node); - } - public void endVisit(StringLiteral node) { - endVisitNode(node); - } - public void endVisit(SuperConstructorInvocation node) { - endVisitNode(node); - } - public void endVisit(SuperFieldAccess node) { - endVisitNode(node); - } - public void endVisit(SuperMethodInvocation node) { - endVisitNode(node); - } - public void endVisit(SwitchCase node) { - endVisitNode(node); - } - public void endVisit(SwitchStatement node) { - endVisitNode(node); - } - public void endVisit(SynchronizedStatement node) { - endVisitNode(node); - } - public void endVisit(ThisExpression node) { - endVisitNode(node); - } - public void endVisit(ThrowStatement node) { - endVisitNode(node); - } - public void endVisit(TryStatement node) { - endVisitNode(node); - } - public void endVisit(TypeDeclaration node) { - endVisitNode(node); - } - public void endVisit(TypeDeclarationStatement node) { - endVisitNode(node); - } - public void endVisit(TypeLiteral node) { - endVisitNode(node); - } - public void endVisit(UnionType node) { - endVisitNode(node); - } - public void endVisit(SingleVariableDeclaration node) { - endVisitNode(node); - } - public void endVisit(VariableDeclarationExpression node) { - endVisitNode(node); - } - public void endVisit(VariableDeclarationStatement node) { - endVisitNode(node); - } - public void endVisit(VariableDeclarationFragment node) { - endVisitNode(node); - } - public void endVisit(WhileStatement node) { - endVisitNode(node); - } - - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) - */ - public void endVisit(AnnotationTypeDeclaration node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) - */ - public void endVisit(AnnotationTypeMemberDeclaration node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.BlockComment) - */ - public void endVisit(BlockComment node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnhancedForStatement) - */ - public void endVisit(EnhancedForStatement node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnumConstantDeclaration) - */ - public void endVisit(EnumConstantDeclaration node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnumDeclaration) - */ - public void endVisit(EnumDeclaration node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.LineComment) - */ - public void endVisit(LineComment node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MarkerAnnotation) - */ - public void endVisit(MarkerAnnotation node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MemberRef) - */ - public void endVisit(MemberRef node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MemberValuePair) - */ - public void endVisit(MemberValuePair node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MethodRef) - */ - public void endVisit(MethodRef node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MethodRefParameter) - */ - public void endVisit(MethodRefParameter node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.Modifier) - */ - public void endVisit(Modifier node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.NormalAnnotation) - */ - public void endVisit(NormalAnnotation node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.ParameterizedType) - */ - public void endVisit(ParameterizedType node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.QualifiedType) - */ - public void endVisit(QualifiedType node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.SingleMemberAnnotation) - */ - public void endVisit(SingleMemberAnnotation node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TagElement) - */ - public void endVisit(TagElement node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TextElement) - */ - public void endVisit(TextElement node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TypeParameter) - */ - public void endVisit(TypeParameter node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.WildcardType) - */ - public void endVisit(WildcardType node) { - endVisitNode(node); - } - -} diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/NodeFinder.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/NodeFinder.java deleted file mode 100644 index a659f0774c..0000000000 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/NodeFinder.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.astview; - -import org.eclipse.jdt.core.dom.ASTNode; - -/** - * For a give range finds the node covered and the node covering. - */ -public class NodeFinder extends GenericVisitor { - - /** - * A visitor that maps a selection to a given ASTNode. The result node is - * determined as follows: - *
    - *
  • first the visitor tries to find a node with the exact start and length
  • - *
  • if no such node exists than the node that encloses the range defined by - * start and end is returned.
  • - *
  • if the length is zero than also nodes are considered where the node's - * start or end position matches start.
  • - *
  • otherwise null is returned.
  • - *
- */ - public static ASTNode perform(ASTNode root, int start, int length) { - NodeFinder finder= new NodeFinder(start, length); - root.accept(finder); - ASTNode result= finder.getCoveredNode(); - if (result == null || result.getStartPosition() != start || result.getLength() != length) { - return finder.getCoveringNode(); - } - return result; - } - - private int fStart; - private int fEnd; - - private ASTNode fCoveringNode; - private ASTNode fCoveredNode; - - public NodeFinder(int offset, int length) { - super(true); // include Javadoc tags - fStart= offset; - fEnd= offset + length; - } - - protected boolean visitNode(ASTNode node) { - int nodeStart= node.getStartPosition(); - int nodeEnd= nodeStart + node.getLength(); - if (nodeEnd < fStart || fEnd < nodeStart) { - return false; - } - if (nodeStart <= fStart && fEnd <= nodeEnd) { - fCoveringNode= node; - } - if (fStart <= nodeStart && nodeEnd <= fEnd) { - if (fCoveringNode == node) { // nodeStart == fStart && nodeEnd == fEnd - fCoveredNode= node; - return true; // look further for node with same length as parent - } else if (fCoveredNode == null) { // no better found - fCoveredNode= node; - } - return false; - } - return true; - } - - /** - * Returns the covered node. If more than one nodes are covered by the selection, the - * returned node is first covered node found in a top-down traversal of the AST - * @return ASTNode - */ - public ASTNode getCoveredNode() { - return fCoveredNode; - } - - /** - * Returns the covering node. If more than one nodes are covering the selection, the - * returned node is last covering node found in a top-down traversal of the AST - * @return ASTNode - */ - public ASTNode getCoveringNode() { - return fCoveringNode; - } - -} diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/TreeInfoCollector.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/TreeInfoCollector.java index 828b21e8a9..80595d9125 100644 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/TreeInfoCollector.java +++ b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/TreeInfoCollector.java @@ -1,16 +1,17 @@ /******************************************************************************* - * Copyright (c) 2000, 2005 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.astview; import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.CompilationUnit; /** @@ -18,13 +19,12 @@ */ public class TreeInfoCollector { - public static class NodeCounter extends GenericVisitor { + public static class NodeCounter extends ASTVisitor { public int numberOfNodes= 0; - protected boolean visitNode(ASTNode node) { + public void preVisit(ASTNode node) { numberOfNodes++; - return true; } } diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTView.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTView.java index 20ff6c616d..c01088d991 100644 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTView.java +++ b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTView.java @@ -4,7 +4,7 @@ * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -75,6 +75,7 @@ import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.ISelectionService; import org.eclipse.ui.ISharedImages; +import org.eclipse.ui.IViewPart; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchCommandConstants; @@ -85,6 +86,7 @@ import org.eclipse.ui.handlers.IHandlerService; import org.eclipse.ui.part.DrillDownAdapter; import org.eclipse.ui.part.IShowInSource; +import org.eclipse.ui.part.IShowInTarget; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.ui.texteditor.ITextEditor; @@ -92,7 +94,6 @@ import org.eclipse.jdt.astview.ASTViewImages; import org.eclipse.jdt.astview.ASTViewPlugin; import org.eclipse.jdt.astview.EditorUtility; -import org.eclipse.jdt.astview.NodeFinder; import org.eclipse.jdt.astview.TreeInfoCollector; import org.eclipse.jdt.core.IClassFile; @@ -112,21 +113,28 @@ import org.eclipse.jdt.core.dom.ASTRequestor; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.SharedASTProvider; -import org.eclipse.jdt.ui.actions.ShowInPackageViewAction; public class ASTView extends ViewPart implements IShowInSource { + static final int JLS_LATEST= AST.JLS8; + + private static final int JLS8= AST.JLS8; + + /** + * @deprecated to get rid of deprecation warnings in code + */ private static final int JLS4= AST.JLS4; - /** (Used to get rid of deprecation warnings in code) - * @deprecated + /** + * @deprecated to get rid of deprecation warnings in code */ private static final int JLS3= AST.JLS3; - /** (Used to get rid of deprecation warnings in code) - * @deprecated + /** + * @deprecated to get rid of deprecation warnings in code */ private static final int JLS2= AST.JLS2; @@ -459,13 +467,14 @@ public ASTView() { fStatementsRecovery= !fDialogSettings.getBoolean(SETTINGS_NO_STATEMENTS_RECOVERY); // inverse so that default is use recovery fBindingsRecovery= !fDialogSettings.getBoolean(SETTINGS_NO_BINDINGS_RECOVERY); // inverse so that default is use recovery fIgnoreMethodBodies= fDialogSettings.getBoolean(SETTINGS_IGNORE_METHOD_BODIES); - fCurrentASTLevel= JLS4; + fCurrentASTLevel= JLS_LATEST; try { int level= fDialogSettings.getInt(SETTINGS_JLS); switch (level) { case JLS2: case JLS3: case JLS4: + case JLS8: fCurrentASTLevel= level; } } catch (NumberFormatException e) { @@ -539,13 +548,19 @@ private CompilationUnit internalSetInput(ITypeRoot input, int offset, int length throw new CoreException(getErrorStatus("Input has no buffer", null)); //$NON-NLS-1$ } + CompilationUnit root; try { - CompilationUnit root= createAST(input, offset); + root= createAST(input, offset); resetView(root); if (root == null) { setContentDescription("AST could not be created."); //$NON-NLS-1$ return null; } + } catch (RuntimeException e) { + throw new CoreException(getErrorStatus("Could not create AST:\n" + e.getMessage(), e)); //$NON-NLS-1$ + } + + try { ASTNode node= NodeFinder.perform(root, offset, length); if (node != null) { fViewer.getTree().setRedraw(false); @@ -556,11 +571,11 @@ private CompilationUnit internalSetInput(ITypeRoot input, int offset, int length fViewer.getTree().setRedraw(true); } } - return root; - } catch (RuntimeException e) { - throw new CoreException(getErrorStatus("Could not create AST:\n" + e.getMessage(), e)); //$NON-NLS-1$ + showAndLogError("Could not select node for editor selection", e); //$NON-NLS-1$ } + + return root; } private void clearView() { @@ -1044,9 +1059,10 @@ public void run() { ASTViewImages.setImageDescriptors(fLinkWithEditor, ASTViewImages.LINK_WITH_EDITOR); fASTVersionToggleActions= new ASTLevelToggle[] { - new ASTLevelToggle("AST Level &2.0", JLS2), //$NON-NLS-1$ - new ASTLevelToggle("AST Level &3.0", JLS3), //$NON-NLS-1$ - new ASTLevelToggle("AST Level &4.0", JLS4), //$NON-NLS-1$ + new ASTLevelToggle("AST Level &2 (1.2)", JLS2), //$NON-NLS-1$ + new ASTLevelToggle("AST Level &3 (1.5)", JLS3), //$NON-NLS-1$ + new ASTLevelToggle("AST Level &4 (1.7)", JLS4), //$NON-NLS-1$ + new ASTLevelToggle("AST Level &8 (1.8)", JLS8), //$NON-NLS-1$ }; fAddToTrayAction= new Action() { @@ -1202,9 +1218,7 @@ private void doLinkWithEditor(ISelection selection) { int offset= textSelection.getOffset(); int length= textSelection.getLength(); - NodeFinder finder= new NodeFinder(offset, length); - fRoot.accept(finder); - ASTNode covering= finder.getCoveringNode(); + ASTNode covering= NodeFinder.perform(fRoot, offset, length); if (covering != null) { fViewer.reveal(covering); fViewer.setSelection(new StructuredSelection(covering)); @@ -1475,8 +1489,15 @@ protected void performDoubleClick() { } else if (obj instanceof JavaElement) { IJavaElement javaElement= ((JavaElement) obj).getJavaElement(); if (javaElement instanceof IPackageFragment) { - ShowInPackageViewAction showInPackageViewAction= new ShowInPackageViewAction(getViewSite()); - showInPackageViewAction.run(javaElement); + try { + IViewPart packageExplorer= getSite().getPage().showView(JavaUI.ID_PACKAGES); + if (packageExplorer instanceof IShowInTarget) { + IShowInTarget showInTarget= (IShowInTarget) packageExplorer; + showInTarget.show(getShowInContext()); + } + } catch (PartInitException e) { + showAndLogError("Could not open Package Explorer.", e); //$NON-NLS-1$ + } } else { try { IEditorPart editorPart= JavaUI.openInEditor(javaElement); diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewContentProvider.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewContentProvider.java index a3d0e3031f..e1bfe1fd1f 100644 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewContentProvider.java +++ b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewContentProvider.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -17,6 +17,8 @@ import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; +import org.eclipse.jdt.astview.ASTViewPlugin; + import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.Annotation; @@ -34,11 +36,13 @@ import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MemberRef; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.MethodRef; +import org.eclipse.jdt.core.dom.MethodReference; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; @@ -139,6 +143,19 @@ private Object[] getNodeChildren(ASTNode node) { } else if (expression instanceof Annotation) { IAnnotationBinding binding= ((Annotation) expression).resolveAnnotationBinding(); res.add(createBinding(expression, binding)); + } else if (expression instanceof LambdaExpression) { + ASTAttribute bindingAttribute; + try { + IMethodBinding binding= ((LambdaExpression) expression).resolveMethodBinding(); + bindingAttribute= createBinding(expression, binding); + } catch (RuntimeException e) { + bindingAttribute= new Error(res, ">binding: Error: " + e.getMessage(), e); + ASTViewPlugin.log("Exception thrown in LambdaExpression#resolveMethodBinding() for \"" + expression + "\"", e); + } + res.add(bindingAttribute); + } else if (expression instanceof MethodReference) { + IMethodBinding binding= ((MethodReference) expression).resolveMethodBinding(); + res.add(createBinding(expression, binding)); } // Expression attributes: res.add(new GeneralAttribute(expression, "Boxing: " + expression.resolveBoxing() + "; Unboxing: " + expression.resolveUnboxing())); //$NON-NLS-1$ //$NON-NLS-2$ diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewLabelProvider.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewLabelProvider.java index 88aee201e6..c5505b4e32 100644 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewLabelProvider.java +++ b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/ASTViewLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,6 +11,9 @@ package org.eclipse.jdt.astview.views; +import java.util.Iterator; +import java.util.List; + import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; @@ -183,7 +186,7 @@ private boolean isNotProperlyNested(Object element) { private boolean isInsideNode(ASTNode node) { int start= node.getStartPosition(); int end= start + node.getLength(); - if (start <= fSelectionStart && (fSelectionStart + fSelectionLength) < end) { + if (start <= fSelectionStart && (fSelectionStart + fSelectionLength) <= end) { return true; } return false; @@ -197,6 +200,13 @@ private boolean isInside(Object element) { Object object= property.getNode(); if (object instanceof ASTNode) { return isInsideNode((ASTNode) object); + } else if (object instanceof List) { + for (Iterator iter= ((List) object).iterator(); iter.hasNext(); ) { + Object child= iter.next(); + if (isInside(child)) { + return true; + } + } } } return false; diff --git a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/Binding.java b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/Binding.java index aacab5d2bc..f2e65b3e4e 100644 --- a/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/Binding.java +++ b/org.eclipse.jdt.astview/src/org/eclipse/jdt/astview/views/Binding.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials + * Copyright (c) 2000, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -16,7 +16,6 @@ import org.eclipse.jdt.astview.ASTViewPlugin; -import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CharacterLiteral; @@ -27,6 +26,7 @@ import org.eclipse.jdt.core.dom.IPackageBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.StringLiteral; @@ -76,7 +76,14 @@ private static boolean isType(int typeKinds, int kind) { * @see org.eclipse.jdt.astview.views.ASTAttribute#getChildren() */ public Object[] getChildren() { - + try { + if (fBinding != null) { + fBinding.getKey(); + } + } catch (RuntimeException e) { + ASTViewPlugin.log("Exception thrown in IBinding#getKey() for \"" + fBinding + "\"", e); + return new Object[] { new Error(this, "BrokenBinding: " + fBinding, null) }; + } if (fBinding != null) { ArrayList res= new ArrayList(); res.add(new BindingProperty(this, "NAME", fBinding.getName(), true)); //$NON-NLS-1$ @@ -89,7 +96,7 @@ public Object[] getChildren() { res.add(new BindingProperty(this, "IS ENUM CONSTANT", variableBinding.isEnumConstant(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS PARAMETER", variableBinding.isParameter(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "VARIABLE ID", variableBinding.getVariableId(), true)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "MODIFIERS", Flags.toString(fBinding.getModifiers()), true)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "MODIFIERS", getModifiersString(fBinding.getModifiers(), false), true)); //$NON-NLS-1$ res.add(new Binding(this, "TYPE", variableBinding.getType(), true)); //$NON-NLS-1$ res.add(new Binding(this, "DECLARING CLASS", variableBinding.getDeclaringClass(), true)); //$NON-NLS-1$ res.add(new Binding(this, "DECLARING METHOD", variableBinding.getDeclaringMethod(), true)); //$NON-NLS-1$ @@ -97,6 +104,7 @@ public Object[] getChildren() { res.add(new BindingProperty(this, "IS SYNTHETIC", fBinding.isSynthetic(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS DEPRECATED", fBinding.isDeprecated(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "CONSTANT VALUE", variableBinding.getConstantValue(), true)); //$NON-NLS-1$ //$NON-NLS-2$ + res.add(new BindingProperty(this, "IS EFFECTIVELY FINAL", variableBinding.isEffectivelyFinal(), true)); //$NON-NLS-1$ break; case IBinding.PACKAGE: @@ -154,8 +162,6 @@ public Object[] getChildren() { } } - res.add(new BindingProperty(this, "TYPE BOUNDS", typeBinding.getTypeBounds(), isType(typeKind, VARIABLE_TYPE | CAPTURE_TYPE))); //$NON-NLS-1$ - StringBuffer origin= new StringBuffer("ORIGIN:"); //$NON-NLS-1$ if (typeBinding.isTopLevel()) origin.append(" isTopLevel"); //$NON-NLS-1$ if (typeBinding.isNested()) origin.append(" isNested"); //$NON-NLS-1$ @@ -169,13 +175,16 @@ public Object[] getChildren() { res.add(new Binding(this, "PACKAGE", typeBinding.getPackage(), isRefType)); //$NON-NLS-1$ res.add(new Binding(this, "DECLARING CLASS", typeBinding.getDeclaringClass(), isType(typeKind, REF_TYPE | VARIABLE_TYPE | CAPTURE_TYPE))); //$NON-NLS-1$ res.add(new Binding(this, "DECLARING METHOD", typeBinding.getDeclaringMethod(), isType(typeKind, REF_TYPE | VARIABLE_TYPE | CAPTURE_TYPE))); //$NON-NLS-1$ - res.add(new BindingProperty(this, "MODIFIERS", Flags.toString(fBinding.getModifiers()), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "MODIFIERS", getModifiersString(fBinding.getModifiers(), false), isRefType)); //$NON-NLS-1$ res.add(new BindingProperty(this, "BINARY NAME", typeBinding.getBinaryName(), true)); //$NON-NLS-1$ - res.add(new Binding(this, "TYPE DECLARATION", typeBinding.getTypeDeclaration(), isNonPrimitive)); //$NON-NLS-1$ - res.add(new Binding(this, "ERASURE", typeBinding.getErasure(), isNonPrimitive)); //$NON-NLS-1$ + String isTypeDeclaration= typeBinding == typeBinding.getTypeDeclaration() ? " ( == this)" : " ( != this)"; + res.add(new Binding(this, "TYPE DECLARATION" + isTypeDeclaration, typeBinding.getTypeDeclaration(), true)); //$NON-NLS-1$ + String isErasure= typeBinding == typeBinding.getErasure() ? " ( == this)" : " ( != this)"; + res.add(new Binding(this, "ERASURE" + isErasure, typeBinding.getErasure(), isNonPrimitive)); //$NON-NLS-1$ res.add(new BindingProperty(this, "TYPE PARAMETERS", typeBinding.getTypeParameters(), isType(typeKind, GENERIC))); //$NON-NLS-1$ res.add(new BindingProperty(this, "TYPE ARGUMENTS", typeBinding.getTypeArguments(), isType(typeKind, PARAMETRIZED))); //$NON-NLS-1$ + res.add(new BindingProperty(this, "TYPE BOUNDS", typeBinding.getTypeBounds(), isType(typeKind, VARIABLE_TYPE | WILDCARD_TYPE | CAPTURE_TYPE))); //$NON-NLS-1$ res.add(new Binding(this, "BOUND", typeBinding.getBound(), isType(typeKind, WILDCARD_TYPE))); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS UPPERBOUND", typeBinding.isUpperbound(), isType(typeKind, WILDCARD_TYPE))); //$NON-NLS-1$ res.add(new Binding(this, "GENERIC TYPE OF WILDCARD TYPE", typeBinding.getGenericTypeOfWildcardType(), isType(typeKind, WILDCARD_TYPE))); //$NON-NLS-1$ @@ -183,12 +192,14 @@ public Object[] getChildren() { res.add(new Binding(this, "WILDCARD", typeBinding.getWildcard(), isType(typeKind, CAPTURE_TYPE))); //$NON-NLS-1$ res.add(new Binding(this, "SUPERCLASS", typeBinding.getSuperclass(), isRefType)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "INTERFACES", typeBinding.getInterfaces(), isRefType)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "DECLARED TYPES", typeBinding.getDeclaredTypes(), isRefType)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "DECLARED FIELDS", typeBinding.getDeclaredFields(), isRefType)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "DECLARED METHODS", typeBinding.getDeclaredMethods(), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "INTERFACES", typeBinding.getInterfaces(), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "DECLARED TYPES", typeBinding.getDeclaredTypes(), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "DECLARED FIELDS", typeBinding.getDeclaredFields(), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "DECLARED METHODS", typeBinding.getDeclaredMethods(), isRefType)); //$NON-NLS-1$ + res.add(new Binding(this, "FUNCTIONAL INTERFACE METHOD", typeBinding.getFunctionalInterfaceMethod(), typeBinding.isInterface())); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS SYNTHETIC", fBinding.isSynthetic(), isNonPrimitive)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS DEPRECATED", fBinding.isDeprecated(), isRefType)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "TYPE ANNOTATIONS", typeBinding.getTypeAnnotations(), true)); //$NON-NLS-1$ break; case IBinding.METHOD: @@ -197,7 +208,7 @@ public Object[] getChildren() { res.add(new BindingProperty(this, "IS DEFAULT CONSTRUCTOR", methodBinding.isDefaultConstructor(), true)); //$NON-NLS-1$ res.add(new Binding(this, "DECLARING CLASS", methodBinding.getDeclaringClass(), true)); //$NON-NLS-1$ res.add(new Binding(this, "RETURN TYPE", methodBinding.getReturnType(), true)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "MODIFIERS", Flags.toString(fBinding.getModifiers()), true)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "MODIFIERS", getModifiersString(fBinding.getModifiers(), true), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "PARAMETER TYPES", methodBinding.getParameterTypes(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS VARARGS", methodBinding.isVarargs(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "EXCEPTION TYPES", methodBinding.getExceptionTypes(), true)); //$NON-NLS-1$ @@ -208,9 +219,10 @@ public Object[] getChildren() { if (methodBinding.isParameterizedMethod()) genericsM.append(" isParameterizedMethod"); //$NON-NLS-1$ res.add(new BindingProperty(this, genericsM, true)); - res.add(new Binding(this, "METHOD DECLARATION", methodBinding.getMethodDeclaration(), true)); //$NON-NLS-1$ + String isMethodDeclaration= methodBinding == methodBinding.getMethodDeclaration() ? " ( == this)" : " ( != this)"; + res.add(new Binding(this, "METHOD DECLARATION" + isMethodDeclaration, methodBinding.getMethodDeclaration(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "TYPE PARAMETERS", methodBinding.getTypeParameters(), true)); //$NON-NLS-1$ - res.add(new BindingProperty(this, "TYPE ARGUMENTS", methodBinding.getTypeArguments(), true)); //$NON-NLS-1$ + res.add(new BindingProperty(this, "TYPE ARGUMENTS", methodBinding.getTypeArguments(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS SYNTHETIC", fBinding.isSynthetic(), true)); //$NON-NLS-1$ res.add(new BindingProperty(this, "IS DEPRECATED", fBinding.isDeprecated(), true)); //$NON-NLS-1$ @@ -303,7 +315,7 @@ public String getLabel() { } else { buf.append(variableBinding.getDeclaringClass().getName()); buf.append('.'); - buf.append(variableBinding.getName()); + buf.append(variableBinding.getName()); } break; case IBinding.PACKAGE: @@ -312,7 +324,7 @@ public String getLabel() { break; case IBinding.TYPE: ITypeBinding typeBinding= (ITypeBinding) fBinding; - buf.append(typeBinding.getQualifiedName()); + appendAnnotatedQualifiedName(buf, typeBinding); break; case IBinding.METHOD: IMethodBinding methodBinding= (IMethodBinding) fBinding; @@ -343,6 +355,16 @@ public String getLabel() { } + public static void appendAnnotatedQualifiedName(StringBuffer buf, ITypeBinding typeBinding) { + String debugString= typeBinding.toString(); // XXX: hack, but that's OK for a debugging tool... + if (debugString.indexOf('\n') == -1 || typeBinding.getTypeAnnotations().length != 0) { + // one-liner || outermost type has type annotations + buf.append(debugString); + } else { + buf.append(typeBinding.getQualifiedName()); + } + } + /* (non-Javadoc) * @see org.eclipse.jdt.astview.views.ASTAttribute#getImage() */ @@ -460,14 +482,53 @@ public static ASTAttribute createValueAttribute(ASTAttribute parent, String name } public static String getEscapedStringLiteral(String stringValue) { - StringLiteral stringLiteral= AST.newAST(AST.JLS4).newStringLiteral(); + StringLiteral stringLiteral= AST.newAST(ASTView.JLS_LATEST).newStringLiteral(); stringLiteral.setLiteralValue(stringValue); return stringLiteral.getEscapedValue(); } public static String getEscapedCharLiteral(char charValue) { - CharacterLiteral charLiteral= AST.newAST(AST.JLS4).newCharacterLiteral(); + CharacterLiteral charLiteral= AST.newAST(ASTView.JLS_LATEST).newCharacterLiteral(); charLiteral.setCharValue(charValue); return charLiteral.getEscapedValue(); } + + private static StringBuffer getModifiersString(int flags, boolean isMethod) { + StringBuffer sb = new StringBuffer().append("0x").append(Integer.toHexString(flags)).append(" ("); + int prologLen= sb.length(); + int rest= flags; + + rest&= ~ appendFlag(sb, flags, Modifier.PUBLIC, "public "); + rest&= ~ appendFlag(sb, flags, Modifier.PRIVATE, "private "); + rest&= ~ appendFlag(sb, flags, Modifier.PROTECTED, "protected "); + rest&= ~ appendFlag(sb, flags, Modifier.STATIC, "static "); + rest&= ~ appendFlag(sb, flags, Modifier.FINAL, "final "); + if (isMethod) { + rest&= ~ appendFlag(sb, flags, Modifier.SYNCHRONIZED, "synchronized "); + rest&= ~ appendFlag(sb, flags, Modifier.DEFAULT, "default "); + } else { + rest&= ~ appendFlag(sb, flags, Modifier.VOLATILE, "volatile "); + rest&= ~ appendFlag(sb, flags, Modifier.TRANSIENT, "transient "); + } + rest&= ~ appendFlag(sb, flags, Modifier.NATIVE, "native "); + rest&= ~ appendFlag(sb, flags, Modifier.ABSTRACT, "abstract "); + rest&= ~ appendFlag(sb, flags, Modifier.STRICTFP, "strictfp "); + + if (rest != 0) + sb.append("unknown:0x").append(Integer.toHexString(rest)).append(" "); + int len = sb.length(); + if (len != prologLen) + sb.setLength(len - 1); + sb.append(")"); + return sb; + } + + private static int appendFlag(StringBuffer sb, int flags, int flag, String name) { + if ((flags & flag) != 0) { + sb.append(name); + return flag; + } else { + return 0; + } + } } diff --git a/org.eclipse.jdt.jeview.feature/feature.xml b/org.eclipse.jdt.jeview.feature/feature.xml index 11943b20e6..d417b1c76b 100644 --- a/org.eclipse.jdt.jeview.feature/feature.xml +++ b/org.eclipse.jdt.jeview.feature/feature.xml @@ -2,11 +2,11 @@ - JavaElement View for JDT 3.7.0 and later + JavaElement View for JDT UI 4.4 and later @@ -18,8 +18,8 @@ - - + + diff --git a/org.eclipse.jdt.jeview.feature/pom.xml b/org.eclipse.jdt.jeview.feature/pom.xml index eb96b93514..8d86933e04 100644 --- a/org.eclipse.jdt.jeview.feature/pom.xml +++ b/org.eclipse.jdt.jeview.feature/pom.xml @@ -18,6 +18,6 @@ org.eclipse.jdt.feature org.eclipse.jdt.jeview.feature - 1.0.100-SNAPSHOT + 1.0.9-SNAPSHOT eclipse-feature diff --git a/org.eclipse.jdt.jeview/META-INF/MANIFEST.MF b/org.eclipse.jdt.jeview/META-INF/MANIFEST.MF index 6cb0faf052..6398c3ec81 100644 --- a/org.eclipse.jdt.jeview/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.jeview/META-INF/MANIFEST.MF @@ -2,15 +2,15 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.jeview; singleton:=true -Bundle-Version: 1.0.8.qualifier -Eclipse-SourceReferences: scm:git:git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git;path="org.eclipse.jdt.jeview";tag=R1_0_8 +Bundle-Version: 1.0.9.qualifier +Eclipse-SourceReferences: scm:git:git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git;path="org.eclipse.jdt.jeview";tag=R4_4 Bundle-Activator: org.eclipse.jdt.jeview.JEViewPlugin Bundle-Vendor: %providerName Bundle-Localization: plugin Bundle-RequiredExecutionEnvironment: J2SE-1.5 Require-Bundle: org.eclipse.core.runtime, - org.eclipse.jdt.core;bundle-version="[3.7.0,4.0.0)", - org.eclipse.jdt.ui;bundle-version="[3.7.0,4.0.0)", + org.eclipse.jdt.core;bundle-version="[3.10.0,4.0.0)", + org.eclipse.jdt.ui;bundle-version="[3.10.0,4.0.0)", org.eclipse.ui, org.eclipse.core.resources, org.eclipse.jface.text, diff --git a/org.eclipse.jdt.jeview/pom.xml b/org.eclipse.jdt.jeview/pom.xml index 533efbd621..1fe44edc87 100644 --- a/org.eclipse.jdt.jeview/pom.xml +++ b/org.eclipse.jdt.jeview/pom.xml @@ -18,6 +18,6 @@ org.eclipse.jdt org.eclipse.jdt.jeview - 1.0.8-SNAPSHOT + 1.0.9-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.jeview/src/org/eclipse/jdt/jeview/properties/JavaElementProperties.java b/org.eclipse.jdt.jeview/src/org/eclipse/jdt/jeview/properties/JavaElementProperties.java index 0acd38966a..47ec71d211 100644 --- a/org.eclipse.jdt.jeview/src/org/eclipse/jdt/jeview/properties/JavaElementProperties.java +++ b/org.eclipse.jdt.jeview/src/org/eclipse/jdt/jeview/properties/JavaElementProperties.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 IBM Corporation and others. + * Copyright (c) 2005, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -336,6 +336,11 @@ private static void addMethodProperties() { return ((IMethod) element).isMainMethod(); } }); + addProperty(new Property(IMethod.class, "isLambdaMethod") { + @Override public Object compute(IJavaElement element) throws JavaModelException { + return ((IMethod) element).isLambdaMethod(); + } + }); } private static void addTypeProperties() { @@ -626,10 +631,12 @@ static String getFlagsString(int flags, Class clazz) { rest&= ~ appendFlag(sb, flags, Flags.AccProtected, "protected "); rest&= ~ appendFlag(sb, flags, Flags.AccStatic, "static "); rest&= ~ appendFlag(sb, flags, Flags.AccFinal, "final "); - if (IMethod.class.isAssignableFrom(clazz)) { + boolean isMethod = IMethod.class.isAssignableFrom(clazz); + if (isMethod) { rest&= ~ appendFlag(sb, flags, Flags.AccSynchronized, "synchronized "); rest&= ~ appendFlag(sb, flags, Flags.AccBridge, "bridge "); rest&= ~ appendFlag(sb, flags, Flags.AccVarargs, "varargs "); + rest&= ~ appendFlag(sb, flags, Flags.AccDefaultMethod, "default(method) "); } else { rest&= ~ appendFlag(sb, flags, Flags.AccSuper, "super "); rest&= ~ appendFlag(sb, flags, Flags.AccVolatile, "volatile "); @@ -643,6 +650,9 @@ static String getFlagsString(int flags, Class clazz) { rest&= ~ appendFlag(sb, flags, Flags.AccAnnotation, "annotation "); rest&= ~ appendFlag(sb, flags, Flags.AccEnum, "enum "); rest&= ~ appendFlag(sb, flags, Flags.AccDeprecated, "deprecated "); + if (isMethod) { + rest&= ~ appendFlag(sb, flags, Flags.AccAnnotationDefault, "default(annotation) "); + } if (rest != 0) sb.append("unknown:0x").append(Integer.toHexString(rest)).append(" "); diff --git a/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestCaseElement.java b/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestCaseElement.java index 0ba4137304..73516c9776 100644 --- a/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestCaseElement.java +++ b/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestCaseElement.java @@ -8,6 +8,7 @@ * Contributors: * IBM Corporation - initial API and implementation * Andrej Zachar - [JUnit] Add a filter for ignored tests - https://bugs.eclipse.org/bugs/show_bug.cgi?id=298603 + * Xavier Coulon - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512 - [JUnit] test method name cut off before ( *******************************************************************************/ package org.eclipse.jdt.internal.junit.model; @@ -34,7 +35,7 @@ public TestCaseElement(TestSuiteElement parent, String id, String testName) { */ public String getTestMethodName() { String testName= getTestName(); - int index= testName.indexOf('('); + int index= testName.lastIndexOf('('); if (index > 0) return testName.substring(0, index); index= testName.indexOf('@'); diff --git a/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestElement.java b/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestElement.java index c4f2ace672..b4734f60d9 100644 --- a/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestElement.java +++ b/org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/model/TestElement.java @@ -10,6 +10,7 @@ * Brock Janiczak (brockj@tpg.com.au) * - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102236: [JUnit] display execution time next to each test * Andrej Zachar - [JUnit] Add a filter for ignored tests - https://bugs.eclipse.org/bugs/show_bug.cgi?id=298603 + * Xavier Coulon - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512 - [JUnit] test method name cut off before ( *******************************************************************************/ package org.eclipse.jdt.internal.junit.model; @@ -337,11 +338,15 @@ private static String extractClassName(String testNameString) { } public static String extractRawClassName(String testNameString) { - int index= testNameString.indexOf('('); + if (testNameString.startsWith("[") && testNameString.endsWith("]")) { //$NON-NLS-1$ //$NON-NLS-2$ + // a group of parameterized tests, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512 + return testNameString; + } + int index= testNameString.lastIndexOf('('); if (index < 0) return testNameString; - testNameString= testNameString.substring(index + 1); - testNameString= testNameString.substring(0, testNameString.indexOf(')')); + int end= testNameString.lastIndexOf(')'); + testNameString= testNameString.substring(index + 1, end > index ? end : testNameString.length()); return testNameString; } diff --git a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/buildpath/JUnitContainerWizardPage.java b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/buildpath/JUnitContainerWizardPage.java index 540488f2a3..0186ba5f3a 100644 --- a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/buildpath/JUnitContainerWizardPage.java +++ b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/buildpath/JUnitContainerWizardPage.java @@ -48,6 +48,7 @@ import org.eclipse.jdt.ui.wizards.NewElementWizardPage; import org.eclipse.jdt.internal.ui.JavaPluginImages; +import org.eclipse.jdt.internal.ui.util.SWTUtil; public class JUnitContainerWizardPage extends NewElementWizardPage implements IClasspathContainerPage, IClasspathContainerPageExtension { @@ -140,6 +141,7 @@ public void modifyText(ModifyEvent e) { label.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false, 1, 1)); fResolvedPath= new Text(composite, SWT.READ_ONLY | SWT.WRAP); + SWTUtil.fixReadonlyTextBackground(fResolvedPath); data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1); data.widthHint= converter.convertWidthInCharsToPixels(60); fResolvedPath.setFont(composite.getFont()); @@ -151,6 +153,7 @@ public void modifyText(ModifyEvent e) { label.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, false, false, 1, 1)); fResolvedSourcePath= new Text(composite, SWT.READ_ONLY | SWT.WRAP); + SWTUtil.fixReadonlyTextBackground(fResolvedSourcePath); data= new GridData(GridData.FILL, GridData.FILL, true, false, 1, 1); data.widthHint= converter.convertWidthInCharsToPixels(60); fResolvedSourcePath.setFont(composite.getFont()); diff --git a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java index 8817ea5926..cf401c161b 100644 --- a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java +++ b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/CounterPanel.java @@ -23,6 +23,8 @@ import org.eclipse.jdt.internal.junit.Messages; +import org.eclipse.jdt.internal.ui.util.SWTUtil; + /** * A panel with counters for the number of Runs, Errors and Failures. */ @@ -77,7 +79,7 @@ private Text createLabel(String name, Image image, String init) { Text value= new Text(this, SWT.READ_ONLY); value.setText(init); // bug: 39661 Junit test counters do not repaint correctly [JUnit] - value.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + SWTUtil.fixReadonlyTextBackground(value); value.setLayoutData(new GridData(GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING)); return value; } diff --git a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java index 3e78f29794..c777296a4d 100644 --- a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java +++ b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java @@ -10,6 +10,7 @@ * Brock Janiczak (brockj@tpg.com.au) * - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102236: [JUnit] display execution time next to each test * Andrej Zachar - [JUnit] Add a filter for ignored tests - https://bugs.eclipse.org/bugs/show_bug.cgi?id=298603 + * Xavier Coulon - https://bugs.eclipse.org/bugs/show_bug.cgi?id=102512 - [JUnit] test method name cut off before ( *******************************************************************************/ package org.eclipse.jdt.internal.junit.ui; @@ -300,9 +301,17 @@ void handleDefaultSelected() { OpenTestAction action; if (testElement instanceof TestSuiteElement) { - action= new OpenTestAction(fTestRunnerPart, testElement.getTestName()); - } else if (testElement instanceof TestCaseElement){ - TestCaseElement testCase= (TestCaseElement) testElement; + String testName= testElement.getTestName(); + ITestElement[] children= ((TestSuiteElement) testElement).getChildren(); + if (testName.startsWith("[") && testName.endsWith("]") //$NON-NLS-1$ //$NON-NLS-2$ + && children.length > 0 && children[0] instanceof TestCaseElement) { + // a group of parameterized tests + action= new OpenTestAction(fTestRunnerPart, (TestCaseElement) children[0]); + } else { + action= new OpenTestAction(fTestRunnerPart, testName); + } + } else if (testElement instanceof TestCaseElement) { + TestCaseElement testCase= (TestCaseElement)testElement; action= new OpenTestAction(fTestRunnerPart, testCase); } else { throw new IllegalStateException(String.valueOf(testElement)); diff --git a/org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/launcher/JUnitLaunchConfigurationTab.java b/org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/launcher/JUnitLaunchConfigurationTab.java index 3ab7ca64fd..c1c5c53424 100644 --- a/org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/launcher/JUnitLaunchConfigurationTab.java +++ b/org.eclipse.jdt.junit/src/org/eclipse/jdt/junit/launcher/JUnitLaunchConfigurationTab.java @@ -117,6 +117,7 @@ import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor; import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension; +import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; @@ -348,6 +349,7 @@ public void widgetDefaultSelected(SelectionEvent e) { }); fContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY); + SWTUtil.fixReadonlyTextBackground(fContainerText); gd = new GridData(GridData.FILL_HORIZONTAL); gd.horizontalIndent= 25; gd.horizontalSpan = 2; diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java new file mode 100644 index 0000000000..5d79cf2371 --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java @@ -0,0 +1,143 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 + *******************************************************************************/ +package org.eclipse.jdt.text.tests; + +import java.util.Hashtable; + +import junit.framework.TestCase; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jface.text.BadLocationException; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateException; +import org.eclipse.jface.text.templates.persistence.TemplateStore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.template.java.JavaContext; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +/** + * This class provides general functions to test the for loop template based completion. + */ +public abstract class AbstractForLoopJavaContextTest extends TestCase { + + private static final String PROJECT= "NewForLoopJavaContextTest"; + + private static final String SRC= "src"; + + private static final String CU_NAME= "A.java"; + + private static final String CU_PREFIX= "package test;\n" + + "\n" + + "import java.io.Serializable;\n" + + "import java.util.Collection;\n" + + "import java.util.List;\n" + + "\n" + + "public class A {\n"; + + private static final String CU_POSTFIX= " {\n" + + " \n" + + "}\n" + + "}\n"; + + private IJavaProject fProject; + + private ICompilationUnit fCU; + + public AbstractForLoopJavaContextTest() { + super(); + } + + public AbstractForLoopJavaContextTest(String name) { + super(name); + } + + protected void setUp() throws Exception { + if (JavaCore.getPlugin() != null) { + Hashtable options= JavaCore.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + // options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_LENGTH, "4"); + // options.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, "4"); + JavaCore.setOptions(options); + } + setUpProject(JavaCore.VERSION_1_5); + } + + private void setUpProject(String sourceLevel) throws CoreException, JavaModelException { + fProject= JavaProjectHelper.createJavaProject(PROJECT, "bin"); + JavaProjectHelper.addRTJar(fProject); + fProject.setOption(JavaCore.COMPILER_SOURCE, sourceLevel); + IPackageFragmentRoot fragmentRoot= JavaProjectHelper.addSourceContainer(fProject, SRC); + IPackageFragment fragment= fragmentRoot.createPackageFragment("test", true, new NullProgressMonitor()); + fCU= fragment.createCompilationUnit(CU_NAME, "", true, new NullProgressMonitor()); + fCU.becomeWorkingCopy(null); + } + + protected void tearDown() throws Exception { + fCU.discardWorkingCopy(); + JavaProjectHelper.delete(fProject); + if (JavaCore.getPlugin() != null) { + JavaCore.setOptions(JavaCore.getDefaultOptions()); + } + } + + protected Template getTemplate(String id) { + TemplateStore store= JavaPlugin.getDefault().getTemplateStore(); + return store.getTemplateData(id).getTemplate(); + } + + /** + * Load the template using {@link AbstractForLoopJavaContextTest#getTemplate(String)} with the + * template's id. + * + * @return the loaded {@link Template} instance. + */ + protected abstract Template getForLoop(); + + protected String evaluateTemplateInMethod(String signature) throws BadLocationException, TemplateException, CoreException { + String prefix= CU_PREFIX + getInnerClasses(); + fCU.getBuffer().setContents(prefix + signature + CU_POSTFIX); + int offset= prefix.length() + signature.length() + 3; + fCU.reconcile(ICompilationUnit.NO_AST, false, null, null); + return JavaContext.evaluateTemplate(getForLoop(), fCU, offset); + } + + /** + * Helper which should return all inner class declarations which are used in the tests as + * String. + * + * @return all inner class declarations + */ + protected abstract String getInnerClasses(); + + protected String evaluateTemplateInMethodWithField(String signature, String fieldDeclaration) throws BadLocationException, TemplateException, CoreException { + StringBuffer buf= new StringBuffer(); + buf.append(fieldDeclaration); + buf.append(";\n"); + buf.append(signature); + return evaluateTemplateInMethod(buf.toString()); + } + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/ArrayWithTempVarForLoopJavaContextTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/ArrayWithTempVarForLoopJavaContextTest.java new file mode 100644 index 0000000000..b68585274a --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/ArrayWithTempVarForLoopJavaContextTest.java @@ -0,0 +1,111 @@ +/******************************************************************************* + * Copyright (c) 2014 Yatta Solutions GmbH, IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Lukas Hanke - initial API and implementation - https://bugs.eclipse.org/117215 + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jface.text.templates.Template; + +/** + * Tests functionality of the template based for loop completion to iterate over an array, using a + * temporary variable inside the for loop's body. + */ +public class ArrayWithTempVarForLoopJavaContextTest extends AbstractForLoopJavaContextTest { + + public static Test suite() { + return new TestSuite(ArrayWithTempVarForLoopJavaContextTest.class); + } + + @Override + protected String getInnerClasses() { + return NewForLoopJavaContextTest.INNER_CLASS_DECLARATIONS; + } + + @Override + protected Template getForLoop() { + return getTemplate("org.eclipse.jdt.ui.templates.for_temp"); + } + + public void testSimpleArray() throws Exception { + String template= evaluateTemplateInMethod("void method(Number[] numbers)"); + assertEquals( + " for (int i = 0; i < numbers.length; i++) {\n" + + " Number number = numbers[i];\n" + + " \n" + + " }", template); + } + + public void testInnerClassArray() throws Exception { + String template= evaluateTemplateInMethod("void method(Inner[] inners)"); + assertEquals( + " for (int i = 0; i < inners.length; i++) {\n" + + " Inner inner = inners[i];\n" + + " \n" + + " }", template); + } + + public void testInnerClassParameterized() throws Exception { + String template= evaluateTemplateInMethod("void method(Inner2[] inners)"); + assertEquals( + " for (int i = 0; i < inners.length; i++) {\n" + + " Inner2 inner2 = inners[i];\n" + + " \n" + + " }", template); + } + + public void testGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(T[] generics)"); + assertEquals( + " for (int i = 0; i < generics.length; i++) {\n" + + " T t = generics[i];\n" + + " \n" + + " }", template); + } + + public void testUppderboundGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(T[] numbers)"); + assertEquals( + " for (int i = 0; i < numbers.length; i++) {\n" + + " T t = numbers[i];\n" + + " \n" + + " }", template); + } + + public void testLowerboundGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(T[] objects)"); + assertEquals( + " for (int i = 0; i < objects.length; i++) {\n" + + " T t = objects[i];\n" + + " \n" + + " }", template); + } + + public void testProposalsWithField() throws Exception { + String template= evaluateTemplateInMethodWithField("void method()", "Number[] numbers"); + assertEquals( + " for (int i = 0; i < numbers.length; i++) {\n" + + " Number number = numbers[i];\n" + + " \n" + + " }", template); + } + + public void testProposalsWithFieldAndParam() throws Exception { + String template= evaluateTemplateInMethodWithField("void method(String[] strings)", "Number[] numbers"); + assertEquals( + " for (int i = 0; i < strings.length; i++) {\n" + + " String string = strings[i];\n" + + " \n" + + " }", template); + } + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/IteratorForLoopJavaContextTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/IteratorForLoopJavaContextTest.java new file mode 100644 index 0000000000..a0611c6ea6 --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/IteratorForLoopJavaContextTest.java @@ -0,0 +1,172 @@ +/******************************************************************************* + * Copyright (c) 2014 Yatta Solutions GmbH, IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Lukas Hanke - initial API and implementation - https://bugs.eclipse.org/117215 + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests; + +import java.util.Collection; +import java.util.Iterator; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jface.text.templates.Template; + +/** + * Tests functionality of the template based for loop completion to iterate over a + * {@link Collection}, using an {@link Iterator} variable to fetch collection elements. + */ +public class IteratorForLoopJavaContextTest extends AbstractForLoopJavaContextTest { + + public static final String INNER_CLASS_DECLARATIONS= " private static abstract class InnerCollection implements Collection {\n" + + " }\n" + + " \n" + + " private static abstract class InnerCollection2 implements Collection {\n" + + " }\n" + + " \n" + + " private static abstract class InnerCollection3 implements Collection {\n" + + " }\n" + + " \n" + + " private static abstract class TransiCollection implements Collection {\n" + + " }\n" + + " \n"; + + public static Test suite() { + return new TestSuite(IteratorForLoopJavaContextTest.class); + } + + @Override + protected String getInnerClasses() { + return INNER_CLASS_DECLARATIONS; + } + + @Override + protected Template getForLoop() { + return getTemplate("org.eclipse.jdt.ui.templates.for_collection"); + } + + public void testCollection() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " Number number = (Number) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testInnerParameterized() throws Exception { + String template= evaluateTemplateInMethod("void method(InnerCollection numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " Number number = (Number) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testInnerFixTypedInterface() throws Exception { + String template= evaluateTemplateInMethod("void method(InnerCollection2 numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " Serializable serializable = (Serializable) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testInnerWithMixedTypes() throws Exception { + String template= evaluateTemplateInMethod("void method(InnerCollection3 numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " String string = (String) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testSimpleTransitive() throws Exception { + String template= evaluateTemplateInMethod("void method(TransiCollection> lists)"); + assertEquals( + " for (java.util.Iterator iterator = lists.iterator(); iterator.hasNext();) {\n" + + " List list = (List) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testWildcard() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection objects)"); + assertEquals( + " for (java.util.Iterator iterator = objects.iterator(); iterator.hasNext();) {\n" + + " Object object = (Object) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testUpperboundWildcard() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " Number number = (Number) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testLowerboundWildcard() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection objects)"); + assertEquals( + " for (java.util.Iterator iterator = objects.iterator(); iterator.hasNext();) {\n" + + " Object object = (Object) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection objects)"); + assertEquals( + " for (java.util.Iterator iterator = objects.iterator(); iterator.hasNext();) {\n" + + " T t = (T) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testUppderboundGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection numbers)"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " T t = (T) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testLowerboundGeneric() throws Exception { + String template= evaluateTemplateInMethod("void method(Collection objects)"); + assertEquals( + " for (java.util.Iterator iterator = objects.iterator(); iterator.hasNext();) {\n" + + " T t = (T) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testProposalsWithField() throws Exception { + String template= evaluateTemplateInMethodWithField("void method()", "Collection numbers"); + assertEquals( + " for (java.util.Iterator iterator = numbers.iterator(); iterator.hasNext();) {\n" + + " Number number = (Number) iterator.next();\n" + + " \n" + + " }", template); + } + + public void testProposalsWithFieldAndParam() throws Exception { + String template= evaluateTemplateInMethodWithField("void method(Collection strings)", "Collection numbers"); + assertEquals( + " for (java.util.Iterator iterator = strings.iterator(); iterator.hasNext();) {\n" + + " String string = (String) iterator.next();\n" + + " \n" + + " }", template); + } + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaHeuristicScannerTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaHeuristicScannerTest.java index f2325c9cf0..eee6e4d06a 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaHeuristicScannerTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaHeuristicScannerTest.java @@ -16,8 +16,6 @@ import junit.framework.TestCase; import junit.framework.TestSuite; -import org.junit.Assert; - import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.rules.FastPartitioner; @@ -100,7 +98,7 @@ public void testPrevIndentationUnit1() { ""); int pos= fScanner.findReferencePosition(18); - Assert.assertEquals(9, pos); + assertEquals(9, pos); } public void testPrevIndentationUnit2() { @@ -109,7 +107,7 @@ public void testPrevIndentationUnit2() { "\t\treturn a"); int pos= fScanner.findReferencePosition(28); - Assert.assertEquals(21, pos); + assertEquals(21, pos); } @@ -120,7 +118,7 @@ public void testPrevIndentationUnit5() { ""); int pos= fScanner.findReferencePosition(30); - Assert.assertEquals(9, pos); + assertEquals(9, pos); } public void testPrevIndentationUnit6() { @@ -128,7 +126,7 @@ public void testPrevIndentationUnit6() { fDocument.set("\tvoid proc (int par1, int par2\n"); int pos= fScanner.findReferencePosition(30); - Assert.assertEquals(12, pos); + assertEquals(12, pos); } public void testPrevIndentationUnit7() { @@ -139,7 +137,7 @@ public void testPrevIndentationUnit7() { ""); int pos= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(39, pos); + assertEquals(39, pos); } public void testPrevIndentationUnit8() { @@ -148,7 +146,7 @@ public void testPrevIndentationUnit8() { int pos= fScanner.findReferencePosition(fDocument.getLength()); // Assert.assertEquals(1, pos); - Assert.assertEquals(15, pos); + assertEquals(15, pos); } public void testPrevIndentationUnit9() { @@ -161,7 +159,7 @@ public void testPrevIndentationUnit9() { "\t\tint i;\n"); int pos= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(fDocument.getLength() - 7, pos); + assertEquals(fDocument.getLength() - 7, pos); } public void testPrevIndentationUnit10() { @@ -176,7 +174,7 @@ public void testPrevIndentationUnit10() { ""); int pos= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(39, pos); + assertEquals(39, pos); } public void testPrevIndentationUnit11() { @@ -191,7 +189,7 @@ public void testPrevIndentationUnit11() { ""); int pos= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(83, pos); + assertEquals(83, pos); } public void testPrevIndentation1() { @@ -200,7 +198,7 @@ public void testPrevIndentation1() { ""); String indent= fScanner.getReferenceIndentation(18).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testPrevIndentation2() { @@ -209,7 +207,7 @@ public void testPrevIndentation2() { "\t\treturn a"); String indent= fScanner.getReferenceIndentation(28).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation3() { @@ -218,7 +216,7 @@ public void testPrevIndentation3() { "\t\treturn a;"); String indent= fScanner.getReferenceIndentation(29).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation4() { @@ -228,7 +226,7 @@ public void testPrevIndentation4() { ""); String indent= fScanner.getReferenceIndentation(29).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation5() { @@ -238,14 +236,14 @@ public void testPrevIndentation5() { ""); String indent= fScanner.getReferenceIndentation(30).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testPrevIndentation6() { fDocument.set("\tvoid proc (int par1, int par2\n"); String indent= fScanner.getReferenceIndentation(30).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testPrevIndentation7() { @@ -256,14 +254,14 @@ public void testPrevIndentation7() { ""); String indent= fScanner.getReferenceIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation8() { fDocument.set("\t/* package */ void proc (int par1, int par2) {\n"); String indent= fScanner.getReferenceIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testPrevIndentation9() { @@ -276,7 +274,7 @@ public void testPrevIndentation9() { "\t\tint i;\n"); String indent= fScanner.getReferenceIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation10() { @@ -291,7 +289,7 @@ public void testPrevIndentation10() { ""); String indent= fScanner.getReferenceIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testPrevIndentation11() { @@ -306,7 +304,7 @@ public void testPrevIndentation11() { ""); String indent= fScanner.getReferenceIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation1() { @@ -315,7 +313,7 @@ public void testIndentation1() { ""); String indent= fScanner.computeIndentation(18).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation5() { @@ -325,7 +323,7 @@ public void testIndentation5() { ""); String indent= fScanner.computeIndentation(30).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation6() { @@ -333,7 +331,7 @@ public void testIndentation6() { fDocument.set("\tvoid proc (int par1, int par2\n"); String indent= fScanner.computeIndentation(30).toString(); - Assert.assertEquals("\t ", indent); + assertEquals("\t ", indent); } public void testIndentation6a() { @@ -341,7 +339,7 @@ public void testIndentation6a() { fDocument.set("\tvoid proc ( int par1, int par2\n"); String indent= fScanner.computeIndentation(30).toString(); - Assert.assertEquals("\t ", indent); + assertEquals("\t ", indent); } public void testIndentation7() { @@ -352,7 +350,7 @@ public void testIndentation7() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation8() { @@ -360,7 +358,7 @@ public void testIndentation8() { fDocument.set("\t/* package */ void proc (int par1, int par2) {\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation9() { @@ -373,7 +371,7 @@ public void testIndentation9() { "\t\tint i;\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation10() { @@ -388,7 +386,7 @@ public void testIndentation10() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation11() { @@ -403,7 +401,7 @@ public void testIndentation11() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation12() { @@ -414,7 +412,7 @@ public void testIndentation12() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation13() { @@ -425,7 +423,7 @@ public void testIndentation13() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation14() { @@ -436,7 +434,7 @@ public void testIndentation14() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testIndentation15() { @@ -446,7 +444,7 @@ public void testIndentation15() { "\t}\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation16() { @@ -455,7 +453,7 @@ public void testIndentation16() { "\t\t;"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation17() { @@ -464,7 +462,7 @@ public void testIndentation17() { ";"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation18() { @@ -473,7 +471,7 @@ public void testIndentation18() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation19() { @@ -482,7 +480,7 @@ public void testIndentation19() { "\t\t}"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation20() { @@ -491,7 +489,7 @@ public void testIndentation20() { "\t\t}"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation21() { @@ -501,7 +499,7 @@ public void testIndentation21() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentation22() { @@ -513,7 +511,7 @@ public void testIndentation22() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); // because of possible dangling else + assertEquals("\t", indent); // because of possible dangling else } public void testIndentation22a() { @@ -525,7 +523,7 @@ public void testIndentation22a() { ""); String indent= fScanner.computeIndentation(fDocument.getLength() - 2).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation22b() { @@ -537,7 +535,7 @@ public void testIndentation22b() { "a"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals("\t", indent); // no dangling else possible + assertEquals("\t", indent); // no dangling else possible } public void testIndentation23() { @@ -546,7 +544,7 @@ public void testIndentation23() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation24() { @@ -557,7 +555,7 @@ public void testIndentation24() { "\t\tnoStuff"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation25() { @@ -568,7 +566,7 @@ public void testIndentation25() { "\t\tnoStuff;\r\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation26() { @@ -579,7 +577,7 @@ public void testIndentation26() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation27() { @@ -590,9 +588,9 @@ public void testIndentation27() { ""); int i= fScanner.findReferencePosition(8); - Assert.assertEquals(1, i); + assertEquals(1, i); String indent= fScanner.computeIndentation(8).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation28() { @@ -603,9 +601,9 @@ public void testIndentation28() { ""); int i= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(1, i); + assertEquals(1, i); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation29() { @@ -614,9 +612,9 @@ public void testIndentation29() { "\t\t\t\tfoo();\n"); int i= fScanner.findReferencePosition(fDocument.getLength()); - Assert.assertEquals(2, i); + assertEquals(2, i); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation30() { @@ -625,7 +623,7 @@ public void testIndentation30() { "\t{"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentation31() { @@ -637,7 +635,7 @@ public void testIndentation31() { "\t\tnoStuff"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testIndentation32() { @@ -646,7 +644,7 @@ public void testIndentation32() { "\t\tcase one:\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testAnonymousIndentation1() { @@ -656,7 +654,7 @@ public void testAnonymousIndentation1() { ); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testAnonymousIndentation2() { @@ -672,7 +670,7 @@ public void testAnonymousIndentation2() { // this is bogus, since this is really just an unfinished call argument list - how could we know String indent= fScanner.computeIndentation(fDocument.getLength() - 2).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testExceptionIndentation1() { @@ -685,7 +683,7 @@ public void testExceptionIndentation1() { " new Bla(new CoreExeption(new Status(IStatus.ERROR, JavaPlugin.getPluginId()"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testExceptionIndentation2() { @@ -698,7 +696,7 @@ public void testExceptionIndentation2() { " new Bla(new CoreExeption(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testExceptionIndentation3() { @@ -711,7 +709,7 @@ public void testExceptionIndentation3() { " new char[] { new CoreExeption(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testListAlignmentMethodDeclaration() { @@ -720,7 +718,7 @@ public void testListAlignmentMethodDeclaration() { " int par3, int par4,\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testListAlignmentMethodCall() { @@ -729,7 +727,7 @@ public void testListAlignmentMethodCall() { " par3, par4,\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testListAlignmentArray() { @@ -738,7 +736,7 @@ public void testListAlignmentArray() { " three, four,\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testListAlignmentArray2() { @@ -746,7 +744,7 @@ public void testListAlignmentArray2() { fDocument.set( "\tint[]= new int[] { 1, two,\n"); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals("\t ", indent); + assertEquals("\t ", indent); } @@ -759,7 +757,7 @@ public void testBraceAlignmentOfMultilineDeclaration() { " }"); String indent= fScanner.computeIndentation(fDocument.getLength() - 1).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testBlocksInCaseStatements() { @@ -770,7 +768,7 @@ public void testBlocksInCaseStatements() { ""); String indent= fScanner.computeIndentation(fDocument.getLength()).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testAnonymousTypeBraceNextLine() throws Exception { @@ -781,7 +779,7 @@ public void testAnonymousTypeBraceNextLine() throws Exception { ); String indent= fScanner.computeIndentation(fDocument.getLength() - 2).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } @@ -821,7 +819,7 @@ public void testConditional1() throws Exception { ); String indent= fScanner.computeIndentation(fDocument.getLength() - 8).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } public void testConditional2() throws Exception { @@ -835,7 +833,7 @@ public void testConditional2() throws Exception { ); String indent= fScanner.computeIndentation(fDocument.getLength() - 8).toString(); - Assert.assertEquals(" ", indent); + assertEquals(" ", indent); } @@ -845,19 +843,19 @@ public void testContinuationIndentationOfForStatement() throws Exception { "\t}"); String indent= fScanner.computeIndentation(22).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(27).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(39).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(40).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(5).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); indent= fScanner.computeIndentation(45).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); indent= fScanner.computeIndentation(60).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testContinuationIndentationOfForEachStatement() throws Exception { @@ -868,7 +866,7 @@ public void testContinuationIndentationOfForEachStatement() throws Exception { "\t}"); String indent= fScanner.computeIndentation(44).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfForEachStatement2() throws Exception { @@ -879,7 +877,7 @@ public void testContinuationIndentationOfForEachStatement2() throws Exception { "\t}"); String indent= fScanner.computeIndentation(44).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testContinuationIndentationOfBooleanExpression() throws Exception { @@ -887,55 +885,55 @@ public void testContinuationIndentationOfBooleanExpression() throws Exception { "\tboolean b = a || false;\n"); String indent= fScanner.computeIndentation(20).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(40).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfReturnStatement() throws Exception { fDocument.set("\t\treturn \"I'm such a long string that you have to split me to see the whole line without scrolling around\"\n"); String indent= fScanner.computeIndentation(8).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); indent= fScanner.computeIndentation(21).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); indent= fScanner.computeIndentation(38).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentationOfAssignmentStatement() throws Exception { fDocument.set("\tint i= 5+"); String indent= fScanner.computeIndentation(7).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(10).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfThrowsClause() throws Exception { fDocument.set("\tprivate void thrower() throws java.sql.SQLException, java.io.IOException {"); String indent= fScanner.computeIndentation(23).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(24).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfParentheses() throws Exception { fDocument.set("\tint foo() {\n\treturn \"\".length(\n\t\t);\n\t}"); String indent= fScanner.computeIndentation(34).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfAnnotation() throws Exception { fDocument.set("\t@MyAnnotation(\n\t\tvalue=\"hello\")\n\t\tpublic class ArrayAnnotationBug {\n\t\t}"); String indent= fScanner.computeIndentation(33).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); fDocument.set("\t@org.eclipse.jdt.MyAnnotation(\n\t\tvalue=\"hello\")\n\t\tpublic class ArrayAnnotationBug {\n\t\t}"); indent= fScanner.computeIndentation(49).toString(); - Assert.assertEquals("\t", indent); + assertEquals("\t", indent); } public void testIndentationAfterIfTryCatch() throws Exception { @@ -949,7 +947,7 @@ public void testIndentationAfterIfTryCatch() throws Exception { "\t\t}\n" + "\t}"); String indent= fScanner.computeIndentation(117).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); fDocument.set("\tpublic class Bug237081 {\n" + "\t\tpublic void foo() {\n" + @@ -963,28 +961,28 @@ public void testIndentationAfterIfTryCatch() throws Exception { "\t\t}\n" + "\t}"); indent= fScanner.computeIndentation(167).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentationOfBrackets() throws Exception { fDocument.set("\tprivate void helper2(boolean[] booleans) {\n\t}"); String indent= fScanner.computeIndentation(31).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(30).toString(); - Assert.assertEquals("\t ", indent); + assertEquals("\t ", indent); fDocument.set("\tif (booleans[0]) {\n\t\tString[] aString= new String[]{\"a\", \"b\"};\n\t\tbooleans[5]= true;\n\t}"); indent= fScanner.computeIndentation(16).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(14).toString(); - Assert.assertEquals("\t ", indent); + assertEquals("\t ", indent); indent= fScanner.computeIndentation(30).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); indent= fScanner.computeIndentation(52).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); indent= fScanner.computeIndentation(77).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentationOfStrings1() throws Exception { @@ -996,9 +994,9 @@ public void testContinuationIndentationOfStrings1() throws Exception { " + \" public \"};");//82- String indent= fScanner.computeIndentation(73).toString(); // at the beginning of 4th line - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); indent= fScanner.computeIndentation(84).toString(); // at the beginning of 5th line - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); fDocument.set( " String[] i = new String[] {\n" +//0-28 @@ -1008,7 +1006,7 @@ public void testContinuationIndentationOfStrings1() throws Exception { " \" public\"\n};"); indent= fScanner.computeIndentation(75).toString(); //at the beginning of 4th line - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentationOfStrings2() throws Exception { @@ -1019,7 +1017,7 @@ public void testContinuationIndentationOfStrings2() throws Exception { " + \"string:\\n\" + definedType.toString());\n"); //44- String indent= fScanner.computeIndentation(59).toString(); //before the last + - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentationOfStrings3() throws Exception { @@ -1029,7 +1027,7 @@ public void testContinuationIndentationOfStrings3() throws Exception { " + \"this is the 1st string\";\n");//42- String indent= fScanner.computeIndentation(44).toString();//at the beginning of 3rd line - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentation1() throws Exception { @@ -1037,9 +1035,9 @@ public void testContinuationIndentation1() throws Exception { "\t\t|| thisIsAVeryLongName == 2;"); String indent= fScanner.computeIndentation(68).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); indent= fScanner.computeIndentation(88).toString(); - Assert.assertEquals("\t\t", indent); + assertEquals("\t\t", indent); } public void testContinuationIndentation2() { @@ -1049,7 +1047,7 @@ public void testContinuationIndentation2() { ""); int pos= fScanner.findReferencePosition(29); - Assert.assertEquals(21, pos); + assertEquals(21, pos); } public void testContinuationIndentation3() { @@ -1058,7 +1056,7 @@ public void testContinuationIndentation3() { "\t\treturn a"); String indent= fScanner.computeIndentation(28).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentation4() { @@ -1067,7 +1065,7 @@ public void testContinuationIndentation4() { "\t\treturn a;"); String indent= fScanner.computeIndentation(29).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testContinuationIndentation5() { @@ -1077,7 +1075,7 @@ public void testContinuationIndentation5() { ""); String indent= fScanner.computeIndentation(29).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); } public void testIndentationTryWithResources() throws Exception { @@ -1099,10 +1097,47 @@ public void testIndentationTryWithResources() throws Exception { int offset= s.indexOf("FileReader reader2"); String indent= fScanner.computeIndentation(offset).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); offset= s.indexOf("FileReader reader5"); indent= fScanner.computeIndentation(offset).toString(); - Assert.assertEquals("\t\t\t", indent); + assertEquals("\t\t\t", indent); + } + + public void testDefaultMethod1() { + StringBuffer buf= new StringBuffer(); + buf.append("interface I {\n"); + buf.append(" default void foo (int a) {\n"); + buf.append(" switch(a) {\n"); + buf.append(" case 0: \n"); + buf.append(" break;\n"); + buf.append(" default : \n"); + buf.append(" System.out.println(\"default\");\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + fDocument.set(buf.toString()); + + int offset= buf.indexOf("default void"); + String indent= fScanner.computeIndentation(offset).toString(); + assertEquals("\t", indent); + + offset= buf.indexOf("default :"); + indent= fScanner.computeIndentation(offset).toString(); + assertEquals("\t\t", indent); + } + + public void testDefaultMethod2() { + StringBuffer buf= new StringBuffer(); + buf.append("interface I {\n"); + buf.append(" default String name() {\n"); + buf.append(" return \"unnamed\";\n"); + buf.append(" }\n"); + buf.append("}\n"); + fDocument.set(buf.toString()); + + int offset= buf.indexOf("default String"); + String indent= fScanner.computeIndentation(offset).toString(); + assertEquals("\t", indent); } } diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java index adb1311aa4..568f03a5c3 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 *******************************************************************************/ package org.eclipse.jdt.text.tests; @@ -58,6 +59,8 @@ public static Test suite() { suite.addTest(SemanticHighlightingTest.suite()); suite.addTest(AutoboxingSemanticHighlightingTest.suite()); suite.addTest(NewForLoopJavaContextTest.suite()); + suite.addTest(IteratorForLoopJavaContextTest.suite()); + suite.addTest(ArrayWithTempVarForLoopJavaContextTest.suite()); suite.addTest(JavaDoubleClickSelectorTest.suite()); suite.addTest(BreakContinueTargetFinderTest.suite()); suite.addTest(ContentAssistTestSuite.suite()); diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/MarkOccurrenceTest18.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/MarkOccurrenceTest18.java new file mode 100644 index 0000000000..ac7ba61e9c --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/MarkOccurrenceTest18.java @@ -0,0 +1,209 @@ +/******************************************************************************* + * Copyright (c) 2011, 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests; + +import java.util.Arrays; +import java.util.Comparator; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder; +import org.eclipse.jdt.internal.ui.search.IOccurrencesFinder; +import org.eclipse.jdt.internal.ui.search.IOccurrencesFinder.OccurrenceLocation; + +public class MarkOccurrenceTest18 extends TestCase { + private static final Class THIS= MarkOccurrenceTest18.class; + + public static Test suite() { + return new Java18ProjectTestSetup(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + private ASTParser fParser; + + private IOccurrencesFinder fFinder; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + /* + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + fParser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + + fJProject1= Java18ProjectTestSetup.getProject(); + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + JavaPlugin.getDefault().getPreferenceStore().setValue(PreferenceConstants.EDITOR_MARK_OCCURRENCES, true); + } + + /* (non-Javadoc) + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + private OccurrenceLocation[] getHighlights(StringBuffer source, int offset, int length) throws Exception { + CompilationUnit root= createCompilationUnit(source); + String errorString= fFinder.initialize(root, offset, length); + assertNull(errorString, errorString); + return fFinder.getOccurrences(); + } + + private CompilationUnit createCompilationUnit(StringBuffer source) throws JavaModelException { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", source.toString(), true, null); + fParser.setSource(cu); + fParser.setResolveBindings(true); + return (CompilationUnit)fParser.createAST(null); + } + + private void checkSelection(StringBuffer s, int offset, int length, OccurrenceLocation[] expected) throws Exception { + OccurrenceLocation[] selectedNodes= getHighlights(s, offset, length); + assertEquals("number of selections", expected.length, selectedNodes.length); + sortByStartIndex(selectedNodes); + sortByStartIndex(expected); + for (int i= 0; i < selectedNodes.length; i++) { + assertEquals(expected[i].getOffset(), selectedNodes[i].getOffset()); + assertEquals(expected[i].getLength(), selectedNodes[i].getLength()); + } + } + + private void sortByStartIndex(OccurrenceLocation[] OccurrenceLocations) { + Arrays.sort(OccurrenceLocations, new Comparator() { + public int compare(Object arg0, Object arg1) { + OccurrenceLocation node0= (OccurrenceLocation)arg0; + OccurrenceLocation node1= (OccurrenceLocation)arg1; + return node0.getOffset() - node1.getOffset(); + } + }); + } + + //pattern must be found - otherwise it's assumed to be an error + private OccurrenceLocation find(StringBuffer s, String pattern, int ithOccurrence) { + if (ithOccurrence < 1) + throw new IllegalStateException("ithOccurrence = " + ithOccurrence); + return find(s, pattern, ithOccurrence, 0); + } + + private OccurrenceLocation find(StringBuffer s, String pattern, int ithOccurrence, int startIdx) { + if (startIdx < 0 || startIdx > s.length()) + throw new IllegalStateException("startIdx = " + startIdx); + int idx= s.indexOf(pattern, startIdx); + if (idx == -1) + throw new IllegalStateException("not found \"" + pattern + "\" in \"" + s.substring(startIdx)); + if (ithOccurrence == 1) + return new OccurrenceLocation(idx, pattern.length(), 0, ""); + return find(s, pattern, ithOccurrence - 1, idx + 1); + } + + public void testThrowingAnnotatedException1() throws Exception { + StringBuffer s= new StringBuffer(); + s.append("package test1;\n"); + s.append("import java.lang.annotation.Documented;\n"); + s.append("import java.lang.annotation.ElementType;\n"); + s.append("import java.lang.annotation.Retention;\n"); + s.append("import java.lang.annotation.RetentionPolicy;\n"); + s.append("import java.lang.annotation.Target;\n"); + s.append("\n"); + s.append("public class E {\n"); + s.append(" @Target(ElementType.TYPE_USE)\n"); + s.append(" @Retention(RetentionPolicy.RUNTIME)\n"); + s.append(" @Documented\n"); + s.append(" static @interface Critical {\n"); + s.append(" String msg() default \"We're all going to die!\";\n"); + s.append(" }\n"); + s.append("\n"); + s.append(" class InnerException extends Exception {\n"); + s.append(" private static final long serialVersionUID = 1L;\n"); + s.append(" }\n"); + s.append("\n"); + s.append(" /**\n"); + s.append(" * @throws E.InnerException\n"); + s.append(" */\n"); + s.append(" void foo() throws @Critical() E.@Critical() InnerException, IllegalArgumentException {\n"); + s.append(" if (Boolean.TRUE)\n"); + s.append(" throw new @Critical() InnerException();\n"); + s.append(" else\n"); + s.append(" throw new @Critical() E.@Critical() InnerException();\n"); + s.append(" }\n"); + s.append("\n"); + s.append(" void tryCatch() {\n"); + s.append(" try {\n"); + s.append(" foo();\n"); + s.append(" } catch (@Critical() E.@Critical() InnerException e) {\n"); + s.append(" } catch (RuntimeException e) {\n"); + s.append(" }\n"); + s.append(" try {\n"); + s.append(" foo();\n"); + s.append(" } catch (RuntimeException | @Critical(msg=\"He\"+\"llo\") E.@Critical() InnerException e) {\n"); + s.append(" }\n"); + s.append(" }\n"); + s.append("}\n"); + + fFinder= new ExceptionOccurrencesFinder(); + int offset= 8 + s.indexOf("@throws E.InnerException"); // in Javadoc + int length= 0; + OccurrenceLocation[] ranges= { find(s, "E.InnerException", 1), find(s, "@Critical() E.@Critical() InnerException", 1), + find(s, "throw", 3), find(s, "throw", 4) }; + checkSelection(s, offset, length, ranges); + + fFinder= new ExceptionOccurrencesFinder(); + offset= 1 + s.indexOf("@Critical() E.@Critical() InnerException"); // in annotation + length= 0; + checkSelection(s, offset, length, ranges); + + fFinder= new ExceptionOccurrencesFinder(); + offset= s.indexOf("E.@Critical() InnerException"); // in annotated type qualifier + length= 1; + checkSelection(s, offset, length, ranges); + + fFinder= new ExceptionOccurrencesFinder(); + offset= 1 + s.indexOf("InnerException e)"); // in annotated catch type (does NOT include modifier "@Critical() "!) + length= 0; + ranges= new OccurrenceLocation[] { find(s, "foo", 2), find(s, "E.@Critical() InnerException", 3)}; + checkSelection(s, offset, length, ranges); + + fFinder= new ExceptionOccurrencesFinder(); + offset= s.indexOf("RuntimeException |"); // in annotated union type + length= 0; + ranges= new OccurrenceLocation[] { find(s, "foo", 3), find(s, "RuntimeException", 2)}; + checkSelection(s, offset, length, ranges); + + fFinder= new ExceptionOccurrencesFinder(); + offset= s.indexOf("He"); // in annotation expression + length= 0; + ranges= new OccurrenceLocation[] { find(s, "foo", 3), find(s, "@Critical(msg=\"He\"+\"llo\") E.@Critical() InnerException", 1)}; + checkSelection(s, offset, length, ranges); + } +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/NewForLoopJavaContextTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/NewForLoopJavaContextTest.java index c8327c56e6..0c1027e5c8 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/NewForLoopJavaContextTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/NewForLoopJavaContextTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,37 +7,14 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 *******************************************************************************/ package org.eclipse.jdt.text.tests; -import java.util.Hashtable; - import junit.framework.Test; -import junit.framework.TestCase; import junit.framework.TestSuite; -import org.eclipse.jdt.testplugin.JavaProjectHelper; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.NullProgressMonitor; - -import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.templates.Template; -import org.eclipse.jface.text.templates.TemplateException; -import org.eclipse.jface.text.templates.persistence.TemplateStore; - -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; - -import org.eclipse.jdt.internal.corext.template.java.JavaContext; - -import org.eclipse.jdt.internal.ui.JavaPlugin; - /** * Tests the automatic bracket insertion feature of the CUEditor. Also tests @@ -45,97 +22,41 @@ * * @since 3.1 */ -public class NewForLoopJavaContextTest extends TestCase { - - private static final String PROJECT= "NewForLoopJavaContextTest"; - private static final String SRC= "src"; - private static final String CU_NAME= "A.java"; - - private static final String CU_PREFIX= - "package test;\n" + - "\n" + - "import java.io.Serializable;\n" + - "import java.util.Collection;\n" + - "import java.util.List;\n" + - "\n" + - "public class A {\n" + - " private static class Inner {\n" + - " }\n" + - " \n" + - " private static abstract class Inner2 implements Iterable {\n" + - " }\n" + - " \n" + - " private static abstract class Inner3 implements Iterable {\n" + - " }\n" + - " \n" + - " private static abstract class Inner4 implements Iterable {\n" + - " }\n" + - " \n" + - " private static abstract class Transi1 implements Iterable {\n" + - " }\n" + - " \n" + - " private static abstract class Transi2 extends Transi1 {\n" + - " }\n" + - " \n"; - private static final String CU_POSTFIX= - " {\n" + - " \n" + - "}\n" + - "}\n"; +public class NewForLoopJavaContextTest extends AbstractForLoopJavaContextTest { + + public static final String INNER_CLASS_DECLARATIONS= " private static class Inner {\n" + + " }\n" + + " \n" + + " private static abstract class Inner2 implements Iterable {\n" + + " }\n" + + " \n" + + " private static abstract class Inner3 implements Iterable {\n" + + " }\n" + + " \n" + + " private static abstract class Inner4 implements Iterable {\n" + + " }\n" + + " \n" + + " private static abstract class Transi1 implements Iterable {\n" + + " }\n" + + " \n" + + " private static abstract class Transi2 extends Transi1 {\n" + + " }\n" + + " \n"; public static Test suite() { return new TestSuite(NewForLoopJavaContextTest.class); } - private IJavaProject fProject; - private ICompilationUnit fCU; - - protected void setUp() throws Exception { - if (JavaCore.getPlugin() != null) { - Hashtable options= JavaCore.getDefaultOptions(); - options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); - options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); -// options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_LENGTH, "4"); -// options.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, "4"); - JavaCore.setOptions(options); - } - setUpProject(JavaCore.VERSION_1_5); - } - - private void setUpProject(String sourceLevel) throws CoreException, JavaModelException { - fProject= JavaProjectHelper.createJavaProject(PROJECT, "bin"); - JavaProjectHelper.addRTJar(fProject); - fProject.setOption(JavaCore.COMPILER_SOURCE, sourceLevel); - IPackageFragmentRoot fragmentRoot= JavaProjectHelper.addSourceContainer(fProject, SRC); - IPackageFragment fragment= fragmentRoot.createPackageFragment("test", true, new NullProgressMonitor()); - fCU= fragment.createCompilationUnit(CU_NAME, "", true, new NullProgressMonitor()); - fCU.becomeWorkingCopy(null); - } - - protected void tearDown() throws Exception { - fCU.discardWorkingCopy(); - JavaProjectHelper.delete(fProject); - if (JavaCore.getPlugin() != null) { - JavaCore.setOptions(JavaCore.getDefaultOptions()); - } - } - - private Template getTemplate(String id) { - TemplateStore store= JavaPlugin.getDefault().getTemplateStore(); - return store.getTemplateData(id).getTemplate(); + @Override + protected String getInnerClasses() { + return INNER_CLASS_DECLARATIONS; } - private Template getForLoop() { + @Override + protected Template getForLoop() { return getTemplate("org.eclipse.jdt.ui.templates.for_iterable"); } - private String evaluateTemplateInMethod(String signature) throws BadLocationException, TemplateException, CoreException { - fCU.getBuffer().setContents(CU_PREFIX + signature + CU_POSTFIX); - int offset= CU_PREFIX.length() + signature.length() + 3; - fCU.reconcile(ICompilationUnit.NO_AST, false, null, null); - return JavaContext.evaluateTemplate(getForLoop(), fCU, offset); - } - public void testArray() throws Exception { String template= evaluateTemplateInMethod("void method(Number[] array)"); assertEquals( @@ -233,4 +154,20 @@ public void testUpperboundList() throws Exception { " }", template); } + public void testProposeField() throws Exception { + String template= evaluateTemplateInMethodWithField("void method()", "Collection strings"); + assertEquals( + " for (String string : strings) {\n" + + " \n" + + " }", template); + } + + public void testProposeParamWithField() throws Exception { + String template= evaluateTemplateInMethodWithField("void method(List numbers)", "Collection strings"); + assertEquals( + " for (Number number : numbers) {\n" + + " \n" + + " }", template); + } + } diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/CodeCompletionTest18.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/CodeCompletionTest18.java new file mode 100644 index 0000000000..77382756f9 --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/CodeCompletionTest18.java @@ -0,0 +1,345 @@ +/******************************************************************************* + * Copyright (c) 2014 GK Software AG, IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Stephan Herrmann - initial API and implementation - https://bugs.eclipse.org/425183 + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests.contentassist; + +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.contentassist.ICompletionProposal; +import org.eclipse.jface.text.source.ISourceViewer; + +import org.eclipse.ui.IEditorPart; +import org.eclipse.ui.IEditorReference; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchPartSite; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.PlatformUI; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.JavaUI; +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; +import org.eclipse.jdt.ui.text.java.CompletionProposalCollector; +import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; +import org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; + +public class CodeCompletionTest18 extends AbstractCompletionTest { + + private static final Class THIS= CodeCompletionTest18.class; + + public static Test suite() { + return new Java18ProjectTestSetup(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + private IJavaProject fJProject1; + + + protected void setUp() throws Exception { + fJProject1= Java18ProjectTestSetup.getProject(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "1"); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + options.put(JavaCore.CODEASSIST_FIELD_PREFIXES, "f"); + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); + store.setValue(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, false); + store.setValue(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, false); + + StubUtility.setCodeTemplate(CodeTemplateContextType.OVERRIDECOMMENT_ID, "/* (non-Javadoc)\n * ${see_to_overridden}\n */", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.DELEGATECOMMENT_ID, "/* (non-Javadoc)\n * ${see_to_target}\n */", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "//TODO\n${body_statement}", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID, "/**\n * Constructor.\n */", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODCOMMENT_ID, "/**\n * Method.\n */", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORSTUB_ID, "//TODO\n${body_statement}", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.GETTERCOMMENT_ID, "/**\n * @return the ${bare_field_name}\n */", fJProject1); + StubUtility.setCodeTemplate(CodeTemplateContextType.SETTERCOMMENT_ID, "/**\n * @param ${param} the ${bare_field_name} to set\n */", fJProject1); + } + + protected void tearDown() throws Exception { + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setToDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS); + store.setToDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS); + store.setToDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS); + closeAllEditors(); + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public static void closeEditor(IEditorPart editor) { + IWorkbenchPartSite site; + IWorkbenchPage page; + if (editor != null && (site= editor.getSite()) != null && (page= site.getPage()) != null) + page.closeEditor(editor, false); + } + + public static void closeAllEditors() { + IWorkbenchWindow[] windows= PlatformUI.getWorkbench().getWorkbenchWindows(); + for (int i= 0; i < windows.length; i++) { + IWorkbenchPage[] pages= windows[i].getPages(); + for (int j= 0; j < pages.length; j++) { + IEditorReference[] editorReferences= pages[j].getEditorReferences(); + for (int k= 0; k < editorReferences.length; k++) + closeEditor(editorReferences[k].getEditor(false)); + } + } + } + + private CompletionProposalCollector createCollector(ICompilationUnit cu, int offset) throws PartInitException, JavaModelException { + CompletionProposalCollector collector= new CompletionProposalCollector(cu); + collector.setInvocationContext(createContext(offset, cu)); + return collector; + } + + private JavaContentAssistInvocationContext createContext(int offset, ICompilationUnit cu) throws PartInitException, JavaModelException { + JavaEditor editor= (JavaEditor) JavaUI.openInEditor(cu); + ISourceViewer viewer= editor.getViewer(); + return new JavaContentAssistInvocationContext(viewer, offset, editor); + } + + private void codeComplete(ICompilationUnit cu, int offset, CompletionProposalCollector collector) throws JavaModelException { + cu.codeComplete(offset, collector, new NullProgressMonitor()); + } + + public void testBug425183_comment8() throws CoreException { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); + String contents= + "package test1\n" + + "public class X {\n" + + " void foo() {\n" + + " java.util.Comparator.reverseOrder(). // content assist after '.' => NPE\n" + + " }\n" + + "}\n"; + ICompilationUnit cu= pack1.createCompilationUnit("X.java", contents, false, null); + + + String str= "java.util.Comparator.reverseOrder()."; + + int offset= contents.indexOf(str) + str.length(); + + CompletionProposalCollector collector= createCollector(cu, offset); + + collector.setReplacementLength(0); + + codeComplete(cu, offset, collector); + + IJavaCompletionProposal[] proposals= collector.getJavaCompletionProposals(); + ICompletionProposal proposal= null; + + for (int i= 0; i < proposals.length; i++) { + IJavaCompletionProposal curr= proposals[i]; + if (curr.getDisplayString().startsWith("thenComparingLong")) { + assertNull("more than one proposal for thenComparingLong()", proposal); + proposal= curr; + } + } + assertNotNull("no proposal for thenComparingLong()", proposal); + IEditorPart part= JavaUI.openInEditor(cu); + IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); + proposal.apply(doc); + + String expectedContents= + "package test1\n" + + "public class X {\n" + + " void foo() {\n" + + " java.util.Comparator.reverseOrder().thenComparingLong() // content assist after '.' => NPE\n" + + " }\n" + + "}\n"; + assertEquals(expectedContents, doc.get()); + } + + public void testOverride1() throws CoreException { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Main {\n"); + buf.append(" private static class Cls implements Interface {\n"); + buf.append(" hello\n"); + buf.append(" }\n"); + buf.append(" private static interface Interface {\n"); + buf.append(" default void hello() {\n"); + buf.append(" System.out.println(\"Hello\");\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Main.java", buf.toString(), false, null); + + String str= "hello"; + int offset= buf.toString().indexOf(str) + str.length(); + + CompletionProposalCollector collector= createCollector(cu, offset); + collector.setReplacementLength(0); + codeComplete(cu, offset, collector); + + IJavaCompletionProposal[] proposals= collector.getJavaCompletionProposals(); + assertEquals(1, proposals.length); + IEditorPart part= JavaUI.openInEditor(cu); + IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); + proposals[0].apply(doc); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Main {\n"); + buf.append(" private static class Cls implements Interface {\n"); + buf.append(" /* (non-Javadoc)\n"); + buf.append(" * @see test1.Main.Interface#hello()\n"); + buf.append(" */\n"); + buf.append(" @Override\n"); + buf.append(" public void hello() {\n"); + buf.append(" //TODO\n"); + buf.append(" Interface.super.hello();\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append(" private static interface Interface {\n"); + buf.append(" default void hello() {\n"); + buf.append(" System.out.println(\"Hello\");\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEquals(buf.toString(), doc.get()); + } + + public void testOverride2() throws CoreException { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Main {\n"); + buf.append(" private static interface Bar extends Foo {\n"); + buf.append(" hello\n"); + buf.append(" }\n"); + buf.append(" private static interface Foo {\n"); + buf.append(" default void hello() {\n"); + buf.append(" System.out.println(\"Hello\");\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Main.java", buf.toString(), false, null); + + String str= "hello"; + int offset= buf.toString().indexOf(str) + str.length(); + + CompletionProposalCollector collector= createCollector(cu, offset); + collector.setReplacementLength(0); + codeComplete(cu, offset, collector); + + IJavaCompletionProposal[] proposals= collector.getJavaCompletionProposals(); + assertEquals(1, proposals.length); + IEditorPart part= JavaUI.openInEditor(cu); + IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); + proposals[0].apply(doc); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Main {\n"); + buf.append(" private static interface Bar extends Foo {\n"); + buf.append(" /* (non-Javadoc)\n"); + buf.append(" * @see test1.Main.Foo#hello()\n"); + buf.append(" */\n"); + buf.append(" @Override\n"); + buf.append(" public default void hello() {\n"); + buf.append(" //TODO\n"); + buf.append(" Foo.super.hello();\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append(" private static interface Foo {\n"); + buf.append(" default void hello() {\n"); + buf.append(" System.out.println(\"Hello\");\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEquals(buf.toString(), doc.get()); + } + + public void testOverride3() throws CoreException { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public interface I {\n"); + buf.append(" default int getSize(String name) {\n"); + buf.append(" return name.length();\n"); + buf.append(" }\n"); + buf.append("}\n"); + buf.append("interface I2 extends I {\n"); + buf.append(" getSize\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("I.java", buf.toString(), false, null); + + String str= "getSize"; + int offset= buf.toString().lastIndexOf(str) + str.length(); + + CompletionProposalCollector collector= createCollector(cu, offset); + collector.setReplacementLength(0); + codeComplete(cu, offset, collector); + + IJavaCompletionProposal[] proposals= collector.getJavaCompletionProposals(); + assertEquals(1, proposals.length); + IEditorPart part= JavaUI.openInEditor(cu); + IDocument doc= JavaUI.getDocumentProvider().getDocument(part.getEditorInput()); + proposals[0].apply(doc); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public interface I {\n"); + buf.append(" default int getSize(String name) {\n"); + buf.append(" return name.length();\n"); + buf.append(" }\n"); + buf.append("}\n"); + buf.append("interface I2 extends I {\n"); + buf.append(" /* (non-Javadoc)\n"); + buf.append(" * @see test1.I#getSize(java.lang.String)\n"); + buf.append(" */\n"); + buf.append(" @Override\n"); + buf.append(" public default int getSize(String name) {\n"); + buf.append(" //TODO\n"); + buf.append(" return I.super.getSize(name);\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEquals(buf.toString(), doc.get()); + } + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContentAssistTestSuite.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContentAssistTestSuite.java index 5a2bba897c..3e94834d7b 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContentAssistTestSuite.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContentAssistTestSuite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 IBM Corporation and others. + * Copyright (c) 2005, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -36,6 +36,7 @@ public static Test suite() { suite.addTest(TypeCompletionTest17.suite()); suite.addTest(SpecialMethodsCompletionTest.suite()); suite.addTest(CodeCompletionTest.suite()); + suite.addTest(CodeCompletionTest18.suite()); //$JUnit-END$ return suite; diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_in.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_in.java new file mode 100644 index 0000000000..7d52a8e110 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_in.java @@ -0,0 +1,21 @@ +package p; + +public interface A { + + public abstract void m(int i, int j); +} +class AImpl { + + A i1 = (int i, int j) -> System.out.println(); + A i2 = (i, j) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(int i, int j) { + System.out.println(); + } + }; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_out.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_out.java new file mode 100644 index 0000000000..9e4dd1b599 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda0_out.java @@ -0,0 +1,21 @@ +package p; + +public interface A { + + public abstract void m(int j, int i); +} +class AImpl { + + A i1 = (int j, int i) -> System.out.println(); + A i2 = (j, i) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(int j, int i) { + System.out.println(); + } + }; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_in.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_in.java new file mode 100644 index 0000000000..36d0272f0d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_in.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void m(int i); +} +class AImpl { + + A i1 = (int i) -> System.out.println(); + A i2 = i -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(int i) { + System.out.println(); + } + }; + + private void foo() { + A i4 = i -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_out.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_out.java new file mode 100644 index 0000000000..d4aba5aaad --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda1_out.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void m(int i, int j); +} +class AImpl { + + A i1 = (int i, int j) -> System.out.println(); + A i2 = (i, j) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(int i, int j) { + System.out.println(); + } + }; + + private void foo() { + A i4 = (i, j) -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_in.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_in.java new file mode 100644 index 0000000000..b6c1091a66 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_in.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void m(); +} +class AImpl { + + A i1 = () -> System.out.println(); + A i2 = () -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m() { + System.out.println(); + } + }; + + private void foo() { + A i4 = () -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_out.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_out.java new file mode 100644 index 0000000000..381cabbeea --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda2_out.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void m(int x); +} +class AImpl { + + A i1 = (x) -> System.out.println(); + A i2 = (x) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(int x) { + System.out.println(); + } + }; + + private void foo() { + A i4 = (x) -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_in.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_in.java new file mode 100644 index 0000000000..423e7f707c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_in.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void m(String s); +} +class AImpl { + + A i1 = (String s) -> System.out.println(); + A i2 = (s) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void m(String s) { + System.out.println(); + } + }; + + private void foo() { + A i4 = s -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_out.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_out.java new file mode 100644 index 0000000000..81fac635da --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testLambda3_out.java @@ -0,0 +1,27 @@ +package p; + +public interface A { + + public abstract void newName(String s); +} +class AImpl { + + A i1 = (String s) -> System.out.println(); + A i2 = (s) -> { + System.out.println(); + }; + A i3 = new A() { + + @Override + public void newName(String s) { + System.out.println(); + } + }; + + private void foo() { + A i4 = s -> { + System.out.println(); + }; + + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_in.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_in.java new file mode 100644 index 0000000000..6b5bfc603a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_in.java @@ -0,0 +1,17 @@ +package p; + +import java.util.*; + +class B { + public void bar() { + List people = new ArrayList<>(); + Collections.sort(people, Comparator.comparing(A::m)); // Case1 w/o space + Collections.sort(people, Comparator.comparing(A :: m));// Case2 with space + } +} + +public class A { + String m() { + return null; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_out.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_out.java new file mode 100644 index 0000000000..30cbe8b45e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature18/canModify/A_testMethodReference0_out.java @@ -0,0 +1,17 @@ +package p; + +import java.util.*; + +class B { + public void bar() { + List people = new ArrayList<>(); + Collections.sort(people, Comparator.comparing(A::newName)); // Case1 w/o space + Collections.sort(people, Comparator.comparing(A :: newName));// Case2 with space + } +} + +public class A { + String newName() { + return null; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/in/A.java new file mode 100644 index 0000000000..3ee7c0f3b6 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/in/A.java @@ -0,0 +1,14 @@ +package p; + +public abstract class A { + + public abstract void abstractM(); + + public void m1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/A.java new file mode 100644 index 0000000000..e929f2fdfc --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/A.java @@ -0,0 +1,20 @@ +package p; + +public abstract class A implements B { + + /* (non-Javadoc) + * @see p.B#abstractM() + */ + public abstract void abstractM(); + + /* (non-Javadoc) + * @see p.B#m1(java.lang.String) + */ + public void m1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/B.java new file mode 100644 index 0000000000..82c93dffd4 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromAbstractClass/out/B.java @@ -0,0 +1,10 @@ +package p; + +/** typecomment template*/ +public interface B { + + public abstract void abstractM(); + + public abstract void m1(String s); + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/in/A.java new file mode 100644 index 0000000000..524112913b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/in/A.java @@ -0,0 +1,12 @@ +package p; + +public class A { + + public void m1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/A.java new file mode 100644 index 0000000000..9081cbbe45 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/A.java @@ -0,0 +1,15 @@ +package p; + +public class A implements B { + + /* (non-Javadoc) + * @see p.B#m1(java.lang.String) + */ + public void m1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/B.java new file mode 100644 index 0000000000..6269332012 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromClass/out/B.java @@ -0,0 +1,8 @@ +package p; + +/** typecomment template*/ +public interface B { + + public abstract void m1(String s); + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/in/A.java new file mode 100644 index 0000000000..566eab39fb --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/in/A.java @@ -0,0 +1,19 @@ +package p; + +interface A { + public abstract void abstractM1(); + + public void abstractM2(); + + abstract void abstractM3(); + + void abstractM4(); + + public default void defaultM1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/A.java new file mode 100644 index 0000000000..69d13ffa44 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/A.java @@ -0,0 +1,14 @@ +package p; + +interface A extends B { + /* (non-Javadoc) + * @see p.B#defaultM1(java.lang.String) + */ + public default void defaultM1(String s) { + System.out.println(s); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/B.java new file mode 100644 index 0000000000..bc2010693c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface1/out/B.java @@ -0,0 +1,16 @@ +package p; + +/** typecomment template*/ +interface B { + + public abstract void abstractM1(); + + public abstract void abstractM2(); + + public abstract void abstractM3(); + + public abstract void abstractM4(); + + public abstract void defaultM1(String s); + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/A.java new file mode 100644 index 0000000000..6acd68ef24 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/A.java @@ -0,0 +1,24 @@ +package p; + +import p2.I2; + +public interface A extends I1{ + public static final int count= 10; + public abstract void abstractM1(); + + public void abstractM2(); + + abstract void abstractM3(); + + void abstractM4(); + + public default void defaultM1() { + System.out.println(count); + System.out.println(message); + System.out.println(I2.total); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I1.java new file mode 100644 index 0000000000..1ee2f1b22f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I1.java @@ -0,0 +1,6 @@ +package p; + +public interface I1{ + public static final String message= "Reporting from super interface."; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I2.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I2.java new file mode 100644 index 0000000000..be19d8b1d6 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/in/I2.java @@ -0,0 +1,6 @@ +package p2; + +public interface I2{ + public static final int total= 100; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/A.java new file mode 100644 index 0000000000..662c0fb90f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/A.java @@ -0,0 +1,19 @@ +package p; + +import p2.I2; + +public interface A extends I1, B{ + public static final int count= 10; + /* (non-Javadoc) + * @see p.B#defaultM1() + */ + public default void defaultM1() { + System.out.println(count); + System.out.println(message); + System.out.println(I2.total); + } + + public static void statictM1(String s) { + System.out.println(s); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/B.java new file mode 100644 index 0000000000..2e8ff0f528 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/B.java @@ -0,0 +1,16 @@ +package p; + +/** typecomment template*/ +public interface B { + + public abstract void abstractM1(); + + public abstract void abstractM2(); + + public abstract void abstractM3(); + + public abstract void abstractM4(); + + public abstract void defaultM1(); + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I1.java new file mode 100644 index 0000000000..1ee2f1b22f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I1.java @@ -0,0 +1,6 @@ +package p; + +public interface I1{ + public static final String message= "Reporting from super interface."; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I2.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I2.java new file mode 100644 index 0000000000..be19d8b1d6 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractInterface18/testExtractInterfaceFromInterface2/out/I2.java @@ -0,0 +1,6 @@ +package p2; + +public interface I2{ + public static final int total= 100; + +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1.java new file mode 100644 index 0000000000..64b8db144a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1.java @@ -0,0 +1,7 @@ +package defaultMethods_in; + +public interface A_test1 { + default int foo() { + /*[*/return 0;/*]*/ + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1a.java new file mode 100644 index 0000000000..0a834ec719 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test1a.java @@ -0,0 +1,7 @@ +package defaultMethods_in; + +public interface A_test1a { + public default int foo() { + /*[*/return 0;/*]*/ + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2.java new file mode 100644 index 0000000000..6bcff895f5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2.java @@ -0,0 +1,9 @@ +package defaultMethods_in; + +public class A_test2 { + interface B { + default int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2a.java new file mode 100644 index 0000000000..df92ee3f64 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test2a.java @@ -0,0 +1,9 @@ +package defaultMethods_in; + +public class A_test2a { + interface B { + public default int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3.java new file mode 100644 index 0000000000..3215a2d31d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3.java @@ -0,0 +1,9 @@ +package defaultMethods_in; + +public interface A_test3 { + interface B { + default int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3a.java new file mode 100644 index 0000000000..1b2a88dc7d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test3a.java @@ -0,0 +1,9 @@ +package defaultMethods_in; + +public interface A_test3a { + interface B { + public default int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test4.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test4.java new file mode 100644 index 0000000000..97a255b295 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test4.java @@ -0,0 +1,12 @@ +package staticMethods_in; + +interface A_test4 { + default void foo() { + Runnable r= new Runnable() { + @Override + public void run() { + /*[*/int i = 0;/*]*/ + } + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test5.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test5.java new file mode 100644 index 0000000000..741135a75b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_in/A_test5.java @@ -0,0 +1,11 @@ +package defaultMethods_in; + +public interface A_test5 { + default int foo() { + /*[*/return 0;/*]*/ + } + + static int foo() { + return 0; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1.java new file mode 100644 index 0000000000..f6cf8df007 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1.java @@ -0,0 +1,11 @@ +package defaultMethods_out; + +public interface A_test1 { + default int foo() { + return extracted(); + } + + default int extracted() { + /*[*/return 0;/*]*/ + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1a.java new file mode 100644 index 0000000000..d92fdafc14 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test1a.java @@ -0,0 +1,11 @@ +package defaultMethods_out; + +public interface A_test1a { + public default int foo() { + return extracted(); + } + + public default int extracted() { + /*[*/return 0;/*]*/ + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2.java new file mode 100644 index 0000000000..d4645998a7 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2.java @@ -0,0 +1,13 @@ +package defaultMethods_out; + +public class A_test2 { + interface B { + default int foo() { + return extracted(); + } + } + + protected static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2a.java new file mode 100644 index 0000000000..98cb960cec --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test2a.java @@ -0,0 +1,13 @@ +package defaultMethods_out; + +public class A_test2a { + interface B { + public default int foo() { + return extracted(); + } + } + + protected static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3.java new file mode 100644 index 0000000000..a9988764d5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3.java @@ -0,0 +1,13 @@ +package defaultMethods_out; + +public interface A_test3 { + interface B { + default int foo() { + return extracted(); + } + } + + static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3a.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3a.java new file mode 100644 index 0000000000..58412dd042 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test3a.java @@ -0,0 +1,13 @@ +package defaultMethods_out; + +public interface A_test3a { + interface B { + public default int foo() { + return extracted(); + } + } + + static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test4.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test4.java new file mode 100644 index 0000000000..67becb5baa --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test4.java @@ -0,0 +1,16 @@ +package staticMethods_in; + +interface A_test4 { + default void foo() { + Runnable r= new Runnable() { + @Override + public void run() { + extracted(); + } + }; + } + + default void extracted() { + /*[*/int i = 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test5.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test5.java new file mode 100644 index 0000000000..a88cbb8de3 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/defaultMethods18_out/A_test5.java @@ -0,0 +1,15 @@ +package defaultMethods_out; + +public interface A_test5 { + default int foo() { + return extracted(); + } + + static int extracted() { + /*[*/return 0;/*]*/ + } + + static int foo() { + return extracted(); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test201.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test201.java new file mode 100644 index 0000000000..20446f97ac --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test201.java @@ -0,0 +1,9 @@ +package destination18_in; + +public class A_test201 { + interface B { + @interface C { + int i= /*[*/0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test202.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test202.java new file mode 100644 index 0000000000..9361e42c07 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test202.java @@ -0,0 +1,11 @@ +package destination_in; + +public class A_test202 { + @interface C { + interface B { + default void foo() { + int i= /*[*/0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test203.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test203.java new file mode 100644 index 0000000000..5222c1537b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test203.java @@ -0,0 +1,11 @@ +package destination_in; + +public class A_test203 { + @interface C { + interface B { + default void foo() { + int i= /*[*/0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test204.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test204.java new file mode 100644 index 0000000000..00dbf32dc4 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_in/A_test204.java @@ -0,0 +1,9 @@ +package destination18_in; + +public class A_test204 { + interface B { + @interface C { + int i= /*[*/0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test201.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test201.java new file mode 100644 index 0000000000..a6df53354f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test201.java @@ -0,0 +1,13 @@ +package destination_in; + +public class A_test201 { + interface B { + @interface C { + int i= /*[*/extracted();/*]*/ + } + + static int extracted() { + return 0; + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test202.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test202.java new file mode 100644 index 0000000000..4c9365b2b8 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test202.java @@ -0,0 +1,15 @@ +package destination_in; + +public class A_test202 { + @interface C { + interface B { + default void foo() { + int i= /*[*/extracted();/*]*/ + } + + default int extracted() { + return 0; + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test203.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test203.java new file mode 100644 index 0000000000..108222e100 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test203.java @@ -0,0 +1,15 @@ +package destination_in; + +public class A_test203 { + @interface C { + interface B { + default void foo() { + int i= /*[*/extracted();/*]*/ + } + } + } + + protected static int extracted() { + return 0; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test204.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test204.java new file mode 100644 index 0000000000..179b5a9da3 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination18_out/A_test204.java @@ -0,0 +1,13 @@ +package destination18_in; + +public class A_test204 { + interface B { + @interface C { + int i= /*[*/extracted();/*]*/ + } + } + + protected static int extracted() { + return 0; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1059.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1059.java new file mode 100644 index 0000000000..c9c82c3d41 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1059.java @@ -0,0 +1,9 @@ +package destination_in; + +public class A_test1059 { + interface B { + @interface C { + int i= /*[*/0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1060.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1060.java new file mode 100644 index 0000000000..bc81492628 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1060.java @@ -0,0 +1,11 @@ +package destination_in; + +public class A_test1060 { + interface B { + class C { + int foo() { + /*[*/return 0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1061.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1061.java new file mode 100644 index 0000000000..9810e3f319 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1061.java @@ -0,0 +1,11 @@ +package destination_in; + +public class A_test1061 { + static class B { + class C { + int foo() { + /*[*/return 0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1062.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1062.java new file mode 100644 index 0000000000..7c64ea83ca --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_in/A_test1062.java @@ -0,0 +1,11 @@ +package destination_in; + +public class A_test1062 { + static class B { + class C { + int foo() { + /*[*/return 0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1059.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1059.java new file mode 100644 index 0000000000..29504e965d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1059.java @@ -0,0 +1,13 @@ +package destination_in; + +public class A_test1059 { + interface B { + @interface C { + int i= /*[*/extracted();/*]*/ + } + } + + protected static int extracted() { + return 0; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1060.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1060.java new file mode 100644 index 0000000000..dee74a668f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1060.java @@ -0,0 +1,15 @@ +package destination_in; + +public class A_test1060 { + interface B { + class C { + int foo() { + return extracted(); + } + } + } + + protected static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1061.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1061.java new file mode 100644 index 0000000000..0b4002f750 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1061.java @@ -0,0 +1,15 @@ +package destination_in; + +public class A_test1061 { + static class B { + class C { + int foo() { + return extracted(); + } + } + + protected int extracted() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1062.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1062.java new file mode 100644 index 0000000000..2b8992b38e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/destination_out/A_test1062.java @@ -0,0 +1,15 @@ +package destination_in; + +public class A_test1062 { + static class B { + class C { + int foo() { + return extracted(); + } + } + } + + protected static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test301.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test301.java new file mode 100644 index 0000000000..d2caac2f69 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test301.java @@ -0,0 +1,13 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + I1 i1= (int a) -> { + /*[*/int b = 10;/*]*/ + return a + b; + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test302.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test302.java new file mode 100644 index 0000000000..4e8a533176 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test302.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + class Y { + I1 i1 = (int a) -> { + /*[*/int b = 10;/*]*/ + return a + b; + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test303.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test303.java new file mode 100644 index 0000000000..1a091d24de --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test303.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + void foo() { + I1 i1 = (int a) -> { + /*[*/int b = 10;/*]*/ + return a + b; + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test304.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test304.java new file mode 100644 index 0000000000..a27c97450c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test304.java @@ -0,0 +1,21 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + void bar() { + Runnable r = new Runnable() { + I1 i1 = (int a) -> { + /*[*/int b = 10;/*]*/ + return a + b; + }; + + @Override + public void run() { + } + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test305.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test305.java new file mode 100644 index 0000000000..fb2ea904e9 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test305.java @@ -0,0 +1,13 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +interface I2 { + I1 i1 = (a) -> { + /*[*/int b = 10;/*]*/ + return a + b; + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test306.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test306.java new file mode 100644 index 0000000000..f7eab18ad3 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test306.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +interface I2 { + public default int foo() { + I1 i1 = (a) -> { + /*[*/int b = a;/*]*/ + return a + b; + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test307.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test307.java new file mode 100644 index 0000000000..99b3b053d6 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test307.java @@ -0,0 +1,13 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + I1 i1= (a) -> { + /*[*/int b = a;/*]*/ + return a + b; + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test308.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test308.java new file mode 100644 index 0000000000..6897aa739f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test308.java @@ -0,0 +1,12 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + I i= a -> { + /*[*/ return a++; /*]*/ + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test309.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test309.java new file mode 100644 index 0000000000..3a4357e49d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test309.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + String foo() { + I i= a -> { + /*[*/ return a++; /*]*/ + }; + return ""; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test310.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test310.java new file mode 100644 index 0000000000..15ffa8d64b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test310.java @@ -0,0 +1,21 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + String bar() { + I i4= a -> { + class X { + float bar() { + /*[*/ return 100; /*]*/ + } + } + return a++; + }; + + return ""; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test311.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test311.java new file mode 100644 index 0000000000..6975bccf4a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test311.java @@ -0,0 +1,12 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface J { + void foo(); +} + +class X1 { + J j1= () -> { + /*[*/ return; /*]*/ + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test312.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test312.java new file mode 100644 index 0000000000..1a494e482f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test312.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface J { + void foo(); +} + +class X1 { + J j_1= () -> /*]*/ {}; /*[*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test313.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test313.java new file mode 100644 index 0000000000..6c117927cb --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test313.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface J { + void foo(); +} + +class X1 { + String m1() { + /*[*/J j2= () -> { + return; + };/*]*/ + return ""; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test314.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test314.java new file mode 100644 index 0000000000..48d256249d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test314.java @@ -0,0 +1,14 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +class X { + void foo() { + I1 i1= /*]*/a -> { + return a + 10; + }/*[*/ ; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test315.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test315.java new file mode 100644 index 0000000000..570faad82a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test315.java @@ -0,0 +1,15 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +class X { + void foo() { + bar(/*[*/(a) -> a + 10/*]*/); + } + + void bar(I1 i) { + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test316.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test316.java new file mode 100644 index 0000000000..4334c2bff5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test316.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +interface X { + I1 i2= a -> /*[*/ a++; /*]*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test317.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test317.java new file mode 100644 index 0000000000..b3fe2af89d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test317.java @@ -0,0 +1,13 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +interface C_Test { + default String foo() { + I i= a -> /*[*/ a++; /*]*/ + return ""; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test318.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test318.java new file mode 100644 index 0000000000..3df7a869af --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test318.java @@ -0,0 +1,12 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +interface I_Test { + I i = a -> /*]*/{ + return Integer.valueOf(a); + };/*[*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test319.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test319.java new file mode 100644 index 0000000000..da5c33aea1 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test319.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface F { + String foo(); +} + +interface I_Test { + F f_11= () -> /*[*/ "abc"; /*]*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test320.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test320.java new file mode 100644 index 0000000000..e976b92b6c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test320.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface F { + void foo(); +} + +interface I_Test { + /*]*/F f_0= () -> {};/*[*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test321.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test321.java new file mode 100644 index 0000000000..66f330611f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test321.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface F { + void foo(); +} + +interface I_Test { + /*]*/F f_1= () -> {}/*[*/; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test322.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test322.java new file mode 100644 index 0000000000..2c497b7b46 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test322.java @@ -0,0 +1,10 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface F { + int foo(int s1, int s2); +} + +interface I_Test { + F f_1= (/*]*/int n1, int n2/*[*/) -> n1 * n2; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test323.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test323.java new file mode 100644 index 0000000000..4fb9f20c7a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test323.java @@ -0,0 +1,18 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo1(int s1, int s2); +} + +@FunctionalInterface +interface I2 { + I1 foo2(int n1); +} + +interface I_Test { + static I2 i2 = x1 -> (a1, b1) -> {/*]*/ + int m = 4; + return m; + /*[*/}; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test324.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test324.java new file mode 100644 index 0000000000..f42c4e2ddc --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test324.java @@ -0,0 +1,29 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + void foo(String s); +} + +class I_Test { + public boolean flag; + + public int foo() { + int i = 10; + + I1 i1 = s -> { + /*]*/switch (i) { + case 1: + if (flag) + break; + foo(); + case 2: + return; + default: + throw new NullPointerException(); + }/*[*/ + }; + + return i; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test325.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test325.java new file mode 100644 index 0000000000..1113415c70 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_in/A_test325.java @@ -0,0 +1,16 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface FI { + int foo1(int a); +} + +class FI_1 { + void fun(int a) { + FI i1 = x1-> x1; + FI i2 = xxx-> { + i1.foo1(a); + /*]*/return xxx;/*[*/ + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test301.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test301.java new file mode 100644 index 0000000000..9f1f958ba1 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test301.java @@ -0,0 +1,18 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + I1 i1= (int a) -> { + int b = extracted(); + return a + b; + }; + + private int extracted() { + /*[*/int b = 10;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test302.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test302.java new file mode 100644 index 0000000000..3275ea4b33 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test302.java @@ -0,0 +1,20 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + class Y { + I1 i1 = (int a) -> { + int b = extracted(); + return a + b; + }; + } + + private int extracted() { + /*[*/int b = 10;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test303.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test303.java new file mode 100644 index 0000000000..e7e851cd4a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test303.java @@ -0,0 +1,20 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + void foo() { + I1 i1 = (int a) -> { + int b = extracted(); + return a + b; + }; + } + + private int extracted() { + /*[*/int b = 10;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test304.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test304.java new file mode 100644 index 0000000000..9d26fa55f0 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test304.java @@ -0,0 +1,26 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + void bar() { + Runnable r = new Runnable() { + I1 i1 = (int a) -> { + int b = extracted(); + return a + b; + }; + + private int extracted() { + /*[*/int b = 10;/*]*/ + return b; + } + + @Override + public void run() { + } + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test305.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test305.java new file mode 100644 index 0000000000..d1c7b16965 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test305.java @@ -0,0 +1,18 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +interface I2 { + I1 i1 = (a) -> { + int b = extracted(); + return a + b; + }; + + static int extracted() { + /*[*/int b = 10;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test306.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test306.java new file mode 100644 index 0000000000..5f9721661f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test306.java @@ -0,0 +1,20 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +interface I2 { + public default int foo() { + I1 i1 = (a) -> { + int b = extracted(a); + return a + b; + }; + } + + public default int extracted(int a) { + /*[*/int b = a;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test307.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test307.java new file mode 100644 index 0000000000..f9839d0c7e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test307.java @@ -0,0 +1,18 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo(int a); +} + +class X { + I1 i1= (a) -> { + int b = extracted(a); + return a + b; + }; + + private int extracted(int a) { + /*[*/int b = a;/*]*/ + return b; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test308.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test308.java new file mode 100644 index 0000000000..4b184f4d4e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test308.java @@ -0,0 +1,16 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + I i= a -> { + return extracted(a); + }; + + private int extracted(int a) { + /*[*/ return a++; /*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test309.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test309.java new file mode 100644 index 0000000000..31f41f9c7d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test309.java @@ -0,0 +1,19 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + String foo() { + I i= a -> { + return extracted(a); + }; + return ""; + } + + private int extracted(int a) { + /*[*/ return a++; /*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test310.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test310.java new file mode 100644 index 0000000000..abaf64fcc3 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test310.java @@ -0,0 +1,25 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +class C_Test { + String bar() { + I i4= a -> { + class X { + float bar() { + return extracted(); + } + + private float extracted() { + /*[*/ return 100; /*]*/ + } + } + return a++; + }; + + return ""; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test311.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test311.java new file mode 100644 index 0000000000..be964fd6fb --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test311.java @@ -0,0 +1,16 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface J { + void foo(); +} + +class X1 { + J j1= () -> { + extracted(); + }; + + private void extracted() { + /*[*/ return; /*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test313.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test313.java new file mode 100644 index 0000000000..9e590080d4 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test313.java @@ -0,0 +1,19 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface J { + void foo(); +} + +class X1 { + String m1() { + extracted(); + return ""; + } + + private void extracted() { + /*[*/J j2= () -> { + return; + };/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test314.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test314.java new file mode 100644 index 0000000000..074c914ccd --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test314.java @@ -0,0 +1,18 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +class X { + void foo() { + I1 i1= /*]*/extracted()/*[*/ ; + } + + private I1 extracted() { + return a -> { + return a + 10; + }; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test315.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test315.java new file mode 100644 index 0000000000..d46c118d34 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test315.java @@ -0,0 +1,19 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +class X { + void foo() { + bar(extracted()); + } + + private I1 extracted() { + return /*[*/(a) -> a + 10/*]*/; + } + + void bar(I1 i) { + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test316.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test316.java new file mode 100644 index 0000000000..791af34ef9 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test316.java @@ -0,0 +1,14 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I1 { + int foo(int a); +} + +interface X { + I1 i2= a -> /*[*/ extracted(a); /*]*/ + + static int extracted(int a) { + return a++; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test317.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test317.java new file mode 100644 index 0000000000..000c794d58 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test317.java @@ -0,0 +1,17 @@ +package lambdaExpression18_in; + +@FunctionalInterface +public interface I { + int foo(int a); +} + +interface C_Test { + default String foo() { + I i= a -> /*[*/ extracted(a); /*]*/ + return ""; + } + + default int extracted(int a) { + return a++; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test319.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test319.java new file mode 100644 index 0000000000..c8c5d4a4ac --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test319.java @@ -0,0 +1,14 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface F { + String foo(); +} + +interface I_Test { + F f_11= () -> /*[*/ extracted(); /*]*/ + + static String extracted() { + return "abc"; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test323.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test323.java new file mode 100644 index 0000000000..253a48702f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test323.java @@ -0,0 +1,22 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface I1 { + int foo1(int s1, int s2); +} + +@FunctionalInterface +interface I2 { + I1 foo2(int n1); +} + +interface I_Test { + static I2 i2 = x1 -> (a1, b1) -> {/*]*/ + return extracted(); + /*[*/}; + + static int extracted() { + int m = 4; + return m; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test325.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test325.java new file mode 100644 index 0000000000..43b31fc98a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/lambdaExpression18_out/A_test325.java @@ -0,0 +1,20 @@ +package lambdaExpression18_in; + +@FunctionalInterface +interface FI { + int foo1(int a); +} + +class FI_1 { + void fun(int a) { + FI i1 = x1-> x1; + FI i2 = xxx-> { + i1.foo1(a); + /*]*/return extracted(xxx);/*[*/ + }; + } + + private int extracted(int xxx) { + return xxx; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test101.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test101.java new file mode 100644 index 0000000000..debc458b1c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test101.java @@ -0,0 +1,9 @@ +package staticMethods_in; + +public interface A_test101 { + class B { + int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test102.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test102.java new file mode 100644 index 0000000000..9515e574a5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test102.java @@ -0,0 +1,9 @@ +package staticMethods_in; + +interface A_test102 { + class B { + static { + /*[*/int i= 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test103.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test103.java new file mode 100644 index 0000000000..21f9f73cdf --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test103.java @@ -0,0 +1,6 @@ +package staticMethods_in; + +interface A_test103 { + int i= 0; + int j= /*[*/i + 10;/*]*/ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test104.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test104.java new file mode 100644 index 0000000000..d05459b329 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test104.java @@ -0,0 +1,11 @@ +package staticMethods_in; + +interface A_test104 { + Runnable r= new Runnable() { + @Override + public void run() { + /*[*/int i = 0;/*]*/ + System.out.println(i); + } + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test105.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test105.java new file mode 100644 index 0000000000..aa3e547fd7 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test105.java @@ -0,0 +1,11 @@ +package staticMethods_in; + +interface A_test105 { + enum E { + A { + int foo() { + /*[*/return 0;/*]*/ + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test106.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test106.java new file mode 100644 index 0000000000..b4086ba6c3 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test106.java @@ -0,0 +1,10 @@ +package staticMethods_in; + +interface A_test106 { + enum E { + A; + int foo() { + /*[*/return 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test107.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test107.java new file mode 100644 index 0000000000..7cc10a5b14 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_in/A_test107.java @@ -0,0 +1,9 @@ +package staticMethods_in; + +interface A_test107 { + class B { + { + /*[*/int i= 0;/*]*/ + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test101.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test101.java new file mode 100644 index 0000000000..46d0c8a85b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test101.java @@ -0,0 +1,13 @@ +package staticMethods_out; + +public interface A_test101 { + class B { + int foo() { + return extracted(); + } + } + + static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test102.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test102.java new file mode 100644 index 0000000000..b5c0880186 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test102.java @@ -0,0 +1,13 @@ +package staticMethods_in; + +interface A_test102 { + class B { + static { + extracted(); + } + } + + static void extracted() { + /*[*/int i= 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test103.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test103.java new file mode 100644 index 0000000000..45471499b0 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test103.java @@ -0,0 +1,9 @@ +package staticMethods_in; + +interface A_test103 { + int i= 0; + int j= /*[*/extracted();/*]*/ + static int extracted() { + return i + 10; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test104.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test104.java new file mode 100644 index 0000000000..ea247bcd70 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test104.java @@ -0,0 +1,16 @@ +package staticMethods_in; + +interface A_test104 { + static int extracted() { + /*[*/int i = 0;/*]*/ + return i; + } + + Runnable r= new Runnable() { + @Override + public void run() { + int i = extracted(); + System.out.println(i); + } + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test105.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test105.java new file mode 100644 index 0000000000..07af08dd0e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test105.java @@ -0,0 +1,15 @@ +package staticMethods_in; + +interface A_test105 { + enum E { + A { + int foo() { + return extracted(); + } + } + } + + static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test106.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test106.java new file mode 100644 index 0000000000..a55d5bbfc5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test106.java @@ -0,0 +1,14 @@ +package staticMethods_in; + +interface A_test106 { + enum E { + A; + int foo() { + return extracted(); + } + } + + static int extracted() { + /*[*/return 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test107.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test107.java new file mode 100644 index 0000000000..a93844604a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/staticMethods18_out/A_test107.java @@ -0,0 +1,13 @@ +package staticMethods_in; + +interface A_test107 { + class B { + { + extracted(); + } + } + + static void extracted() { + /*[*/int i= 0;/*]*/ + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/in/A.java new file mode 100644 index 0000000000..6c9c733414 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/in/A.java @@ -0,0 +1,16 @@ +package p; + +public class A { + static final String EXT2_CLASS = ".class"; + + enum Replacer2 { + NILL1(EXT2_CLASS), + NILL2(A.EXT2_CLASS); + + String s; + + Replacer2(String s) { + this.s = s; + } + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/out/A.java new file mode 100644 index 0000000000..da3e3d8e71 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test40/out/A.java @@ -0,0 +1,14 @@ +package p; + +public class A { + enum Replacer2 { + NILL1(".class"), + NILL2(".class"); + + String s; + + Replacer2(String s) { + this.s = s; + } + } + } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/in/A.java new file mode 100644 index 0000000000..318fdf52a9 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/in/A.java @@ -0,0 +1,16 @@ +package p; + +public class A { + static final String EXT2_CLASS= ".class"; + + enum Replacer2 { + NILL1(EXT2_CLASS), + NILL2(A.EXT2_CLASS); + + String s; + + Replacer2(String s) { + this.s= s; + } + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/out/A.java new file mode 100644 index 0000000000..81b078b7c5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineConstant/canInline/test41/out/A.java @@ -0,0 +1,14 @@ +package p; + +public class A { + enum Replacer2 { + NILL1(".class"), + NILL2(".class"); + + String s; + + Replacer2(String s) { + this.s= s; + } + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/A.java new file mode 100644 index 0000000000..18d89a371b --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/A.java @@ -0,0 +1,5 @@ +package p; +public class A{ + private static int m(){ return 1;}; + public static int i= m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/B.java new file mode 100644 index 0000000000..93910c8f26 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/in/B.java @@ -0,0 +1,3 @@ +package p; +interface B{ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/A.java new file mode 100644 index 0000000000..42d5c8c5b0 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/A.java @@ -0,0 +1,4 @@ +package p; +public class A{ + public static int i= B.m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/B.java new file mode 100644 index 0000000000..2e386bbf3f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_1/out/B.java @@ -0,0 +1,5 @@ +package p; +interface B{ + + static int m(){ return 1;} +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/A.java new file mode 100644 index 0000000000..01a7295086 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/A.java @@ -0,0 +1,5 @@ +package p; +public interface A{ + static int m(){ return 1;}; + int i= m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/B.java new file mode 100644 index 0000000000..93910c8f26 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/in/B.java @@ -0,0 +1,3 @@ +package p; +interface B{ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/A.java new file mode 100644 index 0000000000..e8f4e139ad --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/A.java @@ -0,0 +1,4 @@ +package p; +public interface A{ + int i= B.m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/B.java new file mode 100644 index 0000000000..2e386bbf3f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_2/out/B.java @@ -0,0 +1,5 @@ +package p; +interface B{ + + static int m(){ return 1;} +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/A.java new file mode 100644 index 0000000000..01a7295086 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/A.java @@ -0,0 +1,5 @@ +package p; +public interface A{ + static int m(){ return 1;}; + int i= m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/B.java new file mode 100644 index 0000000000..d110d65e7a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/in/B.java @@ -0,0 +1,3 @@ +package p; +class B{ +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/A.java new file mode 100644 index 0000000000..e8f4e139ad --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/A.java @@ -0,0 +1,4 @@ +package p; +public interface A{ + int i= B.m(); +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/B.java b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/B.java new file mode 100644 index 0000000000..446ef2471f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18_3/out/B.java @@ -0,0 +1,5 @@ +package p; +class B{ + + public static int m(){ return 1;} +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods1.java new file mode 100644 index 0000000000..ff3807c922 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods1.java @@ -0,0 +1,8 @@ +//6, 13, 6, 14 +package p; + +interface I { + default void defaultMethod() { + int i; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods2.java b/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods2.java new file mode 100644 index 0000000000..5525b3cf23 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/cannotPromote/A_testFailInterfaceMethods2.java @@ -0,0 +1,8 @@ +//6, 13, 6, 14 +package p; + +interface I { + static void staticMethod() { + int i; + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/in/A.java new file mode 100644 index 0000000000..5abbe088b1 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/in/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i= (int /*[*/f/*]*/) -> { + int p= 10; + return ii.foo(f) + p; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/out/A.java new file mode 100644 index 0000000000..e9b62351ad --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda0/out/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i= (int /*[*/renamedF/*]*/) -> { + int p= 10; + return ii.foo(renamedF) + p; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/in/A.java new file mode 100644 index 0000000000..1f0245f131 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/in/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i= (int f) -> { + int /*[*/p/*]*/= 10; + return ii.foo(f) + p; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/out/A.java new file mode 100644 index 0000000000..b2dc1b1630 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda1/out/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i= (int f) -> { + int /*[*/renamedP/*]*/= 10; + return ii.foo(f) + renamedP; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/in/A.java new file mode 100644 index 0000000000..93056d1719 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/in/A.java @@ -0,0 +1,13 @@ +package p; +@FunctionalInterface +interface I { + int foo (int x); +} + +public class C1 { + I i= (int x) -> { + int p= 10; + I /*[*/ii/*]*/= (int a) -> a+100; + return ii.foo(x) + p; + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/out/A.java new file mode 100644 index 0000000000..b0b207f177 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda2/out/A.java @@ -0,0 +1,13 @@ +package p; +@FunctionalInterface +interface I { + int foo (int x); +} + +public class C1 { + I i= (int x) -> { + int p= 10; + I /*[*/renamedIi/*]*/= (int a) -> a+100; + return renamedIi.foo(x) + p; + }; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/in/A.java new file mode 100644 index 0000000000..67479ed91f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/in/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i1= (x) -> { + x++; + return /*[*/x/*]*/; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/out/A.java new file mode 100644 index 0000000000..df7774f3b7 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testLambda3/out/A.java @@ -0,0 +1,12 @@ +package p; + @FunctionalInterface + interface I { + int foo (int x); + } + + public class A { + I i1= (x_renamed) -> { + x_renamed++; + return /*[*/x_renamed/*]*/; + }; + } diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/in/A.java new file mode 100644 index 0000000000..c46bc4b0ab --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/in/A.java @@ -0,0 +1,9 @@ +package p; +@FunctionalInterface +interface I { + int m(); +} + +public class A { + I i1= () -> 2; +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/out/A.java new file mode 100644 index 0000000000..5e25f4ddda --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod0/out/A.java @@ -0,0 +1,9 @@ +package p; +@FunctionalInterface +interface I { + int k(); +} + +public class A { + I i1= () -> 2; +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/in/A.java new file mode 100644 index 0000000000..bde80b913d --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/in/A.java @@ -0,0 +1,19 @@ +package p; +@FunctionalInterface +interface I { + int m(); +} + +public class A implements I { + I i1= this::m; + I i2= A::length; + + @Override + public int m() { + return 0; + } + + public static int length() { + return 42; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/out/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/out/A.java new file mode 100644 index 0000000000..5ddd706338 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/RenameTests18/testMethod1/out/A.java @@ -0,0 +1,19 @@ +package p; +@FunctionalInterface +interface I { + int k(); +} + +public class A implements I { + I i1= this::k; + I i2= A::length; + + @Override + public int k() { + return 0; + } + + public static int length() { + return 42; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.classpath b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.classpath new file mode 100644 index 0000000000..fc8ee0f7b6 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.settings/org.eclipse.jdt.core.prefs b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..295926d964 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,7 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_in/TestArrayAnnotations.java b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_in/TestArrayAnnotations.java new file mode 100644 index 0000000000..c30ea2ebe5 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_in/TestArrayAnnotations.java @@ -0,0 +1,18 @@ +package object_in; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE_USE) @interface A {} +@Target(ElementType.TYPE_USE) @interface B {} +@Target(ElementType.TYPE_USE) @interface C {} +@Target(ElementType.TYPE_USE) @interface D {} +@Target(ElementType.TYPE_USE) @interface E {} + +public class TestArrayAnnotations { + boolean @D[]@E[] field@A[]@B []@C[]; + + public TestArrayAnnotations() { + field= new boolean[0][][][][]; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_out/TestArrayAnnotations.java b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_out/TestArrayAnnotations.java new file mode 100644 index 0000000000..ea3e431d5a --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/object_out/TestArrayAnnotations.java @@ -0,0 +1,26 @@ +package object_out; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE_USE) @interface A {} +@Target(ElementType.TYPE_USE) @interface B {} +@Target(ElementType.TYPE_USE) @interface C {} +@Target(ElementType.TYPE_USE) @interface D {} +@Target(ElementType.TYPE_USE) @interface E {} + +public class TestArrayAnnotations { + private boolean @D[]@E[] field@A[]@B []@C[]; + + public TestArrayAnnotations() { + setField(new boolean[0][][][][]); + } + + boolean@A[]@B []@C[]@D[]@E[] getField() { + return field; + } + + void setField(boolean @D[]@E[] field@A[]@B []@C[]) { + this.field = field; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_in/TestSimple1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_in/TestSimple1.java new file mode 100644 index 0000000000..d61cd36425 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_in/TestSimple1.java @@ -0,0 +1,14 @@ +package trycatch18_in; + +import java.io.FileNotFoundException; +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +class TestSimple1 { + void foo(int a) { + /*[*/throw new @Marker FileNotFoundException();/*]*/ + } +} + +@Target(ElementType.TYPE_USE) +@interface Marker { } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_out/TestSimple1.java b/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_out/TestSimple1.java new file mode 100644 index 0000000000..cb06ccdc9c --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch18_out/TestSimple1.java @@ -0,0 +1,17 @@ +package trycatch18_out; + +import java.io.FileNotFoundException; +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +class TestSimple1 { + void foo(int a) { + try { + /*[*/throw new @Marker FileNotFoundException();/*]*/ + } catch (@Marker FileNotFoundException e) { + } + } +} + +@Target(ElementType.TYPE_USE) +@interface Marker { } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java index 53957f0269..12ba2a5a1a 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AbstractSelectionTestCase.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,6 +39,11 @@ import org.eclipse.jdt.ui.tests.refactoring.infra.AbstractCUTestCase; import org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin; +/** + * Selection in the file read by {@link #getFileContents(InputStream)} is marked with + * /*]*/ and /*[*/ (excluding the marker comments) or + * /*[*/ and /*]*/ (including comments). + */ public abstract class AbstractSelectionTestCase extends AbstractCUTestCase { public static final String SQUARE_BRACKET_OPEN= "/*[*/"; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java index 4310a79a24..cdefabb45e 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllRefactoringTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,9 +21,12 @@ public class AllRefactoringTests { public static Test suite() { TestSuite suite= new TestSuite(clazz.getName()); + suite.addTest(RenameTests18.suite()); + //--code suite.addTest(ExtractMethodTests.suite()); suite.addTest(ExtractMethodTests17.suite()); + suite.addTest(ExtractMethodTests18.suite()); suite.addTest(InlineMethodTests.suite()); suite.addTest(ReplaceInvocationsTests.suite()); suite.addTest(SefTests.suite()); @@ -43,11 +46,14 @@ public static Test suite() { //-- structure suite.addTest(ChangeSignatureTests.suite()); + suite.addTest(ChangeSignatureTests18.suite()); suite.addTest(IntroduceParameterObjectTests.suite()); suite.addTest(PullUpTests.suite()); suite.addTest(PushDownTests.suite()); suite.addTest(MoveMembersTests.suite()); + suite.addTest(MoveMembersTests18.suite()); suite.addTest(ExtractInterfaceTests.suite()); + suite.addTest(ExtractInterfaceTests18.suite()); suite.addTest(ExtractSupertypeTests.suite()); suite.addTest(MoveInnerToTopLevelTests.suite()); suite.addTest(UseSupertypeWherePossibleTests.suite()); diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java index b6cc18bcb4..33d24df29e 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -26,6 +26,7 @@ public static Test suite() { suite.addTest(RefactoringScannerTests.suite()); suite.addTest(SurroundWithTests.suite()); suite.addTest(SurroundWithTests17.suite()); + suite.addTest(SurroundWithTests18.suite()); return suite; } } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java index 65e2d7010e..f422cae06b 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -56,6 +56,7 @@ public ChangeSignatureTests(String name) { super(name); } + @Override protected String getRefactoringPath() { return REFACTORING_PATH; } @@ -110,7 +111,7 @@ static void addInfos(List list, ParameterInfo[] newParamInfos, int[] newIndices) } } - private void helperAdd(String[] signature, ParameterInfo[] newParamInfos, int[] newIndices) throws Exception { + protected void helperAdd(String[] signature, ParameterInfo[] newParamInfos, int[] newIndices) throws Exception { helperAdd(signature, newParamInfos, newIndices, false); } @@ -149,7 +150,7 @@ private static void assertParticipant(IType typeOfMethod) throws JavaModelExcept /* * Rename method 'A.m(signature)' to 'A.newMethodName(signature)' */ - private void helperRenameMethod(String[] signature, String newMethodName, boolean createDelegate, boolean markAsDeprecated) throws Exception { + protected void helperRenameMethod(String[] signature, String newMethodName, boolean createDelegate, boolean markAsDeprecated) throws Exception { ICompilationUnit cu= createCUfromTestFile(getPackageP(), true, true); IType classA= getType(cu, "A"); IMethod method = classA.getMethod("m", signature); @@ -240,7 +241,7 @@ private void markAsDeleted(List list, int[] deleted) { } } - private void helper1(String[] newOrder, String[] signature) throws Exception{ + protected void helper1(String[] newOrder, String[] signature) throws Exception { helper1(newOrder, signature, null, null); } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests18.java new file mode 100644 index 0000000000..741ac4f586 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests18.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ + +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +import org.eclipse.jdt.core.IJavaProject; + +import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; + +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +public class ChangeSignatureTests18 extends ChangeSignatureTests { + + private static final Class THIS= ChangeSignatureTests18 .class; + + private IJavaProject fJProject1; + + public ChangeSignatureTests18 (String name) { + super(name); + } + + @Override + protected String getRefactoringPath() { + return "ChangeSignature18/"; + } + + public static Test suite() { + return new Java18ProjectTestSetup(new NoSuperTestsSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(new RefactoringTestSetup(test)); + } + + @Override + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + @Override + protected void setUp() throws Exception { + fJProject1= Java18ProjectTestSetup.getProject(); + fRoot= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + fPackageP= fRoot.createPackageFragment("p", true, null); + fIsPreDeltaTest= false; + RefactoringCore.getUndoManager().flush(); + } + + // Exchange the method parameters + public void testLambda0() throws Exception { + helper1(new String[]{"j", "i"}, new String[]{"I", "I"}); + } + + // Add an extra method parameter + public void testLambda1() throws Exception { + String[] signature= { "I" }; + String[] newNames= { "j" }; + String[] newTypes= { "int" }; + String[] newDefaultValues= { "0" }; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= { 1 }; + helperAdd(signature, newParamInfo, newIndices); + } + + // Add a new method parameter to an empty parameter method + public void testLambda2() throws Exception { + String[] signature= {}; + String[] newNames= { "x" }; + String[] newTypes= { "int" }; + String[] newDefaultValues= { "0" }; + ParameterInfo[] newParamInfo= createNewParamInfos(newTypes, newNames, newDefaultValues); + int[] newIndices= { 0 }; + helperAdd(signature, newParamInfo, newIndices); + } + + // Rename method + public void testLambda3() throws Exception { + String[] signature= { "QString;" }; + helperRenameMethod(signature, "newName", false, true); + } + + // Rename method involving method reference + public void testMethodReference0() throws Exception { + String[] signature= {}; + helperRenameMethod(signature, "newName", false, true); + } + + // TODO Remove a method parameter +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java index b72880f6fd..355cb4360a 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -42,6 +42,7 @@ public class ExtractConstantTests extends RefactoringTest { private static final String REFACTORING_PATH = "ExtractConstant/"; private static final boolean BUG_86113_ImportRewrite= true; + private static final boolean BUG_405780= true; //XXX: [1.8][compiler] Bad syntax error 'insert ":: IdentifierOrNew"' for missing semicolon private Object fCompactPref; private boolean fAddComments; @@ -307,6 +308,8 @@ public void test33() throws Exception { //bug 108354 } public void test34() throws Exception { // syntax error + if (BUG_405780) + return; helper1(7, 20, 7, 35, true, false, "STRING", "STRING"); } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java index 7dcc92d87c..90ccb6561a 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,10 +55,12 @@ public static Test setUpTest(Test someTest) { return new RefactoringTestSetup(someTest); } + @Override protected String getRefactoringPath() { return REFACTORING_PATH; } + @Override protected void setUp() throws Exception { super.setUp(); StubUtility.setCodeTemplate(CodeTemplateContextType.NEWTYPE_ID, @@ -80,13 +82,14 @@ protected void setUp() throws Exception { JavaCore.setOptions(options); } - protected void tearDown() throws Exception { + @Override + protected void tearDown() throws Exception { super.tearDown(); JavaCore.setOptions(fOldOptions); fOldOptions= null; } - private static String getTopLevelTypeName(String typeQualifiedTyperName){ + protected static String getTopLevelTypeName(String typeQualifiedTyperName) { int dotIndex= typeQualifiedTyperName.indexOf('.'); if (dotIndex == -1) return typeQualifiedTyperName; @@ -130,7 +133,7 @@ private void validatePassingTest(String className, String[] cuNames, String newI assertEqualLines("(interface cu)", getFileContents(getOutputTestFileName(newInterfaceName)), interfaceCu.getSource()); } - private void validatePassingTest(String className, String newInterfaceName, boolean extractAll, boolean replaceOccurrences) throws Exception { + protected void validatePassingTest(String className, String newInterfaceName, boolean extractAll, boolean replaceOccurrences) throws Exception { IType clas= getClassFromTestFile(getPackageP(), className); ICompilationUnit cu= clas.getCompilationUnit(); IPackageFragment pack= (IPackageFragment)cu.getParent(); diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests18.java new file mode 100644 index 0000000000..dbe236c57f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests18.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.List; + +import junit.framework.Test; + +import org.eclipse.ltk.core.refactoring.Refactoring; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.ProcessorBasedRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; + +import org.eclipse.jdt.internal.corext.refactoring.structure.ExtractInterfaceProcessor; + +import org.eclipse.jdt.ui.tests.core.NoSuperTestsSuite; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; + +public class ExtractInterfaceTests18 extends ExtractInterfaceTests { + + private static final Class clazz= ExtractInterfaceTests18.class; + + private static final String REFACTORING_PATH= "ExtractInterface18/"; + + public ExtractInterfaceTests18(String name) { + super(name); + } + + public static Test suite() { + return new Java18Setup(new NoSuperTestsSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java18Setup(someTest); + } + + @Override + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + public void testExtractInterfaceFromInterface1() throws Exception { + validatePassingTest("A", "B", true, true); + } + + public void testExtractInterfaceFromInterface2() throws Exception { + String className= "A"; + String extendingInterfaceName= "I1"; + String newInterfaceName= "B"; + + IType clas= getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(className)), className); + ICompilationUnit cu= clas.getCompilationUnit(); + IPackageFragment pack= (IPackageFragment)cu.getParent(); + + getType(createCUfromTestFile(getPackageP(), getTopLevelTypeName(extendingInterfaceName)), extendingInterfaceName); + + IPackageFragmentRoot root= RefactoringTestSetup.getDefaultSourceFolder(); + assertNotNull(root); + IPackageFragment p2= root.createPackageFragment("p2", true, null); + getType(createCUfromTestFile(p2, getTopLevelTypeName("I2")), "I2"); + + ExtractInterfaceProcessor processor= new ExtractInterfaceProcessor(clas, JavaPreferencesSettings.getCodeGenerationSettings(clas.getJavaProject())); + Refactoring ref= new ProcessorBasedRefactoring(processor); + + processor.setTypeName(newInterfaceName); + assertEquals("interface name should be accepted", RefactoringStatus.OK, processor.checkTypeName(newInterfaceName).getSeverity()); + + IMember[] extractableMembers= processor.getExtractableMembers(); + final IMember[] members= new IMember[extractableMembers.length - 1]; + List list= new ArrayList(); + for (IMember iMember : extractableMembers) { + if (!(iMember instanceof IField)) { + list.add(iMember); + } + } + processor.setExtractedMembers(list.toArray(members)); + processor.setReplace(true); + processor.setAnnotations(false); + RefactoringStatus performRefactoring= performRefactoring(ref); + assertEquals("was supposed to pass", null, performRefactoring); + assertEqualLines("incorrect changes in " + className, + getFileContents(getOutputTestFileName(className)), + cu.getSource()); + + ICompilationUnit interfaceCu= pack.getCompilationUnit(newInterfaceName + ".java"); + assertEqualLines("incorrect interface created", + getFileContents(getOutputTestFileName(newInterfaceName)), + interfaceCu.getSource()); + + } + + public void testExtractInterfaceFromClass() throws Exception { + validatePassingTest("A", "B", true, true); + } + + public void testExtractInterfaceFromAbstractClass() throws Exception { + validatePassingTest("A", "B", true, true); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup18.java new file mode 100644 index 0000000000..d22691a8c9 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTestSetup18.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class ExtractMethodTestSetup18 extends Java18Setup { + + private IPackageFragment fDefaultMethodsPackage; + private IPackageFragment fStaticMethodsPackage; + private IPackageFragment fDestinationPackage; + private IPackageFragment fLambdaExpressionPackage; + + public ExtractMethodTestSetup18(Test test) { + super(test); + } + + protected void setUp() throws Exception { + super.setUp(); + + RefactoringCore.getUndoManager().flush(); + + IPackageFragmentRoot root= getDefaultSourceFolder(); + fDefaultMethodsPackage= root.createPackageFragment("defaultMethods18_in", true, null); + fStaticMethodsPackage= root.createPackageFragment("staticMethods18_in", true, null); + fDestinationPackage= root.createPackageFragment("destination18_in", true, null); + fLambdaExpressionPackage= root.createPackageFragment("lambdaExpression18_in", true, null); + } + + public IPackageFragment getDefaultMethodsPackage() { + return fDefaultMethodsPackage; + } + + public IPackageFragment getStaticMethodsPackage() { + return fStaticMethodsPackage; + } + + public IPackageFragment getDestinationPackage() { + return fDestinationPackage; + } + + public IPackageFragment getLambdaExpressionPackage() { + return fLambdaExpressionPackage; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java index 353153df59..b3c03b0fae 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,6 +40,9 @@ import org.eclipse.jdt.ui.tests.refactoring.infra.TextRangeUtil; public class ExtractMethodTests extends AbstractSelectionTestCase { + + private static final boolean BUG_405778= true; //XXX: [1.8][dom ast] method body recovery broken (empty body) + private static ExtractMethodTestSetup fgTestSetup; public ExtractMethodTests(String name) { @@ -86,11 +89,15 @@ protected void performTest(IPackageFragment packageFragment, String id, int mode } protected void performTest(IPackageFragment packageFragment, String id, int mode, String outputFolder, String[] newNames, int[] newOrder, int destination) throws Exception { + performTest(packageFragment, id, mode, outputFolder, newNames, newOrder, destination, Modifier.PROTECTED); + } + + protected void performTest(IPackageFragment packageFragment, String id, int mode, String outputFolder, String[] newNames, int[] newOrder, int destination, int visibility) throws Exception { ICompilationUnit unit= createCU(packageFragment, id); int[] selection= getSelection(); ExtractMethodRefactoring refactoring= new ExtractMethodRefactoring(unit, selection[0], selection[1]); refactoring.setMethodName("extracted"); - refactoring.setVisibility(Modifier.PROTECTED); + refactoring.setVisibility(visibility); TestModelProvider.clearDelta(); RefactoringStatus status= refactoring.checkInitialConditions(new NullProgressMonitor()); switch (mode) { @@ -1746,6 +1753,8 @@ public void test802() throws Exception { } public void test803() throws Exception { + if (BUG_405778) + return; errorTest(); } @@ -1988,6 +1997,22 @@ public void test1058() throws Exception { destinationTest(2); } + public void test1059() throws Exception { + destinationTest(0); + } + + public void test1060() throws Exception { + destinationTest(1); + } + + public void test1061() throws Exception { + destinationTest(1); + } + + public void test1062() throws Exception { + destinationTest(2); + } + //---- Test Generics -------------------------------------------------- public void test1100() throws Exception { diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests18.java new file mode 100644 index 0000000000..9abdd5628e --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests18.java @@ -0,0 +1,241 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.core.dom.Modifier; + +public class ExtractMethodTests18 extends ExtractMethodTests { + private static ExtractMethodTestSetup18 fgTestSetup; + + public ExtractMethodTests18(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new ExtractMethodTestSetup18(new NoSuperTestsSuite(ExtractMethodTests18.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test test) { + fgTestSetup= new ExtractMethodTestSetup18(test); + return fgTestSetup; + } + + protected void defaultMethodsTest(int destination, int visibility) throws Exception { + performTest(fgTestSetup.getDefaultMethodsPackage(), "A", COMPARE_WITH_OUTPUT, "defaultMethods18_out", null, null, destination, visibility); + } + + protected void staticMethodsTest(int destination, int visibility) throws Exception { + performTest(fgTestSetup.getStaticMethodsPackage(), "A", COMPARE_WITH_OUTPUT, "staticMethods18_out", null, null, destination, visibility); + } + + protected void destinationTest(int destination, int visibility) throws Exception { + performTest(fgTestSetup.getDestinationPackage(), "A", COMPARE_WITH_OUTPUT, "destination18_out", null, null, destination, visibility); + } + + protected void lambdaExpressionTest(int destination, int visibility) throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", COMPARE_WITH_OUTPUT, "lambdaExpression18_out", null, null, destination, visibility); + } + + //==================================================================================== + // Testing Default Methods + //==================================================================================== + + public void test1() throws Exception { + defaultMethodsTest(0, Modifier.PUBLIC); + } + + public void test1a() throws Exception { + defaultMethodsTest(0, Modifier.PUBLIC); + } + + public void test2() throws Exception { + defaultMethodsTest(1, Modifier.PROTECTED); + } + + public void test2a() throws Exception { + defaultMethodsTest(1, Modifier.PROTECTED); + } + + public void test3() throws Exception { + defaultMethodsTest(1, Modifier.PUBLIC); + } + + public void test3a() throws Exception { + defaultMethodsTest(1, Modifier.PUBLIC); + } + + public void test4() throws Exception { + defaultMethodsTest(1, Modifier.PUBLIC); + } + + public void test5() throws Exception { + defaultMethodsTest(0, Modifier.PUBLIC); + } + + //==================================================================================== + // Testing Static Methods + //==================================================================================== + + public void test101() throws Exception { + staticMethodsTest(1, Modifier.PUBLIC); + } + + public void test102() throws Exception { + staticMethodsTest(1, Modifier.PUBLIC); + } + + public void test103() throws Exception { + staticMethodsTest(0, Modifier.PUBLIC); + } + + public void test104() throws Exception { + staticMethodsTest(1, Modifier.PUBLIC); + } + + public void test105() throws Exception { + staticMethodsTest(2, Modifier.PUBLIC); + } + + public void test106() throws Exception { + staticMethodsTest(1, Modifier.PUBLIC); + } + + public void test107() throws Exception { + staticMethodsTest(1, Modifier.PUBLIC); + } + + //==================================================================================== + // Testing Destination Types + //==================================================================================== + + public void test201() throws Exception { + destinationTest(0, Modifier.PUBLIC); + } + + public void test202() throws Exception { + destinationTest(0, Modifier.PUBLIC); + } + + public void test203() throws Exception { + destinationTest(1, Modifier.PROTECTED); + } + + public void test204() throws Exception { + destinationTest(1, Modifier.PROTECTED); + } + + //==================================================================================== + // Testing Lambda Expressions + //==================================================================================== + + public void test301() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test302() throws Exception { + lambdaExpressionTest(1, Modifier.PRIVATE); + } + + public void test303() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test304() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test305() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test306() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test307() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test308() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test309() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test310() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test311() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test312() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", INVALID_SELECTION, null); + } + + public void test313() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test314() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test315() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } + + public void test316() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test317() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test318() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", INVALID_SELECTION, null); + } + + public void test319() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test320() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", INVALID_SELECTION, null); + } + + public void test321() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", INVALID_SELECTION, null); + } + + public void test322() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", INVALID_SELECTION, null); + } + + public void test323() throws Exception { + lambdaExpressionTest(0, Modifier.PUBLIC); + } + + public void test324() throws Exception { + performTest(fgTestSetup.getLambdaExpressionPackage(), "A", VALID_SELECTION, null); + } + + public void test325() throws Exception { + lambdaExpressionTest(0, Modifier.PRIVATE); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java index 25c7670e4c..6b7fcd4019 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -322,6 +322,16 @@ public void test39() throws Exception { // test for https://bugs.eclipse.org/bug helper1("p.A", 7, 26, 7, 27, true, true); } + public void test40() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=431158 + // Select simple name to inline + helper1("p.A", 7, 26, 7, 27, true, true); + } + + public void test41() throws Exception { // test for https://bugs.eclipse.org/bugs/show_bug.cgi?id=431158 + // Select qualified name to inline + helper1("p.A", 8, 15, 8, 21, true, true); + } + // -- testing failing preconditions public void testFail0() throws Exception { diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java18Setup.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java18Setup.java new file mode 100644 index 0000000000..c95b62a451 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/Java18Setup.java @@ -0,0 +1,35 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +public class Java18Setup extends RefactoringTestSetup { + + public Java18Setup(Test test) { + super(test); + } + + /* + * @see org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSetup#addRTJar(org.eclipse.jdt.core.IJavaProject) + */ + @Override + protected IPackageFragmentRoot addRTJar(IJavaProject project) throws CoreException { + return JavaProjectHelper.addRTJar18(project); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java index 9a72c81f10..e90a1f2948 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -139,7 +139,7 @@ private void fieldHelperDelegate_passing(String[] fieldNames) throws Exception { fieldMethodTypeHelper_passing(fieldNames, new String[0], new String[0][0], new String[0], true); } - private void methodHelper_passing(String[] methodNames, String[][] signatures) throws Exception { + protected void methodHelper_passing(String[] methodNames, String[][] signatures) throws Exception { fieldMethodTypeHelper_passing(new String[0], methodNames, signatures, new String[0], false); } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests18.java new file mode 100644 index 0000000000..b0e274a73f --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests18.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * Copyright (c) 2000, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +public class MoveMembersTests18 extends MoveMembersTests { + + private static final Class clazz= MoveMembersTests18.class; + + public MoveMembersTests18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new NoSuperTestsSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java18Setup(someTest); + } + + public void test18_1() throws Exception { + // move private static method from class to interface, update visibility + methodHelper_passing(new String[] { "m" }, new String[][] { new String[0] }); + } + + public void test18_2() throws Exception { + // move static method from interface to another interface + methodHelper_passing(new String[] { "m" }, new String[][] { new String[0] }); + } + + public void test18_3() throws Exception { + // move static method from interface to class, add 'public' + methodHelper_passing(new String[] { "m" }, new String[][] { new String[0] }); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java index 15d69ecd38..016196127c 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -105,7 +105,7 @@ protected final ICompilationUnit createCUfromEnablementTestFile(IPackageFragment return createCU(pack, getSimpleEnablementTestFileName(), getFileContents(getEnablementTestFileName())); } - private void passHelper(int startLine, int startColumn, int endLine, int endColumn, + protected void passHelper(int startLine, int startColumn, int endLine, int endColumn, String newName, boolean declareStatic, boolean declareFinal, @@ -137,7 +137,7 @@ private void passHelper(int startLine, int startColumn, int endLine, int endColu assertEqualLines("incorrect changes", getFileContents(getTestFileName(true, false)), newcu.getSource()); } - private void failHelper(int startLine, int startColumn, int endLine, int endColumn, + protected void failHelper(int startLine, int startColumn, int endLine, int endColumn, String newName, boolean declareStatic, boolean declareFinal, diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests18.java new file mode 100644 index 0000000000..3f82561880 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests18.java @@ -0,0 +1,44 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.ltk.core.refactoring.RefactoringStatus; + +import org.eclipse.jdt.core.dom.Modifier; + +import org.eclipse.jdt.internal.corext.refactoring.code.PromoteTempToFieldRefactoring; + +public class PromoteTempToFieldTests18 extends PromoteTempToFieldTests { + private static final Class clazz= PromoteTempToFieldTests18.class; + + public PromoteTempToFieldTests18(String name) { + super(name); + } + + public static Test setUpTest(Test test) { + return new Java18Setup(test); + } + + public static Test suite() { + return setUpTest(new NoSuperTestsSuite(clazz)); + } + + public void testFailInterfaceMethods1() throws Exception { + failHelper(6, 13, 6, 14, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + + public void testFailInterfaceMethods2() throws Exception { + failHelper(6, 13, 6, 14, "i", false, false, PromoteTempToFieldRefactoring.INITIALIZE_IN_METHOD, Modifier.PRIVATE, RefactoringStatus.FATAL); + } + +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java index 4cd0e291b9..2bb73fcd00 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -77,8 +77,8 @@ public abstract class RefactoringTest extends TestCase { */ private static final boolean DESCRIPTOR_TEST= false; - private IPackageFragmentRoot fRoot; - private IPackageFragment fPackageP; + protected IPackageFragmentRoot fRoot; + protected IPackageFragment fPackageP; public boolean fIsVerbose= false; public boolean fIsPreDeltaTest= false; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java index 044b1c7f46..5e5c7d296d 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -35,6 +35,9 @@ public static Test suite() { suite.addTest(RenameTypeParameterTests.suite()); suite.addTest(RenameNonPrivateFieldTests.suite()); suite.addTest(RenameJavaProjectTests.suite()); + suite.addTest(RenameTests18.suite()); + + //XXX: NOT part of AllRefactoringTests. Also add suites there! return suite; } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests18.java new file mode 100644 index 0000000000..0737dd4808 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTests18.java @@ -0,0 +1,188 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.ArrayList; +import java.util.Hashtable; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.NullProgressMonitor; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; +import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.ltk.core.refactoring.participants.RenameArguments; +import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.ISourceRange; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.SourceRange; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; +import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; + +import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; + +public class RenameTests18 extends RefactoringTest { + + private static final Class clazz= RenameTests18.class; + + private static final String REFACTORING_PATH= "RenameTests18/"; + + + public RenameTests18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new TestSuite(clazz)); + } + + public static Test setUpTest(Test someTest) { + return new Java18Setup(someTest); + } + + protected String getRefactoringPath() { + return REFACTORING_PATH; + } + + protected void setUp() throws Exception { + super.setUp(); + Hashtable options= JavaCore.getOptions(); + JavaCore.setOptions(options); + fIsPreDeltaTest= true; + } + + protected void tearDown() throws Exception { + super.tearDown(); + Hashtable options= JavaCore.getOptions(); + JavaCore.setOptions(options); + } + + private ISourceRange getSelection(ICompilationUnit cu) throws Exception { + String source= cu.getSource(); + //Warning: this *includes* the SQUARE_BRACKET_OPEN! + int offset= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_OPEN); + int end= source.indexOf(AbstractSelectionTestCase.SQUARE_BRACKET_CLOSE); + return new SourceRange(offset + AbstractSelectionTestCase.SQUARE_BRACKET_OPEN.length(), end - offset); + } + + private void renameLocalVariable(String newFieldName, boolean updateReferences) throws Exception { + ParticipantTesting.reset(); + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + + ISourceRange selection= getSelection(cu); + IJavaElement[] elements= cu.codeSelect(selection.getOffset(), selection.getLength()); + assertEquals(1, elements.length); + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_LOCAL_VARIABLE); + descriptor.setJavaElement(elements[0]); + descriptor.setNewName(newFieldName); + descriptor.setUpdateReferences(updateReferences); + descriptor.setUpdateTextualOccurrences(false); + + RenameRefactoring refactoring= (RenameRefactoring) createRefactoring(descriptor); + List list= new ArrayList(); + list.add(elements[0]); + List args= new ArrayList(); + args.add(new RenameArguments(newFieldName, updateReferences)); + String[] renameHandles= ParticipantTesting.createHandles(list.toArray()); + + RefactoringStatus result= performRefactoring(refactoring); + assertEquals("was supposed to pass", null, result); + assertEqualLines("invalid renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + ParticipantTesting.testRename( + renameHandles, + (RenameArguments[]) args.toArray(new RenameArguments[args.size()])); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + public void testLambda0() throws Exception { + renameLocalVariable("renamedF", true); + } + + public void testLambda1() throws Exception { + renameLocalVariable("renamedP", true); + } + + public void testLambda2() throws Exception { + renameLocalVariable("renamedIi", true); + } + + public void testLambda3() throws Exception { + renameLocalVariable("x_renamed", true); + } + + + private void renameMethodInInterface(String methodName, String newMethodName, String[] signatures, boolean shouldPass, boolean updateReferences, boolean createDelegate) throws Exception{ + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IType interfaceI= getType(cu, "I"); + IMethod method= interfaceI.getMethod(methodName, signatures); + + RenameJavaElementDescriptor descriptor= RefactoringSignatureDescriptorFactory.createRenameJavaElementDescriptor(IJavaRefactorings.RENAME_METHOD); + descriptor.setJavaElement(method); + descriptor.setUpdateReferences(updateReferences); + descriptor.setNewName(newMethodName); + descriptor.setKeepOriginal(createDelegate); + descriptor.setDeprecateDelegate(true); + + assertEquals("was supposed to pass", null, performRefactoring(descriptor)); + if (!shouldPass){ + assertTrue("incorrect renaming because of a java model bug", ! getFileContents(getOutputTestFileName("A")).equals(cu.getSource())); + return; + } + assertEqualLines("incorrect renaming", getFileContents(getOutputTestFileName("A")), cu.getSource()); + + assertTrue("anythingToUndo", RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("! anythingToRedo", !RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to undo", 1, Refactoring.getUndoManager().getRefactoringLog().size()); + + RefactoringCore.getUndoManager().performUndo(null, new NullProgressMonitor()); + assertEqualLines("invalid undo", getFileContents(getInputTestFileName("A")), cu.getSource()); + + assertTrue("! anythingToUndo", !RefactoringCore.getUndoManager().anythingToUndo()); + assertTrue("anythingToRedo", RefactoringCore.getUndoManager().anythingToRedo()); + //assertEquals("1 to redo", 1, Refactoring.getUndoManager().getRedoStack().size()); + + RefactoringCore.getUndoManager().performRedo(null, new NullProgressMonitor()); + assertEqualLines("invalid redo", getFileContents(getOutputTestFileName("A")), cu.getSource()); + } + + private void renameMethodInInterface() throws Exception{ + renameMethodInInterface("m", "k", new String[0], true, true, false); + } + + // method with a lambda method as reference + public void testMethod0() throws Exception{ + renameMethodInInterface(); + } + + // method with method references as reference + public void testMethod1() throws Exception{ + renameMethodInInterface(); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java index 80e6639a13..0de7f3c566 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java @@ -267,6 +267,10 @@ public void testGenericReadWrite() throws Exception { objectTest("field"); } + public void testArrayAnnotations() throws Exception { + objectTest("field"); + } + //===================================================================================== // static import tests //===================================================================================== diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup18.java new file mode 100644 index 0000000000..9519076300 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTestSetup18.java @@ -0,0 +1,84 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import java.util.Hashtable; + +import junit.extensions.TestSetup; +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.ltk.core.refactoring.RefactoringCore; + +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.util.CoreUtility; + + +public class SurroundWithTestSetup18 extends TestSetup { + + private IJavaProject fJavaProject; + + private IPackageFragmentRoot fRoot; + + private static final String CONTAINER= "src"; + + private IPackageFragment fTryCatchPackage; + + public SurroundWithTestSetup18(Test test) { + super(test); + } + + public IPackageFragmentRoot getRoot() { + return fRoot; + } + + protected void setUp() throws Exception { + super.setUp(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "0"); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + JavaCore.setOptions(options); + TestOptions.initializeCodeGenerationOptions(); + JavaPlugin.getDefault().getCodeTemplateStore().load(); + + fJavaProject= JavaProjectHelper.createJavaProject("TestProject18", "bin"); + JavaProjectHelper.addRTJar18(fJavaProject); + fRoot= JavaProjectHelper.addSourceContainer(fJavaProject, CONTAINER); + + RefactoringCore.getUndoManager().flush(); + CoreUtility.setAutoBuilding(false); + + fTryCatchPackage= getRoot().createPackageFragment("trycatch18_in", true, null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CATCHBLOCK_ID, "", null); + } + + protected void tearDown() throws Exception { + super.tearDown(); + JavaProjectHelper.delete(fJavaProject); + } + + public IPackageFragment getTryCatchPackage() { + return fTryCatchPackage; + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests18.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests18.java new file mode 100644 index 0000000000..4173818cfc --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests18.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.refactoring; + +import junit.framework.Test; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IPackageFragmentRoot; + +import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; + +public class SurroundWithTests18 extends SurroundWithTests { + + private static SurroundWithTestSetup18 fgTestSetup; + + public SurroundWithTests18(String name) { + super(name); + } + + public static Test suite() { + fgTestSetup= new SurroundWithTestSetup18(new NoSuperTestsSuite(SurroundWithTests18.class)); + return fgTestSetup; + } + + public static Test setUpTest(Test someTest) { + fgTestSetup= new SurroundWithTestSetup18(someTest); + return fgTestSetup; + } + + protected IPackageFragmentRoot getRoot() { + return fgTestSetup.getRoot(); + } + + @Override + protected SurroundWithTryCatchRefactoring createRefactoring(ICompilationUnit unit) { + return SurroundWithTryCatchRefactoring.create(unit, getTextSelection(), true); + } + + protected void tryCatchInvalidTest() throws Exception { + performTest(fgTestSetup.getTryCatchPackage(), getName(), "trycatch18_out", INVALID_SELECTION); + } + + protected void tryCatchTest() throws Exception { + performTest(fgTestSetup.getTryCatchPackage(), getName(), "trycatch18_out", COMPARE_WITH_OUTPUT); + } + + public void testSimple1() throws Exception { + tryCatchTest(); + } +} diff --git a/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ignoreFiles.txt b/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ignoreFiles.txt index ce1806e64a..91d67398a7 100644 --- a/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ignoreFiles.txt +++ b/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ignoreFiles.txt @@ -45,6 +45,7 @@ org.eclipse.tomcat/conf/* org.eclipse.ui/plugin.xml org.eclipse.platform.source/* org.apache.ant/* +org.apache.commons.codec/* org.eclipse.ant.core/* org.eclipse.ant.tests.core/* org.eclipse.ant.tests.ui/* @@ -89,6 +90,7 @@ org.eclipse.help/* org.eclipse.help.appserver/* org.eclipse.help.base/* org.eclipse.help.ui/* +org.eclipse.jdt.core.tests/* org.eclipse.jdt.core.tests.model/workspace/* org.eclipse.jdt.debug/* org.eclipse.jdt.debug.ui/* @@ -182,3 +184,6 @@ platform-text/* tk.eclipse.plugin.htmleditor/* bug/ zz*/* +config/* +org.eclipse.osgi.tests/* +org.eclipse.e4.sdk/* diff --git a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java index 1a7dc739b7..d41fe2ca94 100644 --- a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java +++ b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java @@ -88,6 +88,7 @@ public class JavaProjectHelper { public static final IPath RT_STUBS_15= new Path("testresources/rtstubs15.jar"); public static final IPath RT_STUBS_16= new Path("testresources/rtstubs16.jar"); public static final IPath RT_STUBS_17= new Path("testresources/rtstubs17.jar"); + public static final IPath RT_STUBS_18= new Path("testresources/rtstubs18.jar"); public static final IPath JUNIT_SRC_381= new Path("testresources/junit381-noUI-src.zip"); public static final String JUNIT_SRC_ENCODING= "ISO-8859-1"; @@ -188,6 +189,18 @@ public static IJavaProject createJavaProjectWithJUnitSource(String projectName, return project; } + /** + * Sets the compiler options to 1.8 for the given project. + * + * @param project the java project + * @since 3.10 + */ + public static void set18CompilerOptions(IJavaProject project) { + Map options= project.getOptions(false); + set18CompilerOptions(options); + project.setOptions(options); + } + /** * Sets the compiler options to 1.7 for the given project. * @param project the java project @@ -228,6 +241,16 @@ public static void set14CompilerOptions(IJavaProject project) { project.setOptions(options); } + /** + * Sets the compiler options to 1.8 + * + * @param options the compiler options to configure + * @since 3.10 + */ + public static void set18CompilerOptions(Map options) { + JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options); + } + /** * Sets the compiler options to 1.7 * @param options The compiler options to configure @@ -690,6 +713,12 @@ public static IPackageFragmentRoot addRTJar17(IJavaProject jproject) throws Core return addLibrary(jproject, rtJarPath[0], rtJarPath[1], rtJarPath[2]); } + public static IPackageFragmentRoot addRTJar18(IJavaProject jproject) throws CoreException { + IPath[] rtJarPath= findRtJar(RT_STUBS_18); + set18CompilerOptions(jproject); + return addLibrary(jproject, rtJarPath[0], rtJarPath[1], rtJarPath[2]); + } + /** * Adds a variable entry with source attachment to a IJavaProject. * Can return null if variable can not be resolved. diff --git a/org.eclipse.jdt.ui.tests/testresources/JDTFlagsTest18.zip b/org.eclipse.jdt.ui.tests/testresources/JDTFlagsTest18.zip new file mode 100644 index 0000000000..29a7d72df2 Binary files /dev/null and b/org.eclipse.jdt.ui.tests/testresources/JDTFlagsTest18.zip differ diff --git a/org.eclipse.jdt.ui.tests/testresources/rtstubs18.jar b/org.eclipse.jdt.ui.tests/testresources/rtstubs18.jar new file mode 100644 index 0000000000..225d910051 Binary files /dev/null and b/org.eclipse.jdt.ui.tests/testresources/rtstubs18.jar differ diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AddImportTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AddImportTest.java index e66a0616ca..996bf1bbeb 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AddImportTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AddImportTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -1203,7 +1203,7 @@ public void testAddImportActionBug_409594_test6() throws Exception { assertEqualString(cuB.getSource(), expected); } - public void testAddImports_bug107206() throws Exception { + public void testAddImportAction_bug107206() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); @@ -1297,6 +1297,321 @@ public void testAddImportActionStaticWith14() throws Exception { assertEqualString(cu.getSource(), buf.toString()); } + public void testAddImportActionNestedType1() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.lang.Thread.State s;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Thread"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Thread.State s;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionNestedType2() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.lang.Thread.State s;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("State"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.lang.Thread.State;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" State s;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionParameterizedType1() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.util.Map m;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Map"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.Map;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Map m;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionParameterizedType2() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.util.Map.Entry e;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Entry"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.Map.Entry;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Entry e;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionParameterizedType3() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.util.Map.Entry e;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Map"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.Map;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Map.Entry e;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionParameterizedType4() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.util.Map.Entry e;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Entry"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.Map.Entry;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Entry e;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionParameterizedType5() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack2= sourceFolder.createPackageFragment("pack2", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack2;\n"); + buf.append("\n"); + buf.append("public class Outer {\n"); + buf.append(" public class Middle {\n"); + buf.append(" public class Inner {\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack2.createCompilationUnit("Outer.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" pack2.Outer.Middle.Inner i;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Middle"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import pack2.Outer.Middle;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" Middle.Inner i;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + // Don't touch nested type if outer is parameterized. + public void testAddImportActionParameterizedType6() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack2= sourceFolder.createPackageFragment("pack2", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack2;\n"); + buf.append("\n"); + buf.append("public class Outer {\n"); + buf.append(" public class Middle {\n"); + buf.append(" public class Inner {\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack2.createCompilationUnit("Outer.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" pack2.Outer.Middle.Inner i;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Inner"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" pack2.Outer.Middle.Inner i;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testAddImportActionAnnotatedType1() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.text.@A Format.@A Field f;\n"); + buf.append("}\n"); + buf.append("@Target(ElementType.TYPE_USE) @interface A {}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Format"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("import java.text.Format;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" @A Format.@A Field f;\n"); + buf.append("}\n"); + buf.append("@Target(ElementType.TYPE_USE) @interface A {}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + // Don't touch nested type if outer is annotated. + public void testAddImportActionAnnotatedType2() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.text.@A Format.@A Field f;\n"); + buf.append("}\n"); + buf.append("@Target(ElementType.TYPE_USE) @interface A {}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int selOffset= buf.indexOf("Field"); + + AddImportsOperation op= new AddImportsOperation(cu, selOffset, 0, null, true); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class C {\n"); + buf.append(" java.text.@A Format.@A Field f;\n"); + buf.append("}\n"); + buf.append("@Target(ElementType.TYPE_USE) @interface A {}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + public void testAddImportContextSensitive01() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java index c12928eedb..99ec2c5124 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -44,11 +44,13 @@ public static Test suite() { suite.addTest(CodeFormatterTest.suite()); suite.addTest(HierarchicalASTVisitorTest.suite()); suite.addTest(ImportOrganizeTest.suite()); + suite.addTest(ImportOrganizeTest18.suite()); suite.addTest(JavaElementLabelsTest.suite()); - suite.addTest(JavaElementLabelsTest17.suite()); + suite.addTest(JavaElementLabelsTest18.suite()); suite.addTest(JavaElementPropertyTesterTest.suite()); suite.addTest(JavaModelUtilTest.suite()); suite.addTest(MethodOverrideTest.suite()); + suite.addTest(MethodOverrideTest18.suite()); suite.addTest(NameProposerTest.suite()); suite.addTest(OverrideTest.suite()); suite.addTest(PartialASTTest.suite()); @@ -61,6 +63,7 @@ public static Test suite() { suite.addTest(IndentManipulationTest.suite()); suite.addTest(SelectionHistoryTest.suite()); suite.addTest(ASTProviderTest.suite()); + suite.addTest(JDTFlagsTest18.suite()); return new ProjectTestSetup(suite); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/HierarchicalASTVisitorTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/HierarchicalASTVisitorTest.java index f743669e1e..b48ee2fd58 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/HierarchicalASTVisitorTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/HierarchicalASTVisitorTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,10 +25,12 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; +import org.eclipse.jdt.core.dom.AnnotatableType; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.Comment; import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.MethodReference; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.Type; @@ -36,6 +38,7 @@ import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; +@SuppressWarnings("javadoc") public class HierarchicalASTVisitorTest extends TestCase { private static class TestHierarchicalASTVisitor extends HierarchicalASTVisitor { @@ -93,6 +96,20 @@ public void superEndVisit(Expression node) { super.visit(node); } + public boolean visit(AnnotatableType node) { + registerCall(AnnotatableType.class); + return false; + } + public void superVisit(AnnotatableType node) { + super.visit(node); + } + public void endVisit(AnnotatableType node) { + registerCall(AnnotatableType.class); + } + public void superEndVisit(AnnotatableType node) { + super.visit(node); + } + public boolean visit(Annotation node) { registerCall(Annotation.class); return false; @@ -107,6 +124,20 @@ public void superEndVisit(Annotation node) { super.visit(node); } + public boolean visit(MethodReference node) { + registerCall(MethodReference.class); + return false; + } + public void superVisit(MethodReference node) { + super.visit(node); + } + public void endVisit(MethodReference node) { + registerCall(MethodReference.class); + } + public void superEndVisit(MethodReference node) { + super.visit(node); + } + public boolean visit(Name node) { registerCall(Name.class); return false; @@ -323,6 +354,10 @@ private void callSuperVisitToAvoidUnusedMethodsWarning() { superEndVisit((Expression) null); superVisit((Annotation) null); superEndVisit((Annotation) null); + superVisit((AnnotatableType) null); + superEndVisit((AnnotatableType) null); + superVisit((MethodReference) null); + superEndVisit((MethodReference) null); superVisit((Name) null); superEndVisit((Name) null); superVisit((BodyDeclaration) null); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java index ac1f98d388..09d5daeb89 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java @@ -76,7 +76,7 @@ protected void tearDown() throws Exception { JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); } - private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) { + protected IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) { return new IChooseImportQuery() { public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) { assertTrue(name + "-query-nchoices1", choices.length == openChoices.length); @@ -3209,12 +3209,12 @@ public void testJavadocImports_bug319860() throws Exception { } - private OrganizeImportsOperation createOperation(ICompilationUnit cu, String[] order, int threshold, boolean ignoreLowerCaseNames, boolean save, boolean allowSyntaxErrors, IChooseImportQuery chooseImportQuery) { + protected OrganizeImportsOperation createOperation(ICompilationUnit cu, String[] order, int threshold, boolean ignoreLowerCaseNames, boolean save, boolean allowSyntaxErrors, IChooseImportQuery chooseImportQuery) { setOrganizeImportSettings(order, threshold, threshold, cu.getJavaProject()); return new OrganizeImportsOperation(cu, null, ignoreLowerCaseNames, save, allowSyntaxErrors, chooseImportQuery); } - private void setOrganizeImportSettings(String[] order, int threshold, int staticThreshold, IJavaProject project) { + protected void setOrganizeImportSettings(String[] order, int threshold, int staticThreshold, IJavaProject project) { IEclipsePreferences scope= new ProjectScope(project.getProject()).getNode(JavaUI.ID_PLUGIN); if (order == null) { scope.remove(PreferenceConstants.ORGIMPORTS_IMPORTORDER); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest18.java new file mode 100644 index 0000000000..f9720da6ab --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest18.java @@ -0,0 +1,383 @@ +/******************************************************************************* + * Copyright (c) 2000, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.core; + +import java.util.Hashtable; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; +import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; + + +public class ImportOrganizeTest18 extends ImportOrganizeTest { + + private static final Class THIS= ImportOrganizeTest18.class; + + private IJavaProject fJProject1; + + public ImportOrganizeTest18(String name) { + super(name); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + public static Test suite() { + return setUpTest(new NoSuperTestsSuite(THIS)); + } + + + protected void setUp() throws Exception { + fJProject1= Java18ProjectTestSetup.getProject(); + + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, String.valueOf(99)); + JavaCore.setOptions(options); + } + + + protected void tearDown() throws Exception { + setOrganizeImportSettings(null, 99, 99, fJProject1); + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public void testTypeUseAnnotationImport1() throws Exception { // PrimitiveType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" @TypeUse int i;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" @TypeUse int i;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testTypeUseAnnotationImport2() throws Exception { // SimpleType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse String> list1;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.ArrayList;\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse String> list1;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testTypeUseAnnotationImport3() throws Exception { // QualifiedType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse A.B> list2;\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class A {\n"); + buf.append(" public class B {\n"); + buf.append(" \n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.ArrayList;\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse A.B> list2;\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class A {\n"); + buf.append(" public class B {\n"); + buf.append(" \n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testTypeUseAnnotationImport4() throws Exception { // PackageQualifiedType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList list;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.ArrayList;\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList list;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testTypeUseAnnotationImport5() throws Exception { // WildcardType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse ?> list3;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import java.util.ArrayList;\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" ArrayList<@TypeUse ?> list3;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testTypeUseAnnotationImport6() throws Exception { // ArrayType + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("pack0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package pack0;\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("public @interface TypeUse {\n"); + buf.append("}\n"); + pack0.createCompilationUnit("TypeUse.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("public class C{\n"); + buf.append(" int[] arr = new int @TypeUse [5];\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package pack1;\n"); + buf.append("\n"); + buf.append("import pack0.TypeUse;\n"); + buf.append("\n"); + buf.append("public class C{\n"); + buf.append(" int[] arr = new int @TypeUse [5];\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testStaticMethodReferenceImports_bug424172() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("p", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package p;\n"); + buf.append("\n"); + buf.append("import java.util.function.IntPredicate;\n"); + buf.append("\n"); + buf.append("class UnusedStaticImport {\n"); + buf.append(" boolean value = match(Character::isUpperCase, 'A');\n"); + buf.append("\n"); + buf.append(" public static boolean match(IntPredicate matcher, int codePoint) {\n"); + buf.append(" return matcher.test(codePoint);\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack0.createCompilationUnit("UnusedStaticImport.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("StaticMethodReferenceImports_bug424172", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package p;\n"); + buf.append("\n"); + buf.append("import java.util.function.IntPredicate;\n"); + buf.append("\n"); + buf.append("class UnusedStaticImport {\n"); + buf.append(" boolean value = match(Character::isUpperCase, 'A');\n"); + buf.append("\n"); + buf.append(" public static boolean match(IntPredicate matcher, int codePoint) {\n"); + buf.append(" return matcher.test(codePoint);\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + + public void testMethodReferenceImports_bug424227() throws Exception { + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack0= sourceFolder.createPackageFragment("p0", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package p0;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("public interface FI {\n"); + buf.append(" FI foo();\n"); + buf.append("}\n"); + pack0.createCompilationUnit("FI.java", buf.toString(), false, null); + + buf= new StringBuffer(); + buf.append("package p0;\n"); + buf.append("public class X {\n"); + buf.append(" public static FI staticMethodX() {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack0.createCompilationUnit("X.java", buf.toString(), false, null); + + IPackageFragment pack1= sourceFolder.createPackageFragment("p1", false, null); + buf= new StringBuffer(); + buf.append("package p1;\n"); + buf.append("\n"); + buf.append("public class C1 {\n"); + buf.append(" FI fi = X::staticMethodX;\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C1.java", buf.toString(), false, null); + + String[] order= new String[] {}; + IChooseImportQuery query= createQuery("MethodReferenceImports_bug424227", new String[] {}, new int[] {}); + + OrganizeImportsOperation op= createOperation(cu, order, 99, false, true, true, query); + op.run(null); + + buf= new StringBuffer(); + buf.append("package p1;\n"); + buf.append("\n"); + buf.append("import p0.FI;\n"); + buf.append("import p0.X;\n"); + buf.append("\n"); + buf.append("public class C1 {\n"); + buf.append(" FI fi = X::staticMethodX;\n"); + buf.append("}\n"); + assertEqualString(cu.getSource(), buf.toString()); + } + +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JDTFlagsTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JDTFlagsTest18.java new file mode 100644 index 0000000000..be57de0e6b --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JDTFlagsTest18.java @@ -0,0 +1,476 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.core; + +import java.io.File; +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +import org.junit.Assert; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.JavaTestPlugin; + +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; + +import org.eclipse.core.resources.IResource; + +import org.eclipse.jdt.core.IClassFile; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IField; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IMember; +import org.eclipse.jdt.core.IMethod; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.EnumConstantDeclaration; +import org.eclipse.jdt.core.dom.EnumDeclaration; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; + +import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; +import org.eclipse.jdt.internal.corext.util.JdtFlags; + +import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; + +public class JDTFlagsTest18 extends TestCase { + + private static final Class THIS= JDTFlagsTest18.class; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + public JDTFlagsTest18(String name) { + super(name); + } + + public static Test suite() { + return new Java18ProjectTestSetup(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + fJProject1= Java18ProjectTestSetup.getProject(); + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + } + + @Override + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + protected CompilationUnit getCompilationUnitNode(String source) { + ASTParser parser = ASTParser.newParser(AST.JLS8); + parser.setSource(source.toCharArray()); + Hashtable options= JavaCore.getOptions(); + JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options); + parser.setCompilerOptions(options); + CompilationUnit cuNode = (CompilationUnit) parser.createAST(null); + return cuNode; + } + + public void testIsStaticInSrcFile() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("public interface Snippet {\n"); + buf.append(" public static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("public static"); + IMethod method= (IMethod)cUnit.getElementAt(offset); + Assert.assertTrue(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isAbstract(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + + ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(fJProject1); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertTrue(JdtFlags.isStatic(binding)); + Assert.assertFalse(JdtFlags.isAbstract(binding)); + Assert.assertFalse(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + + MethodDeclaration methodNode= ASTNodeSearchUtil.getMethodDeclarationNode(method, getCompilationUnitNode(buf.toString())); + Assert.assertTrue(JdtFlags.isStatic(methodNode)); + } + + public void testNestedEnumInEnum() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("\n"); + buf.append("enum Snippet {\n"); + buf.append(" A;\n"); + buf.append(" enum E {\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("enum E"); + IJavaElement elem= cUnit.getElementAt(offset); + EnumDeclaration enumNode= ASTNodeSearchUtil.getEnumDeclarationNode((IType)elem, getCompilationUnitNode(buf.toString())); + Assert.assertTrue(JdtFlags.isStatic(enumNode)); + Assert.assertTrue(JdtFlags.isStatic((IType)elem)); + } + + public void testNestedEnumInInterface() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface Snippet {\n"); + buf.append(" enum CoffeeSize {\n"); + buf.append(" BIG, HUGE{\n"); + buf.append(" public String getLidCode() {\n"); + buf.append(" return \"B\";\n"); + buf.append(" }\n"); + buf.append(" }, OVERWHELMING {\n"); + buf.append("\n"); + buf.append(" public String getLidCode() {\n"); + buf.append(" return \"A\";\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" public String getLidCode() {\n"); + buf.append(" return \"B\";\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append(" enum Colors{\n"); + buf.append(" RED, BLUE, GREEN;\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("enum CoffeeSize"); + IJavaElement elem= cUnit.getElementAt(offset); + IMember type= (IMember)elem; + Assert.assertTrue(JdtFlags.isStatic(type)); + Assert.assertFalse(JdtFlags.isAbstract(type)); + + EnumDeclaration enumNode= ASTNodeSearchUtil.getEnumDeclarationNode((IType)elem, getCompilationUnitNode(buf.toString())); + Assert.assertTrue(JdtFlags.isStatic(enumNode)); + + // testcase for isF an enum + Assert.assertFalse(JdtFlags.isFinal(type)); + offset= cUnit.getSource().indexOf("enum Colors"); + type= (IMember)cUnit.getElementAt(offset); + Assert.assertTrue(JdtFlags.isFinal(type)); + } + + public void testNestedEnumInClass() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Snippet { \n"); + buf.append(" enum Color {\n"); + buf.append(" RED,\n"); + buf.append(" BLUE;\n"); + buf.append(" Runnable r = new Runnable() {\n"); + buf.append(" \n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" // TODO Auto-generated method stub\n"); + buf.append(" \n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + // testing nested enum + int offset= cUnit.getSource().indexOf("enum"); + CompilationUnit cuNode= getCompilationUnitNode(buf.toString()); + IJavaElement javaElem= cUnit.getElementAt(offset); + IMember element= (IMember)javaElem; + Assert.assertTrue(JdtFlags.isStatic(element)); + Assert.assertFalse(JdtFlags.isAbstract(element)); + + EnumDeclaration enumNode= ASTNodeSearchUtil.getEnumDeclarationNode((IType)javaElem, cuNode); + Assert.assertTrue(JdtFlags.isStatic(enumNode)); + + // testing enum constant + offset= cUnit.getSource().indexOf("RED"); + javaElem= cUnit.getElementAt(offset); + element= (IMember)javaElem; + Assert.assertTrue(JdtFlags.isStatic(element)); + Assert.assertFalse(JdtFlags.isAbstract(element)); + + EnumConstantDeclaration enumConst= ASTNodeSearchUtil.getEnumConstantDeclaration((IField)javaElem, cuNode); + Assert.assertTrue(JdtFlags.isStatic(enumConst)); + + // testing enum constant + offset= cUnit.getSource().indexOf("Runnable r"); + element= (IMember)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isFinal(element)); + + } + + public void testNestedEnumIsFinal() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class Snippet { \n"); + buf.append(" enum Color {\n"); + buf.append(" BLUE{};\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("enum Color"); + IMember element= (IMember)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isFinal(element)); + } + + public void testIsStaticInBinaryFile() throws Exception { + File clsJarPath= JavaTestPlugin.getDefault().getFileInPlugin(new Path("/testresources/JDTFlagsTest18.zip")); + assertTrue("lib not found", clsJarPath != null && clsJarPath.exists());//$NON-NLS-1$ + IPackageFragmentRoot jarRoot= JavaProjectHelper.addLibraryWithImport(fJProject1, new Path(clsJarPath.getAbsolutePath()), null, null); + fJProject1.open(null); + fJProject1.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); + Assert.assertTrue(jarRoot.exists()); + Assert.assertTrue(jarRoot.isArchive()); + IPackageFragment pf= jarRoot.getPackageFragment("pack1");//$NON-NLS-1$ + Assert.assertTrue(pf.exists()); + IClassFile classFile2= pf.getClassFile("Snippet.class"); + IMethod[] clsFile= classFile2.getType().getMethods(); + IMethod method= clsFile[0]; + Assert.assertTrue(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isAbstract(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + } + + public void testIsDefaultInInterface() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface Snippet {\n"); + buf.append(" public default String defaultMethod(){\n"); + buf.append(" return \"default\";\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("public default"); + IMethod method= (IMethod)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isAbstract(method)); + Assert.assertTrue(JdtFlags.isDefaultMethod(method)); + + ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(pack1.getJavaProject()); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertFalse(JdtFlags.isStatic(binding)); + Assert.assertFalse(JdtFlags.isAbstract(binding)); + Assert.assertTrue(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + } + + public void testIsDefaultInBinaryFile() throws Exception { + File clsJarPath= JavaTestPlugin.getDefault().getFileInPlugin(new Path("/testresources/JDTFlagsTest18.zip")); + assertTrue("lib not found", clsJarPath != null && clsJarPath.exists());//$NON-NLS-1$ + IPackageFragmentRoot jarRoot= JavaProjectHelper.addLibraryWithImport(fJProject1, new Path(clsJarPath.getAbsolutePath()), null, null); + fJProject1.open(null); + fJProject1.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); + Assert.assertTrue(jarRoot.exists()); + Assert.assertTrue(jarRoot.isArchive()); + IPackageFragment pf= jarRoot.getPackageFragment("pack1");//$NON-NLS-1$ + Assert.assertTrue(pf.exists()); + IClassFile classFile2= pf.getClassFile("Snippet.class"); + IMethod method= classFile2.getType().getMethod("defaultMethod", null); + Assert.assertTrue(JdtFlags.isDefaultMethod(method)); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isAbstract(method)); + } + + public void testIsDefaultInClass() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class Snippet {\n"); + buf.append(" public String notDefaultMethod(){\n"); + buf.append(" return \"not default\";\n"); + buf.append(" }\n"); + buf.append(" public @interface A_test109 {\n"); + buf.append(" public String notDefaultIntMet() default \"not default\";\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("public String notDefaultMethod"); + IMethod method= (IMethod)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isAbstract(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + + ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(pack1.getJavaProject()); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertFalse(JdtFlags.isStatic(binding)); + Assert.assertFalse(JdtFlags.isAbstract(binding)); + Assert.assertFalse(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + + offset= cUnit.getSource().indexOf("public String notDefaultIntMet"); + method= (IMethod)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertTrue(JdtFlags.isAbstract(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + + p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(pack1.getJavaProject()); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertFalse(JdtFlags.isStatic(binding)); + Assert.assertTrue(JdtFlags.isAbstract(binding)); + Assert.assertFalse(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + } + + public void testImplicitAbstractInSrcFile() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("public interface Snippet {\n"); + buf.append(" float abstractMethod();\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("float"); + IMethod method= (IMethod)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + Assert.assertTrue(JdtFlags.isAbstract(method)); + + MethodDeclaration methodNode= ASTNodeSearchUtil.getMethodDeclarationNode(method, getCompilationUnitNode(buf.toString())); + Assert.assertFalse(JdtFlags.isStatic(methodNode)); + + ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(pack1.getJavaProject()); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertFalse(JdtFlags.isStatic(binding)); + Assert.assertTrue(JdtFlags.isAbstract(binding)); + Assert.assertFalse(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + } + + public void testExplicitAbstractInSrcFile() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("public interface Snippet {\n"); + buf.append(" public abstract float abstractMethod();\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + int offset= cUnit.getSource().indexOf("public abstract"); + IMethod method= (IMethod)cUnit.getElementAt(offset); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + Assert.assertTrue(JdtFlags.isAbstract(method)); + + ASTParser p= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + p.setProject(pack1.getJavaProject()); + p.setBindingsRecovery(true); + try { + IMethodBinding binding= (IMethodBinding)p.createBindings(new IJavaElement[] { method }, null)[0]; + Assert.assertFalse(JdtFlags.isStatic(binding)); + Assert.assertTrue(JdtFlags.isAbstract(binding)); + Assert.assertFalse(JdtFlags.isDefaultMethod(binding)); + } catch (OperationCanceledException e) { + } + } + + public void testExplicitAbstractInBinaryFile() throws Exception { + File clsJarPath= JavaTestPlugin.getDefault().getFileInPlugin(new Path("/testresources/JDTFlagsTest18.zip")); + assertTrue("lib not found", clsJarPath != null && clsJarPath.exists());//$NON-NLS-1$ + IPackageFragmentRoot jarRoot= JavaProjectHelper.addLibraryWithImport(fJProject1, new Path(clsJarPath.getAbsolutePath()), null, null); + fJProject1.open(null); + fJProject1.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); + Assert.assertTrue(jarRoot.exists()); + Assert.assertTrue(jarRoot.isArchive()); + IPackageFragment pf= jarRoot.getPackageFragment("pack1");//$NON-NLS-1$ + Assert.assertTrue(pf.exists()); + IClassFile classFile2= pf.getClassFile("Snippet.class"); + IMethod method= classFile2.getType().getMethod("explicitAbstractMethod", null); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + Assert.assertTrue(JdtFlags.isAbstract(method)); + } + + public void testImplicitAbstractInBinaryFile() throws Exception { + File clsJarPath= JavaTestPlugin.getDefault().getFileInPlugin(new Path("/testresources/JDTFlagsTest18.zip")); + assertTrue("lib not found", clsJarPath != null && clsJarPath.exists());//$NON-NLS-1$ + IPackageFragmentRoot jarRoot= JavaProjectHelper.addLibraryWithImport(fJProject1, new Path(clsJarPath.getAbsolutePath()), null, null); + fJProject1.open(null); + fJProject1.getProject().refreshLocal(IResource.DEPTH_INFINITE, null); + Assert.assertTrue(jarRoot.exists()); + Assert.assertTrue(jarRoot.isArchive()); + IPackageFragment pf= jarRoot.getPackageFragment("pack1");//$NON-NLS-1$ + Assert.assertTrue(pf.exists()); + IClassFile classFile2= pf.getClassFile("Snippet.class"); + IMethod method= classFile2.getType().getMethod("implicitAbstractMethod", null); + Assert.assertFalse(JdtFlags.isStatic(method)); + Assert.assertFalse(JdtFlags.isDefaultMethod(method)); + Assert.assertTrue(JdtFlags.isAbstract(method)); + } + + public void testIsStaticAnnotationType() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("\n"); + buf.append("public @interface Snippet {\n"); + buf.append(" int i= 0;\n"); + buf.append(" public String name();\n"); + buf.append("}\n"); + ICompilationUnit cUnit= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + CompilationUnit cuNode= getCompilationUnitNode(buf.toString()); + + int offset= cUnit.getSource().indexOf("i="); + IJavaElement elem= cUnit.getElementAt(offset); + FieldDeclaration field= ASTNodeSearchUtil.getFieldDeclarationNode((IField)elem, cuNode); + Assert.assertTrue(JdtFlags.isStatic(field)); + Assert.assertTrue(JdtFlags.isStatic((IField)elem)); + + offset= cUnit.getSource().indexOf("name"); + elem= cUnit.getElementAt(offset); + AnnotationTypeMemberDeclaration annotationMember= ASTNodeSearchUtil.getAnnotationTypeMemberDeclarationNode((IMethod)elem, cuNode); + Assert.assertFalse(JdtFlags.isStatic(annotationMember)); + Assert.assertFalse(JdtFlags.isStatic((IMethod)elem)); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/Java18ProjectTestSetup.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/Java18ProjectTestSetup.java new file mode 100644 index 0000000000..6a7fa8bc34 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/Java18ProjectTestSetup.java @@ -0,0 +1,76 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.core; + +import java.io.File; +import java.io.IOException; + +import junit.framework.Test; + +import org.osgi.framework.Bundle; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; + +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.FileLocator; +import org.eclipse.core.runtime.IPath; + +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class Java18ProjectTestSetup extends ProjectTestSetup { + + public static final String PROJECT_NAME18= "TestSetupProject18"; + + public static IJavaProject getProject() { + IProject project= ResourcesPlugin.getWorkspace().getRoot().getProject(PROJECT_NAME18); + return JavaCore.create(project); + } + + public static IClasspathEntry[] getDefaultClasspath() throws CoreException { + IPath[] rtJarPath= JavaProjectHelper.findRtJar(JavaProjectHelper.RT_STUBS_18); + return new IClasspathEntry[] { JavaCore.newLibraryEntry(rtJarPath[0], rtJarPath[1], rtJarPath[2], true) }; + } + + public static String getJdtAnnotations20Path() throws IOException { + Bundle[] annotationsBundles= JavaPlugin.getDefault().getBundles("org.eclipse.jdt.annotation", "2.0.0"); //$NON-NLS-1$ + File bundleFile= FileLocator.getBundleFile(annotationsBundles[0]); + String path= bundleFile.getPath(); + if (bundleFile.isDirectory()) { + path= bundleFile.getPath() + "/bin"; + } + return path; + } + + public Java18ProjectTestSetup(Test test) { + super(test); + } + + @Override + protected boolean projectExists() { + return getProject().exists(); + } + + @Override + protected IJavaProject createAndInitializeProject() throws CoreException { + IJavaProject javaProject= JavaProjectHelper.createJavaProject(PROJECT_NAME18, "bin"); + javaProject.setRawClasspath(getDefaultClasspath(), null); + JavaProjectHelper.set18CompilerOptions(javaProject); + return javaProject; + } + +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest17.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest18.java similarity index 83% rename from org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest17.java rename to org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest18.java index cfb8d25c89..481d5b24c3 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest17.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest18.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011 IBM Corporation and others. + * Copyright (c) 2011, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,13 +33,13 @@ import org.eclipse.jdt.ui.PreferenceConstants; -public class JavaElementLabelsTest17 extends CoreTests { +public class JavaElementLabelsTest18 extends CoreTests { - private static final Class THIS= JavaElementLabelsTest17.class; + private static final Class THIS= JavaElementLabelsTest18.class; private IJavaProject fJProject1; - public JavaElementLabelsTest17(String name) { + public JavaElementLabelsTest18(String name) { super(name); } @@ -48,18 +48,18 @@ public static Test suite() { } public static Test setUpTest(Test test) { - return new Java17ProjectTestSetup(test); + return new Java18ProjectTestSetup(test); } protected void setUp() throws Exception { - fJProject1= Java17ProjectTestSetup.getProject(); + fJProject1= Java18ProjectTestSetup.getProject(); IPreferenceStore store= PreferenceConstants.getPreferenceStore(); store.setValue(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); } protected void tearDown() throws Exception { - JavaProjectHelper.clear(fJProject1, Java17ProjectTestSetup.getDefaultClasspath()); + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); } @@ -208,4 +208,33 @@ public void testMethodLabelPolymorphicSignatureReference3Ret() throws Exception assertEqualString(lab, "Object invoke(char arg00, ArrayList arg01, Void arg02)"); } + public void testTypeLabelLambda1() throws Exception { + + IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + IPackageFragment pack1= sourceFolder.createPackageFragment("org.test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package org.test;\n"); + buf.append("import java.util.function.IntConsumer;\n"); + buf.append("public class C {\n"); + buf.append(" IntConsumer c = (i) -> { };\n"); + buf.append("}\n"); + String content= buf.toString(); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", content, false, null); + + IJavaElement[] elems= cu.codeSelect(content.lastIndexOf("i"), 1); + IJavaElement i= elems[0]; + String lab= JavaElementLabels.getTextLabel(i, JavaElementLabels.ALL_DEFAULT | JavaElementLabels.ALL_FULLY_QUALIFIED); + assertEqualString(lab, "org.test.C.c.() -> {...} IntConsumer.accept(int).i"); + + IJavaElement lambdaMethod= i.getParent(); + lab= JavaElementLabels.getTextLabel(lambdaMethod, JavaElementLabels.T_FULLY_QUALIFIED + | JavaElementLabels.M_POST_QUALIFIED | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES); + assertEqualString(lab, "accept(int i) - org.test.C.c.() -> {...} IntConsumer"); + + IJavaElement lambdaType= lambdaMethod.getParent(); + lab= JavaElementLabels.getTextLabel(lambdaType, JavaElementLabels.T_POST_QUALIFIED); + assertEqualString(lab, "() -> {...} IntConsumer - org.test.C.c"); + } + } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest.java index bfb25ea36d..6b301e9345 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -62,7 +62,7 @@ public class MethodOverrideTest extends CoreTests { */ private static final Class THIS= MethodOverrideTest.class; - private static final boolean DEBUG_SHOWRESULTS= false; + private static final boolean DEBUG_SHOWRESULTS= true; public static Test suite() { return setUpTest(new TestSuite(THIS)); @@ -283,8 +283,7 @@ public void testOverrideRaw1() throws Exception { doOverrideTests(cu, 1, 1, 0); // B and A } - - private void doOverrideTests(ICompilationUnit cu, int focusIndex, int overridingIndex, int overriddenIndex) throws JavaModelException { + protected void doOverrideTests(ICompilationUnit cu, int focusIndex, int overridingIndex, int overriddenIndex) throws JavaModelException { CompilationUnit root= assertNoCompilationError(cu); IType[] types= cu.getTypes(); @@ -295,15 +294,21 @@ private void doOverrideTests(ICompilationUnit cu, int focusIndex, int overriding typeBindings[i]= typeBindings[i + 1].getSuperclass(); } + IType focusType= types[focusIndex]; + IType overridingType= types[overridingIndex]; ITypeBinding overridingTypeBinding= typeBindings[overridingIndex]; assertSameType(overridingType, overridingTypeBinding); IType overriddenType= types[overriddenIndex]; - ITypeBinding overriddenTypeBinding= typeBindings[overriddenIndex]; + ITypeBinding overriddenTypeBinding= typeBindings[overriddenIndex]; assertSameType(overriddenType, overriddenTypeBinding); - IType focusType= types[focusIndex]; + doOverrideTests(root, focusType, overridingType, overridingTypeBinding, overriddenType, overriddenTypeBinding); + } + + protected void doOverrideTests(CompilationUnit root, IType focusType, IType overridingType, ITypeBinding overridingTypeBinding, IType overriddenType, ITypeBinding overriddenTypeBinding) + throws JavaModelException { ITypeHierarchy hierarchy= focusType.newTypeHierarchy(null); MethodOverrideTester tester= new MethodOverrideTester(focusType, hierarchy); @@ -426,7 +431,7 @@ private void assertSameType(IType type, ITypeBinding binding) throws JavaModelEx assertEquals(methods.length, bindings.length); } - private CompilationUnit assertNoCompilationError(ICompilationUnit cu) { + protected CompilationUnit assertNoCompilationError(ICompilationUnit cu) { ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); parser.setSource(cu); parser.setResolveBindings(true); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest18.java new file mode 100644 index 0000000000..bb788a9e01 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/MethodOverrideTest18.java @@ -0,0 +1,94 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.core; + +import java.util.Hashtable; + +import junit.framework.Test; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.ILocalVariable; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.NodeFinder; +import org.eclipse.jdt.core.dom.TypeDeclaration; + +public class MethodOverrideTest18 extends MethodOverrideTest { + + private static final Class THIS= MethodOverrideTest18.class; + + public static Test suite() { + return setUpTest(new NoSuperTestsSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + private IJavaProject fJProject1; + private IPackageFragmentRoot fSrc; + + public MethodOverrideTest18(String name) { + super(name); + } + + protected void setUp() throws Exception { + fJProject1= Java18ProjectTestSetup.getProject(); + fSrc= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + Hashtable options= TestOptions.getDefaultOptions(); + JavaCore.setOptions(options); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + + public void testOverrideLambda1() throws Exception { + IPackageFragment pack1= fSrc.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public interface MyFunction {\n"); + buf.append(" R apply(T t);\n"); + buf.append(" default MyFunction compose(MyFunction before) {\n"); + buf.append(" return (V v) -> apply(before.apply(v));\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("MyFunction.java", buf.toString(), false, null); + + CompilationUnit root= assertNoCompilationError(cu); + IType focusType= cu.getTypes()[0]; + + int vStart= buf.indexOf("v))"); + ILocalVariable v= (ILocalVariable) cu.codeSelect(vStart, 1)[0]; + IType overridingType= v.getDeclaringMember().getDeclaringType(); + + LambdaExpression lambda= (LambdaExpression) NodeFinder.perform(root, buf.indexOf("->"), 2); + ITypeBinding overridingTypeBinding= lambda.resolveTypeBinding(); + + IType overriddenType= focusType; + ITypeBinding overriddenTypeBinding= ((TypeDeclaration) root.types().get(0)).resolveBinding(); + + doOverrideTests(root, focusType, overridingType, overridingTypeBinding, overriddenType, overriddenTypeBinding); + } + + +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/NoSuperTestsSuite.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/NoSuperTestsSuite.java new file mode 100644 index 0000000000..bc43751137 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/NoSuperTestsSuite.java @@ -0,0 +1,58 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.core; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Test suite that only includes tests from the given test class, but not tests from super classes. + * + * @since 3.10 + */ +public class NoSuperTestsSuite extends TestSuite { + /** + * This implementation creates unnecessary test objects for tests from super classes + * (in {@link junit.framework.TestSuite#addTestMethod}). + * Alternative would have been to copy most of the implementation of TestSuite. + */ + + private static final Class WARNING_TEST_CLASS= warning(null).getClass(); + + public NoSuperTestsSuite(Class theClass) { + super(theClass); + } + + /** + * Adds the given test to this suite, but only if the test was declared in + * the test object's class (and not in a superclass). + */ + @Override + public void addTest(Test test) { + if (test instanceof TestCase) { + TestCase testCase= (TestCase) test; + Class testClass= testCase.getClass(); + try { + testClass.getDeclaredMethod(testCase.getName()); + } catch (NoSuchMethodException e) { + if (testClass != WARNING_TEST_CLASS) + return; + } + super.addTest(test); + } + } + + @Override + public void addTestSuite(Class testClass) { + super.addTest(new NoSuperTestsSuite(testClass)); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/source/AddUnimplementedMethodsTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/source/AddUnimplementedMethodsTest.java index 4c019068c5..af4885dfb7 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/source/AddUnimplementedMethodsTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/source/AddUnimplementedMethodsTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -81,7 +81,6 @@ public static Test setUpTest(Test test) { protected void setUp() throws Exception { fJavaProject= JavaProjectHelper.createJavaProject("DummyProject", "bin"); - assertNotNull(JavaProjectHelper.addRTJar(fJavaProject)); Hashtable options= TestOptions.getDefaultOptions(); options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); @@ -89,6 +88,8 @@ protected void setUp() throws Exception { options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "999"); fJavaProject.setOptions(options); + assertNotNull(JavaProjectHelper.addRTJar(fJavaProject)); + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "${body_statement}\n// TODO", null); IPackageFragmentRoot root= JavaProjectHelper.addSourceContainer(fJavaProject, "src"); @@ -97,7 +98,7 @@ protected void setUp() throws Exception { ICompilationUnit cu= fPackage.getCompilationUnit("A.java"); fClassA= cu.createType("public abstract class A {\n}\n", null, true, null); fClassA.createMethod("public abstract void a();\n", null, true, null); - fClassA.createMethod("public abstract void b(java.util.Vector v);\n", null, true, null); + fClassA.createMethod("public abstract void b(java.util.Vector v);\n", null, true, null); cu= fPackage.getCompilationUnit("B.java"); fInterfaceB= cu.createType("public interface B {\n}\n", null, true, null); @@ -149,7 +150,7 @@ public void test1() throws Exception { checkMethods(new String[] { "a", "b", "c", "equals", "clone", "toString", "finalize", "hashCode" }, methods); IImportDeclaration[] imports= cu.getImports(); - checkImports(new String[] { "java.util.Hashtable", "java.util.Vector" }, imports); + checkImports(new String[] { "java.util.Date", "java.util.Hashtable", "java.util.Vector" }, imports); } /* diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AdvancedQuickAssistTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AdvancedQuickAssistTest18.java new file mode 100644 index 0000000000..fbffc412b2 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AdvancedQuickAssistTest18.java @@ -0,0 +1,419 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix; + +import java.util.Hashtable; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.text.correction.AssistContext; +import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; + +public class AdvancedQuickAssistTest18 extends QuickFixTest { + + private static final Class THIS= AdvancedQuickAssistTest18.class; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + public AdvancedQuickAssistTest18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + + protected void setUp() throws Exception { + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + store.setValue(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); + + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "//TODO\n${body_statement}", null); + + fJProject1= Java18ProjectTestSetup.getProject(); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + } + + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public void testConvertToIfReturn1() throws Exception { + // 'if' in lambda body - positive cases + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface A {\n"); + buf.append(" void run(int n);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface B {\n"); + buf.append(" A foo(int x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class Test {\n"); + buf.append(" A fi0 = (n1) -> {\n"); + buf.append(" if (n1 == 0) {\n"); + buf.append(" System.out.println(n1);\n"); + buf.append(" return;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" \n"); + buf.append(" int fun1(int a, int b) {\n"); + buf.append(" A fi2 = (n2) -> {\n"); + buf.append(" if (a == b) {\n"); + buf.append(" System.out.println(n2);\n"); + buf.append(" return;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" return a + b;\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" A fun2(int a1, int b1) {\n"); + buf.append(" return (n) -> {\n"); + buf.append(" if (a1 == b1) {\n"); + buf.append(" System.out.println(n);\n"); + buf.append(" return;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" int fun3(int a2, int b2) {\n"); + buf.append(" B fi3 = (x) -> (n) -> {\n"); + buf.append(" if (a2 == b2) {\n"); + buf.append(" System.out.println(a2);\n"); + buf.append(" return;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" return a2 + b2;\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + String str= "if (n1 == 0)"; + AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + StringBuffer buf1= new StringBuffer(); + buf1.append("package test1;\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface A {\n"); + buf1.append(" void run(int n);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface B {\n"); + buf1.append(" A foo(int x);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("public class Test {\n"); + buf1.append(" A fi0 = (n1) -> {\n"); + buf1.append(" if (n1 != 0)\n"); + buf1.append(" return;\n"); + buf1.append(" System.out.println(n1);\n"); + buf1.append(" };\n"); + buf1.append(" \n"); + buf1.append(" int fun1(int a, int b) {\n"); + buf1.append(" A fi2 = (n2) -> {\n"); + buf1.append(" if (a == b) {\n"); + buf1.append(" System.out.println(n2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a + b;\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" A fun2(int a1, int b1) {\n"); + buf1.append(" return (n) -> {\n"); + buf1.append(" if (a1 == b1) {\n"); + buf1.append(" System.out.println(n);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" int fun3(int a2, int b2) {\n"); + buf1.append(" B fi3 = (x) -> (n) -> {\n"); + buf1.append(" if (a2 == b2) {\n"); + buf1.append(" System.out.println(a2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a2 + b2;\n"); + buf1.append(" }\n"); + buf1.append("}\n"); + String expected1= buf1.toString(); + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + + str= "if (a == b)"; + context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 3); + assertCorrectLabels(proposals); + buf1= new StringBuffer(); + buf1.append("package test1;\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface A {\n"); + buf1.append(" void run(int n);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface B {\n"); + buf1.append(" A foo(int x);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("public class Test {\n"); + buf1.append(" A fi0 = (n1) -> {\n"); + buf1.append(" if (n1 == 0) {\n"); + buf1.append(" System.out.println(n1);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" \n"); + buf1.append(" int fun1(int a, int b) {\n"); + buf1.append(" A fi2 = (n2) -> {\n"); + buf1.append(" if (a != b)\n"); + buf1.append(" return;\n"); + buf1.append(" System.out.println(n2);\n"); + buf1.append(" };\n"); + buf1.append(" return a + b;\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" A fun2(int a1, int b1) {\n"); + buf1.append(" return (n) -> {\n"); + buf1.append(" if (a1 == b1) {\n"); + buf1.append(" System.out.println(n);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" int fun3(int a2, int b2) {\n"); + buf1.append(" B fi3 = (x) -> (n) -> {\n"); + buf1.append(" if (a2 == b2) {\n"); + buf1.append(" System.out.println(a2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a2 + b2;\n"); + buf1.append(" }\n"); + buf1.append("}\n"); + expected1= buf1.toString(); + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + + + str= "if (a1 == b1)"; + context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 3); + assertCorrectLabels(proposals); + buf1= new StringBuffer(); + buf1.append("package test1;\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface A {\n"); + buf1.append(" void run(int n);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface B {\n"); + buf1.append(" A foo(int x);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("public class Test {\n"); + buf1.append(" A fi0 = (n1) -> {\n"); + buf1.append(" if (n1 == 0) {\n"); + buf1.append(" System.out.println(n1);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" \n"); + buf1.append(" int fun1(int a, int b) {\n"); + buf1.append(" A fi2 = (n2) -> {\n"); + buf1.append(" if (a == b) {\n"); + buf1.append(" System.out.println(n2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a + b;\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" A fun2(int a1, int b1) {\n"); + buf1.append(" return (n) -> {\n"); + buf1.append(" if (a1 != b1)\n"); + buf1.append(" return;\n"); + buf1.append(" System.out.println(n);\n"); + buf1.append(" };\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" int fun3(int a2, int b2) {\n"); + buf1.append(" B fi3 = (x) -> (n) -> {\n"); + buf1.append(" if (a2 == b2) {\n"); + buf1.append(" System.out.println(a2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a2 + b2;\n"); + buf1.append(" }\n"); + buf1.append("}\n"); + expected1= buf1.toString(); + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + + + str= "if (a2 == b2)"; + context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 3); + assertCorrectLabels(proposals); + buf1= new StringBuffer(); + buf1.append("package test1;\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface A {\n"); + buf1.append(" void run(int n);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("@FunctionalInterface\n"); + buf1.append("interface B {\n"); + buf1.append(" A foo(int x);\n"); + buf1.append("}\n"); + buf1.append("\n"); + buf1.append("public class Test {\n"); + buf1.append(" A fi0 = (n1) -> {\n"); + buf1.append(" if (n1 == 0) {\n"); + buf1.append(" System.out.println(n1);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" \n"); + buf1.append(" int fun1(int a, int b) {\n"); + buf1.append(" A fi2 = (n2) -> {\n"); + buf1.append(" if (a == b) {\n"); + buf1.append(" System.out.println(n2);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" return a + b;\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" A fun2(int a1, int b1) {\n"); + buf1.append(" return (n) -> {\n"); + buf1.append(" if (a1 == b1) {\n"); + buf1.append(" System.out.println(n);\n"); + buf1.append(" return;\n"); + buf1.append(" }\n"); + buf1.append(" };\n"); + buf1.append(" }\n"); + buf1.append("\n"); + buf1.append(" int fun3(int a2, int b2) {\n"); + buf1.append(" B fi3 = (x) -> (n) -> {\n"); + buf1.append(" if (a2 != b2)\n"); + buf1.append(" return;\n"); + buf1.append(" System.out.println(a2);\n"); + buf1.append(" };\n"); + buf1.append(" return a2 + b2;\n"); + buf1.append(" }\n"); + buf1.append("}\n"); + expected1= buf1.toString(); + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToIfReturn2() throws Exception { + // 'if' in lambda body - negative cases + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface A {\n"); + buf.append(" void run(int n);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface B {\n"); + buf.append(" A foo(int x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class Test {\n"); + buf.append(" int f1(int a2, int b2) {\n"); + buf.append(" B fi3 = (x) -> {\n"); + buf.append(" if (x != 100) {\n"); + buf.append(" return (n) -> System.out.println(n + x);\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" return a2 + b2;\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" void f2(int a1, int b1) {\n"); + buf.append(" A a= (n) -> {\n"); + buf.append(" if (a1 == b1) {\n"); + buf.append(" System.out.println(n);\n"); + buf.append(" return;\n"); + buf.append(" }\n"); + buf.append(" bar();\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" private void bar() {}\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + String str= "if (x != 100)"; // #foo does not return void + AssistContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 3); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfReturn); + + str= "if (a1 == b1)"; // not the last executable statement in lambda body + context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0); + proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, CorrectionMessages.AdvancedQuickAssistProcessor_convertToIfReturn); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest18.java new file mode 100644 index 0000000000..fd849e544f --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest18.java @@ -0,0 +1,1289 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix; + +import java.util.Hashtable; +import java.util.List; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.fix.FixMessages; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.text.correction.AssistContext; +import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; + +public class AssistQuickFixTest18 extends QuickFixTest { + + private static final Class THIS= AssistQuickFixTest18.class; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + public AssistQuickFixTest18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + protected void setUp() throws Exception { + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "//TODO\n${body_statement}", null); + + fJProject1= Java18ProjectTestSetup.getProject(); + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + } + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public void testAssignParamToField1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public interface I {\n"); + buf.append(" default void foo(int x) {\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("I.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("x"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 0); + } + + public void testAssignParamToField2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public interface I {\n"); + buf.append(" static void bar(int x) {\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("I.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("x"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 0); + } + + public void testConvertToLambda1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> {\n"); + buf.append(" System.out.println();\n"); + buf.append(" System.out.println();\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToLambda2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method(int a, int b);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public void method(int a, int b) {\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method(int a, int b);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar((a, b) -> {\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToLambda3() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append(" boolean equals(Object obj);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" public boolean equals(Object obj) {\n"); + buf.append(" return false;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 1); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } + + public void testConvertToLambda4() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" int count=0;\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" count++;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 1); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } + + public void testConvertToLambda5() throws Exception { + //Quick assist should not be offered in 1.7 mode + JavaProjectHelper.set17CompilerOptions(fJProject1); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + try { + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 1); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } finally { + JavaProjectHelper.set18CompilerOptions(fJProject1); + } + } + + public void testConvertToLambda6() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" boolean equals(Object obj);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public boolean equals(Object obj) {\n"); + buf.append(" return false;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 1); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } + + public void testConvertToLambda7() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("abstract class C {\n"); + buf.append(" abstract void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(C c) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new C() {\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("C()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 1); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } + + public void testConvertToLambda8() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> System.out.println());\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToLambda9() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" int method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" public int method() {\n"); + buf.append(" return 1;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("I()"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" int method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> 1);\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToLambda13() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface J {\n"); + buf.append(" J run(M x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class Test {\n"); + buf.append(" J j = new J() {\n"); + buf.append(" @Override\n"); + buf.append(" public J run(M x) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append(" }; \n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("J()"); // generic lambda not allowed + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, FixMessages.LambdaExpressionsFix_convert_to_lambda_expression); + } + + public void testConvertToAnonymousClassCreation1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> {\n"); + buf.append(" System.out.println();\n"); + buf.append(" System.out.println();\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" @Override\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreation2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method(int a, int b);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar((int a, int b) -> {\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 3); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method(int a, int b);\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" @Override\n"); + buf.append(" public void method(int a, int b) {\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" System.out.println(a+b);\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreation3() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> System.out.println());\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 5); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" void method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" @Override\n"); + buf.append(" public void method() {\n"); + buf.append(" System.out.println();\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreation4() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" int method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(() -> 1);\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 5); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I {\n"); + buf.append(" int method();\n"); + buf.append("}\n"); + buf.append("public class E {\n"); + buf.append(" void bar(I i) {\n"); + buf.append(" }\n"); + buf.append(" void foo() {\n"); + buf.append(" bar(new I() {\n"); + buf.append(" @Override\n"); + buf.append(" public int method() {\n"); + buf.append(" return 1;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreation5() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface FX {\n"); + buf.append(" default int defaultMethod(String x) {\n"); + buf.append(" return -1;\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class TestX {\n"); + buf.append(" FX fxx = x -> {\n"); + buf.append(" return (new FX() {\n"); + buf.append(" @Override\n"); + buf.append(" public int foo(int x) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append(" }).defaultMethod(\"a\");\n"); + buf.append(" };\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("TestX.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface FX {\n"); + buf.append(" default int defaultMethod(String x) {\n"); + buf.append(" return -1;\n"); + buf.append(" }\n"); + buf.append("\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class TestX {\n"); + buf.append(" FX fxx = new FX() {\n"); + buf.append(" @Override\n"); + buf.append(" public int foo(int x) {\n"); + buf.append(" return (new FX() {\n"); + buf.append(" @Override\n"); + buf.append(" public int foo(int x) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append(" }).defaultMethod(\"a\");\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreation6() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.util.function.UnaryOperator;\n"); + buf.append("\n"); + buf.append("public class Snippet {\n"); + buf.append(" UnaryOperator fi3 = x -> {\n"); + buf.append(" return x.toString();\n"); + buf.append(" };\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Snippet.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.util.function.UnaryOperator;\n"); + buf.append("\n"); + buf.append("public class Snippet {\n"); + buf.append(" UnaryOperator fi3 = new UnaryOperator() {\n"); + buf.append(" @Override\n"); + buf.append(" public String apply(String x) {\n"); + buf.append(" return x.toString();\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + // Bug 427694: [1.8][compiler] Functional interface not identified correctly + public void _testConvertToAnonymousClassCreation7() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I { Object m(Class c); }\n"); + buf.append("interface J { S m(Class c); }\n"); + buf.append("interface K { T m(Class c); }\n"); + buf.append("interface Functional extends I, J, K {}\n"); + buf.append("\n"); + buf.append("class C {\n"); + buf.append(" Functional fun= (c) -> { return null;};\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface I { Object m(Class c); }\n"); + buf.append("interface J { S m(Class c); }\n"); + buf.append("interface K { T m(Class c); }\n"); + buf.append("interface Functional extends I, J, K {}\n"); + buf.append("\n"); + buf.append("class C {\n"); + buf.append(" Functional fun= new Functional() {\n"); + buf.append(" @Override\n"); + buf.append(" public Object m(Class c) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testConvertToAnonymousClassCreationWithParameterName() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.util.function.IntFunction;\n"); + buf.append("public class E {\n"); + buf.append(" IntFunction toString= (int i) -> Integer.toString(i);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.util.function.IntFunction;\n"); + buf.append("public class E {\n"); + buf.append(" IntFunction toString= new IntFunction() {\n"); + buf.append(" @Override\n"); + buf.append(" public String apply(int i) {\n"); + buf.append(" return Integer.toString(i);\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToBlock1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1a= x -> -1;\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1a= x -> {\n"); + buf.append(" return -1;\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToBlock2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1b= x -> m1();\n"); + buf.append(" int m1(){ return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1b= x -> {\n"); + buf.append(" return m1();\n"); + buf.append(" };\n"); + buf.append(" int m1(){ return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToBlock3() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2b= x -> m1();\n"); + buf.append(" int m1() { return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2b= x -> {\n"); + buf.append(" m1();\n"); + buf.append(" };\n"); + buf.append(" int m1() { return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToBlock4() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2a= x -> System.out.println();\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2a= x -> {\n"); + buf.append(" System.out.println();\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1= x -> {\n"); + buf.append(" return x=0;\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI1 fi1= x -> x=0;\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI1 {\n"); + buf.append(" int foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> {\n"); + buf.append(" new Runnable() {\n"); + buf.append(" public void run() {\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> new Runnable() {\n"); + buf.append(" public void run() {\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression3() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> { m1(); };\n"); + buf.append(" int m1(){ return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> m1();\n"); + buf.append(" int m1(){ return 0; }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression4() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> {\n"); + buf.append(" super.toString();\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> super.toString();\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression5() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> {\n"); + buf.append(" --x;\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2= x -> --x;\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + String expected1= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1 }); + } + + public void testChangeLambdaBodyToExpression6() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2z= x -> { };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, CorrectionMessages.QuickAssistProcessor_change_lambda_body_to_expression); + } + + public void testChangeLambdaBodyToExpression7() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2c = x -> {\n"); + buf.append(" return;\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, CorrectionMessages.QuickAssistProcessor_change_lambda_body_to_expression); + } + + public void testChangeLambdaBodyToExpression8() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("class E {\n"); + buf.append(" FI2 fi2c = x -> {\n"); + buf.append(" int n= 0;\n"); + buf.append(" };\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface FI2 {\n"); + buf.append(" void foo(int x);\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + int offset= buf.toString().indexOf("->"); + AssistContext context= getCorrectionContext(cu, offset, 0); + assertNoErrors(context); + List proposals= collectAssists(context, false); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + assertProposalDoesNotExist(proposals, CorrectionMessages.QuickAssistProcessor_change_lambda_body_to_expression); + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest18.java new file mode 100644 index 0000000000..a4a8e9619c --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest18.java @@ -0,0 +1,316 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; + +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; + +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +public class CleanUpTest18 extends CleanUpTestCase { + + private static final Class THIS= CleanUpTest18.class; + + public CleanUpTest18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + protected IJavaProject getProject() { + return Java18ProjectTestSetup.getProject(); + } + + protected IClasspathEntry[] getDefaultClasspath() throws CoreException { + return Java18ProjectTestSetup.getDefaultClasspath(); + } + + public void testConvertToLambda01() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(){\n"); + buf.append(" Runnable r = new Runnable() {\n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" System.out.println(\"do something\");\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" };\n"); + buf.append("}\n"); + ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_LAMBDA); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(){\n"); + buf.append(" Runnable r = () -> System.out.println(\"do something\");\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + } + + public void testConvertToLambda02() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(){\n"); + buf.append(" Runnable r1 = new Runnable() {\n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" System.out.println(\"do something\");\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" Runnable r2 = new Runnable() {\n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" System.out.println(\"do one thing\");\n"); + buf.append(" System.out.println(\"do another thing\");\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" };\n"); + buf.append("}\n"); + ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_LAMBDA); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(){\n"); + buf.append(" Runnable r1 = () -> System.out.println(\"do something\");\n"); + buf.append(" Runnable r2 = () -> {\n"); + buf.append(" System.out.println(\"do one thing\");\n"); + buf.append(" System.out.println(\"do another thing\");\n"); + buf.append(" };\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + } + + public void testConvertToAnonymous_andBack_WithWildcards() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.util.*;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(Integer[] ints){\n"); + buf.append(" Arrays.sort(ints, (i1, i2) -> i1 - i2);\n"); + buf.append(" Comparator cw = (w1, w2) -> 0;\n"); + buf.append(" Comparator cr = (r1, r2) -> 0;\n"); + buf.append(" Comparator ce = (n1, n2) -> -0;\n"); + buf.append(" };\n"); + buf.append("}\n"); + String original= buf.toString(); + ICompilationUnit cu1= pack1.createCompilationUnit("E.java", original, false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.util.*;\n"); + buf.append("public class E {\n"); + buf.append(" void foo(Integer[] ints){\n"); + buf.append(" Arrays.sort(ints, new Comparator() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public int compare(Integer i1, Integer i2) {\n"); + buf.append(" return i1 - i2;\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" Comparator cw = new Comparator() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public int compare(Object w1, Object w2) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" Comparator cr = new Comparator() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public int compare(Object r1, Object r2) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" Comparator ce = new Comparator() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public int compare(Number n1, Number n2) {\n"); + buf.append(" return -0;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + + disable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + enable(CleanUpConstants.USE_LAMBDA); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { original }); + } + + public void testConvertToAnonymous_andBack_WithWildcards1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("interface I {\n"); + buf.append(" M run(M x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class Test {\n"); + buf.append(" I li = s -> null;\n"); + buf.append("}\n"); + String original= buf.toString(); + ICompilationUnit cu1= pack1.createCompilationUnit("Test.java", original, false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("interface I {\n"); + buf.append(" M run(M x);\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("class Test {\n"); + buf.append(" I li = new I() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public Object run(Object s) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + + disable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + enable(CleanUpConstants.USE_LAMBDA); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { original }); + } + + public void testConvertToAnonymous_andBack_WithJoinedSAM() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=428526#c1 and #c6 + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("interface Foo {\n"); + buf.append(" void m(T t);\n"); + buf.append(" void m(N n);\n"); + buf.append("}\n"); + buf.append("interface Baz extends Foo {}\n"); + buf.append("class Test {\n"); + buf.append(" Baz baz = x -> { return; };\n"); + buf.append("}\n"); + String original= buf.toString(); + ICompilationUnit cu1= pack1.createCompilationUnit("Test.java", original, false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("\n"); + buf.append("interface Foo {\n"); + buf.append(" void m(T t);\n"); + buf.append(" void m(N n);\n"); + buf.append("}\n"); + buf.append("interface Baz extends Foo {}\n"); + buf.append("class Test {\n"); + buf.append(" Baz baz = new Baz() {\n"); + buf.append(" /* comment */\n"); + buf.append(" @Override\n"); + buf.append(" public void m(Integer x) { return; }\n"); + buf.append(" };\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + + disable(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + enable(CleanUpConstants.USE_LAMBDA); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { original }); + } + + public void testConvertToLambdaNestedWithImports() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.util.concurrent.Callable;\n"); + buf.append("import java.util.concurrent.Executors;\n"); + buf.append("public class E {\n"); + buf.append(" void foo() {\n"); + buf.append(" new Thread(new Runnable() {\n"); + buf.append(" @Override\n"); + buf.append(" public void run() {\n"); + buf.append(" Executors.newSingleThreadExecutor().submit(new Callable() {\n"); + buf.append(" @Override\n"); + buf.append(" public String call() throws Exception {\n"); + buf.append(" return \"hi\";\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append(" });\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + enable(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + enable(CleanUpConstants.USE_LAMBDA); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.util.concurrent.Executors;\n"); + buf.append("public class E {\n"); + buf.append(" void foo() {\n"); + buf.append(" new Thread(() -> Executors.newSingleThreadExecutor().submit(() -> \"hi\"));\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }); + } + +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTestCase.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTestCase.java index 7606629142..8444aca7a1 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTestCase.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTestCase.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2013 IBM Corporation and others. + * Copyright (c) 2005, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,6 +41,7 @@ import org.eclipse.ltk.core.refactoring.RefactoringCore; import org.eclipse.ltk.core.refactoring.RefactoringStatus; +import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; @@ -80,6 +81,7 @@ public static Test suite() { suite.addTest(CleanUpStressTest.suite()); suite.addTest(CleanUpTest.suite()); + suite.addTest(CleanUpTest18.suite()); suite.addTest(CleanUpAnnotationTest.suite()); suite.addTest(SaveParticipantTest.suite()); suite.addTest(CleanUpActionTest.suite()); @@ -116,7 +118,7 @@ protected void setUp() throws Exception { corePrefs.setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, ""); corePrefs.setValue(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, ""); - fJProject1= ProjectTestSetup.getProject(); + fJProject1= getProject(); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); @@ -129,13 +131,21 @@ protected void setUp() throws Exception { } protected void tearDown() throws Exception { - JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); + JavaProjectHelper.clear(fJProject1, getDefaultClasspath()); disableAll(); fJProject1= null; fSourceFolder= null; fProfile= null; } + protected IJavaProject getProject() { + return ProjectTestSetup.getProject(); + } + + protected IClasspathEntry[] getDefaultClasspath() throws CoreException { + return ProjectTestSetup.getDefaultClasspath(); + } + private void disableAll() throws CoreException { Map settings= fProfile.getSettings(); CleanUpOptions options= JavaPlugin.getDefault().getCleanUpRegistry().getDefaultOptions(CleanUpConstants.DEFAULT_CLEAN_UP_OPTIONS); @@ -147,6 +157,11 @@ private void disableAll() throws CoreException { commitProfile(); } + protected void disable(String key) throws CoreException { + fProfile.getSettings().put(key, CleanUpOptions.FALSE); + commitProfile(); + } + protected void enable(String key) throws CoreException { fProfile.getSettings().put(key, CleanUpOptions.TRUE); commitProfile(); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java index cb63787a1d..aa3176a928 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -3081,8 +3081,7 @@ public void testUnimplementedMethodsWithAnnotations() throws Exception { buf.append("class B extends A {\n"); buf.append("\n"); buf.append(" @Override\n"); - buf.append(" public @NonNull\n"); - buf.append(" Object foo(@Nullable Object input) {\n"); + buf.append(" public @NonNull Object foo(@Nullable Object input) {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); @@ -3128,6 +3127,180 @@ public void testUnimplementedMethodsWithAnnotations2() throws Exception { assertExpectedExistInProposals(proposals, expected); } + public void testUnimplementedMethodsWithCovariantReturn() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272657 + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" interface Interface1 { Object getX(); }\n"); + buf.append(" interface Interface2 { Integer getX(); }\n"); + buf.append(" class Cls implements Interface1, Interface2 {\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + + assertCorrectLabels(proposals); + assertNumberOfProposals(proposals, 2); + + String[] expected= new String[2]; + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" interface Interface1 { Object getX(); }\n"); + buf.append(" interface Interface2 { Integer getX(); }\n"); + buf.append(" class Cls implements Interface1, Interface2 {\n"); + buf.append("\n"); + buf.append(" public Integer getX() {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + expected[0]= buf.toString(); + + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("public class Test {\n"); + buf.append(" interface Interface1 { Object getX(); }\n"); + buf.append(" interface Interface2 { Integer getX(); }\n"); + buf.append(" abstract class Cls implements Interface1, Interface2 {\n"); + buf.append(" }\n"); + buf.append("}\n"); + expected[1]= buf.toString(); + + assertExpectedExistInProposals(proposals, expected); + } + + public void testUnimplementedMethodsWithSubsignature() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272657 , https://bugs.eclipse.org/bugs/show_bug.cgi?id=424509#c6 + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface C { Object m(Class c); }\n"); + buf.append("interface D extends A, B, C {}\n"); + buf.append("\n"); + buf.append("//Add unimplemented methods\n"); + buf.append("class M implements D {\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + + assertCorrectLabels(proposals); + assertNumberOfProposals(proposals, 2); + + String[] expected= new String[1]; + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface C { Object m(Class c); }\n"); + buf.append("interface D extends A, B, C {}\n"); + buf.append("\n"); + buf.append("//Add unimplemented methods\n"); + buf.append("class M implements D {\n"); + buf.append("\n"); + buf.append(" public Object m(Class c) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + expected[0]= buf.toString(); + + assertExpectedExistInProposals(proposals, expected); + } + + public void testUnimplementedMethodsWithSubsignature2() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272657 , https://bugs.eclipse.org/bugs/show_bug.cgi?id=424509#c6 + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface D extends A, B {}\n"); + buf.append("\n"); + buf.append("class M implements D {\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + + assertCorrectLabels(proposals); + assertNumberOfProposals(proposals, 2); + + String[] expected= new String[1]; + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface D extends A, B {}\n"); + buf.append("\n"); + buf.append("class M implements D {\n"); + buf.append("\n"); + buf.append(" public Object m(Class c) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + expected[0]= buf.toString(); + + assertExpectedExistInProposals(proposals, expected); + } + + public void testUnimplementedMethodsWithSubsignature3() throws Exception { + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=272657 , https://bugs.eclipse.org/bugs/show_bug.cgi?id=424509#c6 + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface D extends B, A {}\n"); + buf.append("\n"); + buf.append("class M implements D {\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + + assertCorrectLabels(proposals); + assertNumberOfProposals(proposals, 2); + + String[] expected= new String[1]; + buf= new StringBuffer(); + buf.append("package test;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface D extends B, A {}\n"); + buf.append("\n"); + buf.append("class M implements D {\n"); + buf.append("\n"); + buf.append(" public Object m(Class c) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + expected[0]= buf.toString(); + + assertExpectedExistInProposals(proposals, expected); + } + public void testUnitializedVariable() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest18.java new file mode 100644 index 0000000000..d1e20363d2 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest18.java @@ -0,0 +1,151 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix; + +import java.util.ArrayList; +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + +public class LocalCorrectionsQuickFixTest18 extends QuickFixTest { + + private static final Class THIS= LocalCorrectionsQuickFixTest18.class; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + + public LocalCorrectionsQuickFixTest18(String name) { + super(name); + } + + public static Test suite() { + return setUpTest(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + + protected void setUp() throws Exception { + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, String.valueOf(99)); + options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR); + options.put(JavaCore.COMPILER_PB_UNCHECKED_TYPE_OPERATION, JavaCore.IGNORE); + options.put(JavaCore.COMPILER_PB_MISSING_HASHCODE_METHOD, JavaCore.WARNING); + options.put(JavaCore.COMPILER_PB_REDUNDANT_TYPE_ARGUMENTS, JavaCore.WARNING); + + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + + StubUtility.setCodeTemplate(CodeTemplateContextType.CATCHBLOCK_ID, "", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORSTUB_ID, "", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "", null); + + fJProject1= Java18ProjectTestSetup.getProject(); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + } + + + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public void testUncaughtExceptionTypeUseAnnotation1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.FileNotFoundException;\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class E {\n"); + buf.append(" void test(int a) {\n"); + buf.append(" throw new @Marker FileNotFoundException();\n"); + buf.append(" }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("@interface Marker { }\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.FileNotFoundException;\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class E {\n"); + buf.append(" void test(int a) throws @Marker FileNotFoundException {\n"); + buf.append(" throw new @Marker FileNotFoundException();\n"); + buf.append(" }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("@interface Marker { }\n"); + String expected1= buf.toString(); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.FileNotFoundException;\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("public class E {\n"); + buf.append(" void test(int a) {\n"); + buf.append(" try {\n"); + buf.append(" throw new @Marker FileNotFoundException();\n"); + buf.append(" } catch (@Marker FileNotFoundException e) {\n"); + buf.append(" }\n"); + buf.append(" }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("@Target(ElementType.TYPE_USE)\n"); + buf.append("@interface Marker { }\n"); + String expected2= buf.toString(); + + assertExpectedExistInProposals(proposals, new String[] { expected1, expected2 }); + } +} diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/NullAnnotationsQuickFixTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/NullAnnotationsQuickFixTest.java index 234d93360a..ab27c0795e 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/NullAnnotationsQuickFixTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/NullAnnotationsQuickFixTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 GK Software AG and others. + * Copyright (c) 2012, 2014 GK Software AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,6 +18,8 @@ import junit.framework.Test; import junit.framework.TestSuite; +import org.osgi.framework.Bundle; + import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.TestOptions; @@ -92,7 +94,9 @@ protected void setUp() throws Exception { fJProject1= ProjectTestSetup.getProject(); if (this.ANNOTATION_JAR_PATH == null) { - File bundleFile= FileLocator.getBundleFile(Platform.getBundle("org.eclipse.jdt.annotation")); + String version= "[1.1.0,2.0.0)"; // tests run at 1.5, need the "old" null annotations + Bundle[] bundles= Platform.getBundles("org.eclipse.jdt.annotation", version); + File bundleFile= FileLocator.getBundleFile(bundles[0]); if (bundleFile.isDirectory()) this.ANNOTATION_JAR_PATH= bundleFile.getPath() + "/bin"; else @@ -1458,8 +1462,8 @@ public void testChangeReturn4() throws Exception { CompilationUnit astRoot= getASTRoot(cu); ArrayList proposals= collectCorrections(cu, astRoot); - assertNumberOfProposals(proposals, 3); // includes "add @SW" - + assertNumberOfProposals(proposals, 2); + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); assertEqualString(proposal.getDisplayString(), "Change return type of 'foo(..)' to '@Nullable'"); @@ -1499,69 +1503,75 @@ public void testChangeReturn4() throws Exception { // remove @Nullable without adding redundant @NonNull (due to @NonNullByDefault) // variant: package-level default public void testChangeReturn5() throws Exception { - IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + String suppressOptionalErrors= this.fJProject1.getOption(JavaCore.COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS, true); + try { + this.fJProject1.setOption(JavaCore.COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS, JavaCore.ENABLED); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); - StringBuffer buf= new StringBuffer(); - buf.append("@org.eclipse.jdt.annotation.NonNullByDefault\n"); - buf.append("package test1;\n"); - pack1.createCompilationUnit("package-info.java", buf.toString(), false, null); + StringBuffer buf= new StringBuffer(); + buf.append("@org.eclipse.jdt.annotation.NonNullByDefault\n"); + buf.append("package test1;\n"); + pack1.createCompilationUnit("package-info.java", buf.toString(), false, null); - buf= new StringBuffer(); - buf.append("package test1;\n"); - buf.append("import org.eclipse.jdt.annotation.*;\n"); - buf.append("public class E {\n"); - buf.append(" @Nullable Object bar() {\n"); - buf.append(" return new Object();\n"); - buf.append(" }\n"); - buf.append("}\n"); - pack1.createCompilationUnit("E.java", buf.toString(), false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public class E {\n"); + buf.append(" @Nullable Object bar() {\n"); + buf.append(" return new Object();\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack1.createCompilationUnit("E.java", buf.toString(), false, null); - buf= new StringBuffer(); - buf.append("package test1;\n"); - buf.append("public class E2 {\n"); - buf.append(" public Object foo(E e) {\n"); // non-null by default - buf.append(" return e.bar();\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack1.createCompilationUnit("E2.java", buf.toString(), false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class E2 {\n"); + buf.append(" public Object foo(E e) {\n"); // non-null by default + buf.append(" return e.bar();\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E2.java", buf.toString(), false, null); - CompilationUnit astRoot= getASTRoot(cu); - ArrayList proposals= collectCorrections(cu, astRoot); - assertNumberOfProposals(proposals, 3); // includes "add @SW" + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 3); // includes "add @SW" - CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); - assertEqualString(proposal.getDisplayString(), "Change return type of 'foo(..)' to '@Nullable'"); + assertEqualString(proposal.getDisplayString(), "Change return type of 'foo(..)' to '@Nullable'"); - String preview= getPreviewContent(proposal); + String preview= getPreviewContent(proposal); - buf= new StringBuffer(); - buf.append("package test1;\n"); - buf.append("\n"); - buf.append("import org.eclipse.jdt.annotation.Nullable;\n"); - buf.append("\n"); - buf.append("public class E2 {\n"); - buf.append(" public @Nullable Object foo(E e) {\n"); - buf.append(" return e.bar();\n"); - buf.append(" }\n"); - buf.append("}\n"); - assertEqualString(preview, buf.toString()); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("\n"); + buf.append("import org.eclipse.jdt.annotation.Nullable;\n"); + buf.append("\n"); + buf.append("public class E2 {\n"); + buf.append(" public @Nullable Object foo(E e) {\n"); + buf.append(" return e.bar();\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualString(preview, buf.toString()); - proposal= (CUCorrectionProposal)proposals.get(1); + proposal= (CUCorrectionProposal)proposals.get(1); - assertEqualString(proposal.getDisplayString(), "Change return type of 'bar(..)' to '@NonNull'"); + assertEqualString(proposal.getDisplayString(), "Change return type of 'bar(..)' to '@NonNull'"); - preview= getPreviewContent(proposal); + preview= getPreviewContent(proposal); - buf= new StringBuffer(); - buf.append("package test1;\n"); - buf.append("import org.eclipse.jdt.annotation.*;\n"); - buf.append("public class E {\n"); - buf.append(" Object bar() {\n"); // here's the rub: don't add redundant @NonNull, just remove @Nullable - buf.append(" return new Object();\n"); - buf.append(" }\n"); - buf.append("}\n"); - assertEqualString(preview, buf.toString()); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public class E {\n"); + buf.append(" Object bar() {\n"); // here's the rub: don't add redundant @NonNull, just remove @Nullable + buf.append(" return new Object();\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualString(preview, buf.toString()); + } finally { + this.fJProject1.setOption(JavaCore.COMPILER_PB_SUPPRESS_OPTIONAL_ERRORS, suppressOptionalErrors); + } } // https://bugs.eclipse.org/378724 - Null annotations are extremely hard to use in an existing project @@ -1598,7 +1608,7 @@ public void testChangeReturn6() throws Exception { CompilationUnit astRoot= getASTRoot(cu); ArrayList proposals= collectCorrections(cu, astRoot); - assertNumberOfProposals(proposals, 3); // includes "add @SW" + assertNumberOfProposals(proposals, 2); CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.java index a951c5f505..7bd2467b27 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -71,6 +71,7 @@ public class QuickFixTest extends TestCase { public static Test suite() { TestSuite suite= new TestSuite(QuickFixTest.class.getName()); + suite.addTest(QuickFixTest18.suite()); suite.addTest(SerialVersionQuickFixTest.suite()); suite.addTest(UtilitiesTest.suite()); suite.addTest(UnresolvedTypesQuickFixTest.suite()); @@ -79,6 +80,7 @@ public static Test suite() { suite.addTest(ReturnTypeQuickFixTest.suite()); suite.addTest(LocalCorrectionsQuickFixTest.suite()); suite.addTest(LocalCorrectionsQuickFixTest17.suite()); + suite.addTest(LocalCorrectionsQuickFixTest18.suite()); suite.addTest(TypeMismatchQuickFixTests.suite()); suite.addTest(ReorgQuickFixTest.suite()); suite.addTest(ModifierCorrectionsQuickFixTest.suite()); @@ -86,6 +88,7 @@ public static Test suite() { suite.addTest(GetterSetterQuickFixTest.suite()); suite.addTest(AssistQuickFixTest.suite()); suite.addTest(AssistQuickFixTest17.suite()); + suite.addTest(AssistQuickFixTest18.suite()); suite.addTest(ChangeNonStaticToStaticTest.suite()); suite.addTest(MarkerResolutionTest.suite()); suite.addTest(JavadocQuickFixTest.suite()); @@ -93,6 +96,7 @@ public static Test suite() { suite.addTest(ConvertIterableLoopQuickFixTest.suite()); suite.addTest(AdvancedQuickAssistTest.suite()); suite.addTest(AdvancedQuickAssistTest17.suite()); + suite.addTest(AdvancedQuickAssistTest18.suite()); suite.addTest(CleanUpTestCase.suite()); suite.addTest(QuickFixEnablementTest.suite()); suite.addTest(SurroundWithTemplateTest.suite()); @@ -271,7 +275,7 @@ public IProblemRequestor getProblemRequestor(ICompilationUnit workingCopy) { IProblem[] problems= (IProblem[]) problemsList.toArray(new IProblem[problemsList.size()]); assertNumberOfProblems(nProblems, problems); - + return collectCorrections(cu, problems[0], null); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest18.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest18.java new file mode 100644 index 0000000000..e3e6b68835 --- /dev/null +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest18.java @@ -0,0 +1,869 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.tests.quickfix; + +import java.util.ArrayList; +import java.util.Hashtable; + +import junit.framework.Test; +import junit.framework.TestSuite; + +import org.eclipse.jdt.testplugin.JavaProjectHelper; +import org.eclipse.jdt.testplugin.TestOptions; + +import org.eclipse.core.runtime.Path; + +import org.eclipse.jface.preference.IPreferenceStore; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.IPackageFragment; +import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; + +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; + +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.tests.core.Java18ProjectTestSetup; +import org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal; + +import org.eclipse.jdt.internal.ui.JavaPlugin; + + +public class QuickFixTest18 extends QuickFixTest { + + private static final Class THIS= QuickFixTest18.class; + + private IJavaProject fJProject1; + + private IPackageFragmentRoot fSourceFolder; + + public QuickFixTest18(String name) { + super(name); + } + + public static Test suite() { + return new Java18ProjectTestSetup(new TestSuite(THIS)); + } + + public static Test setUpTest(Test test) { + return new Java18ProjectTestSetup(test); + } + + @Override + protected void setUp() throws Exception { + Hashtable options= TestOptions.getDefaultOptions(); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.SPACE); + options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); + options.put(DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_LOCAL_VARIABLE, JavaCore.DO_NOT_INSERT); + + + JavaCore.setOptions(options); + + IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); + store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); + + fJProject1= Java18ProjectTestSetup.getProject(); + + StubUtility.setCodeTemplate(CodeTemplateContextType.METHODSTUB_ID, "", null); + StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORSTUB_ID, "", null); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + } + + + @Override + protected void tearDown() throws Exception { + JavaProjectHelper.clear(fJProject1, Java18ProjectTestSetup.getDefaultClasspath()); + } + + public void testUnimplementedMethods1() throws Exception { + IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test2;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("public interface Inter {\n"); + buf.append(" int getCount(Object[] o) throws IOException;\n"); + buf.append(" static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append(" default int defaultMethod(Object[] o) throws IOException{return 20;}\n"); + buf.append("}\n"); + pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); + + + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(1); + String preview1= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public abstract class E implements Inter{\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + proposal= (CUCorrectionProposal)proposals.get(0); + String preview2= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("\n"); + buf.append("import test2.Inter;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public int getCount(Object[] o) throws IOException {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected2= buf.toString(); + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); + + } + + public void testUnimplementedMethods2() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class MyString implements CharSequence{\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("MyString.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 3); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(1); + String preview1= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public abstract class MyString implements CharSequence{\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + proposal= (CUCorrectionProposal)proposals.get(0); + String preview2= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("public class MyString implements CharSequence{\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public char charAt(int arg0) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public int length() {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public CharSequence subSequence(int arg0, int arg1) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected2= buf.toString(); + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); + + } + + + // bug 420116 : test for annotated varargs and return type + public void testUnimplementedMethods3() throws Exception { + JavaProjectHelper.addLibrary(fJProject1, new Path(Java18ProjectTestSetup.getJdtAnnotations20Path())); + + IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); + + + StringBuffer buf= new StringBuffer(); + buf.append("package test2;\n"); + buf.append("public interface List {\n"); + buf.append("}\n"); + pack2.createCompilationUnit("List.java", buf.toString(), false, null); + + buf.append("package test2;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("import java.util.List;\n\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public interface Inter {\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException;\n"); + buf.append(" public int bug(@NonNull String... s) throws IOException;\n"); + buf.append(" public @NonNull String bar(@NonNull String s, @Nullable List l1, test2.@NonNull List l2);\n"); + buf.append(" public int boo(Object @NonNull [] @Nullable... o1);\n"); + buf.append(" static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append(" default int defaultMethod(Object[] o) throws IOException{return 20;}\n"); + buf.append("}\n"); + pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); + + + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 4); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(1); + String preview1= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public abstract class E implements Inter{\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + proposal= (CUCorrectionProposal)proposals.get(0); + String preview2= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n"); + buf.append("import java.util.List;\n\n"); + buf.append("import org.eclipse.jdt.annotation.NonNull;\n"); + buf.append("import org.eclipse.jdt.annotation.Nullable;\n\n"); + buf.append("import test2.Inter;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public int bug(@NonNull String... s) throws IOException {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public @NonNull String bar(@NonNull String s, @Nullable List l1,\n"); + buf.append(" test2.@NonNull List l2) {\n"); + buf.append(" return null;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public int boo(Object @NonNull [] @Nullable... o1) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected2= buf.toString(); + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); + } + + // bug 420116 : test for annotated varargs and return type + public void testUnimplementedMethods4() throws Exception { + JavaProjectHelper.addLibrary(fJProject1, new Path(Java18ProjectTestSetup.getJdtAnnotations20Path())); + + IPackageFragment pack2= fSourceFolder.createPackageFragment("test1", false, null); + + + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public interface Inter {\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException;\n"); + buf.append(" public int bar(@NonNull String... s) throws IOException;\n"); + buf.append(" static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append(" default int defaultMethod(Object[] o) throws IOException{return 20;}\n"); + buf.append("}\n"); + buf.append("class E implements Inter{\n"); + buf.append("}\n"); + + ICompilationUnit cu= pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 2); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(1); + String preview1= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public interface Inter {\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException;\n"); + buf.append(" public int bar(@NonNull String... s) throws IOException;\n"); + buf.append(" static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append(" default int defaultMethod(Object[] o) throws IOException{return 20;}\n"); + buf.append("}\n"); + buf.append("abstract class E implements Inter{\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + proposal= (CUCorrectionProposal)proposals.get(0); + String preview2= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.io.IOException;\n\n"); + buf.append("import org.eclipse.jdt.annotation.*;\n"); + buf.append("public interface Inter {\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException;\n"); + buf.append(" public int bar(@NonNull String... s) throws IOException;\n"); + buf.append(" static int staticMethod(Object[] o) throws IOException{return 10;}\n"); + buf.append(" default int defaultMethod(Object[] o) throws IOException{return 20;}\n"); + buf.append("}\n"); + buf.append("class E implements Inter{\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public int foo(@NonNull String @Nullable... s) throws IOException {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n\n"); + buf.append(" @Override\n"); + buf.append(" public int bar(@NonNull String... s) throws IOException {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected2= buf.toString(); + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); + } + + // bug 420116 : test for user defined annotation in varargs + public void testUnimplementedMethods5() throws Exception { + IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); + + + StringBuffer buf= new StringBuffer(); + buf.append("package test2;\n"); + buf.append("public interface List {\n"); + buf.append("}\n"); + pack2.createCompilationUnit("List.java", buf.toString(), false, null); + + buf.append("package test2;\n"); + buf.append("import java.lang.annotation.ElementType;\n"); + buf.append("import java.lang.annotation.Target;\n"); + buf.append("\n"); + buf.append("@Target({ ElementType.TYPE_USE }) @interface N1 { }\n"); + buf.append("@Target({ ElementType.TYPE_USE }) @interface N2 { }\n"); + buf.append("@Target({ ElementType.TYPE_USE }) @interface N3 { }\n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public interface Inter {\n"); + buf.append(" int foo2U(@N1 String @N2 [] s1 @N3 [], @N1 String @N2 [] @N3 [] @N4 ... s2);\n"); + buf.append("}\n"); + pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); + + + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 2); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(1); + String preview1= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("public abstract class E implements Inter{\n"); + buf.append("}\n"); + String expected1= buf.toString(); + + proposal= (CUCorrectionProposal)proposals.get(0); + String preview2= getPreviewContent(proposal); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import test2.Inter;\n"); + buf.append("import test2.N1;\n"); + buf.append("import test2.N2;\n"); + buf.append("import test2.N3;\n"); + buf.append("import test2.N4;\n"); + buf.append("public class E implements Inter{\n"); + buf.append("\n"); + buf.append(" @Override\n"); + buf.append(" public int foo2U(@N1 String @N3 [] @N2 [] s1,\n"); + buf.append(" @N1 String @N2 [] @N3 [] @N4... s2) {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append("}\n"); + String expected2= buf.toString(); + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); + } + + public void testLambdaReturnType1() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" int fun2() {\n"); + buf.append(" I i= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" };\n"); + buf.append(" return 10;\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" int fun2() {\n"); + buf.append(" I i= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" return x;\n"); + buf.append(" };\n"); + buf.append(" return 10;\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testLambdaReturnType2() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" void fun2() {\n"); + buf.append(" I i= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" void fun2() {\n"); + buf.append(" I i= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" return x;\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testLambdaReturnType3() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" void fun2() {\n"); + // Inferred parameter type + buf.append(" I i= (x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" };\n"); + buf.append(" i.foo(10);\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" void fun2() {\n"); + buf.append(" I i= (x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" return x;\n"); + buf.append(" };\n"); + buf.append(" i.foo(10);\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testLambdaReturnType4() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" I i2= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" };\n"); + buf.append(" \n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface I {\n"); + buf.append(" int foo(int x); \n"); + buf.append("}\n"); + buf.append("\n"); + buf.append("public class A { \n"); + buf.append(" I i2= (int x) -> {\n"); + buf.append(" x++;\n"); + buf.append(" System.out.println(x);\n"); + buf.append(" return x;\n"); + buf.append(" };\n"); + buf.append(" \n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + // bug 424172 + public void testImportTypeInMethodReference() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test.one", false, null); + buf= new StringBuffer(); + buf.append("package test.one;\n"); + buf.append("\n"); + buf.append("public class X {\n"); + buf.append(" public static F2 staticMethod() {\n"); + buf.append(" return null;\n"); + buf.append(" }\n"); + buf.append("}\n"); + pack1.createCompilationUnit("X.java", buf.toString(), false, null); + buf= new StringBuffer(); + buf.append("package test.one;\n"); + buf.append("\n"); + buf.append("@FunctionalInterface\n"); + buf.append("public interface F2 {\n"); + buf.append(" void foo();\n"); + buf.append("}\n"); + pack1.createCompilationUnit("F2.java", buf.toString(), false, null); + + IPackageFragment pack2= fSourceFolder.createPackageFragment("test.two", false, null); + buf= new StringBuffer(); + buf.append("package test.two;\n"); + buf.append("\n"); + buf.append("import test.one.F2;\n"); + buf.append("\n"); + buf.append("public class C1 {\n"); + buf.append(" public void fun1() {\n"); + buf.append(" F2 f = X::staticMethod;\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack2.createCompilationUnit("C1.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 9); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test.two;\n"); + buf.append("\n"); + buf.append("import test.one.F2;\n"); + buf.append("import test.one.X;\n"); + buf.append("\n"); + buf.append("public class C1 {\n"); + buf.append(" public void fun1() {\n"); + buf.append(" F2 f = X::staticMethod;\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testLambdaReturnType5() throws Exception { + StringBuffer buf= new StringBuffer(); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface C { Object m(Class c); }\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface D extends A, B, C {}\n"); + buf.append("\n"); + buf.append("class E {\n"); + buf.append(" private void foo() {\n"); + buf.append(" D d1= (x) -> {\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("import java.math.BigInteger;\n"); + buf.append("\n"); + buf.append("interface A { Object m(Class c); }\n"); + buf.append("interface B { Object m(Class c); }\n"); + buf.append("interface C { Object m(Class c); }\n"); + buf.append("@FunctionalInterface\n"); + buf.append("interface D extends A, B, C {}\n"); + buf.append("\n"); + buf.append("class E {\n"); + buf.append(" private void foo() {\n"); + buf.append(" D d1= (x) -> {\n"); + buf.append(" return x;\n"); + buf.append(" };\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testChangeModifierToStatic1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface A {\n"); + buf.append(" int i = foo();\n"); + buf.append(" default int foo() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int j = bar1();\n"); + buf.append(" abstract int bar1();\n"); + buf.append(" static void temp() {\n"); + buf.append(" bar2();\n"); + buf.append(" }\n"); + buf.append(" abstract void bar2();\n"); + buf.append(" \n"); + buf.append(" int k = fun1();\n"); + buf.append(" int fun1();\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + + ArrayList proposals= collectCorrections(cu, astRoot, 4, 0); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface A {\n"); + buf.append(" int i = foo();\n"); + buf.append(" static int foo() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int j = bar1();\n"); + buf.append(" abstract int bar1();\n"); + buf.append(" static void temp() {\n"); + buf.append(" bar2();\n"); + buf.append(" }\n"); + buf.append(" abstract void bar2();\n"); + buf.append(" \n"); + buf.append(" int k = fun1();\n"); + buf.append(" int fun1();\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + + proposals= collectCorrections(cu, astRoot, 4, 1); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + proposal= (CUCorrectionProposal)proposals.get(0); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface A {\n"); + buf.append(" int i = foo();\n"); + buf.append(" default int foo() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int j = bar1();\n"); + buf.append(" static int bar1() {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append(" static void temp() {\n"); + buf.append(" bar2();\n"); + buf.append(" }\n"); + buf.append(" abstract void bar2();\n"); + buf.append(" \n"); + buf.append(" int k = fun1();\n"); + buf.append(" int fun1();\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + + proposals= collectCorrections(cu, astRoot, 4, 2); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + proposal= (CUCorrectionProposal)proposals.get(0); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface A {\n"); + buf.append(" int i = foo();\n"); + buf.append(" default int foo() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int j = bar1();\n"); + buf.append(" abstract int bar1();\n"); + buf.append(" static void temp() {\n"); + buf.append(" bar2();\n"); + buf.append(" }\n"); + buf.append(" static void bar2() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int k = fun1();\n"); + buf.append(" int fun1();\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + + proposals= collectCorrections(cu, astRoot, 4, 3); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + proposal= (CUCorrectionProposal)proposals.get(0); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface A {\n"); + buf.append(" int i = foo();\n"); + buf.append(" default int foo() {\n"); + buf.append(" }\n"); + buf.append(" \n"); + buf.append(" int j = bar1();\n"); + buf.append(" abstract int bar1();\n"); + buf.append(" static void temp() {\n"); + buf.append(" bar2();\n"); + buf.append(" }\n"); + buf.append(" abstract void bar2();\n"); + buf.append(" \n"); + buf.append(" int k = fun1();\n"); + buf.append(" static int fun1() {\n"); + buf.append(" return 0;\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } + + public void testChangeModifierToStatic2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + StringBuffer buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface Test {\n"); + buf.append(" int i= foo();\n"); + buf.append(" abstract int foo() {\n"); + buf.append(" return 100;\n"); + buf.append(" }\n"); + buf.append("}\n"); + ICompilationUnit cu= pack1.createCompilationUnit("Test.java", buf.toString(), false, null); + + CompilationUnit astRoot= getASTRoot(cu); + + ArrayList proposals= collectCorrections(cu, astRoot, 2, 0); + assertNumberOfProposals(proposals, 1); + assertCorrectLabels(proposals); + CUCorrectionProposal proposal= (CUCorrectionProposal)proposals.get(0); + buf= new StringBuffer(); + buf.append("package test1;\n"); + buf.append("interface Test {\n"); + buf.append(" int i= foo();\n"); + buf.append(" static int foo() {\n"); + buf.append(" return 100;\n"); + buf.append(" }\n"); + buf.append("}\n"); + assertEqualStringsIgnoreOrder(new String[] { getPreviewContent(proposal) }, new String[] { buf.toString() }); + } +} diff --git a/org.eclipse.jdt.ui/.settings/.api_filters b/org.eclipse.jdt.ui/.settings/.api_filters index 50aeb84a7a..8363dfc280 100644 --- a/org.eclipse.jdt.ui/.settings/.api_filters +++ b/org.eclipse.jdt.ui/.settings/.api_filters @@ -64,6 +64,14 @@ + + + + + + + + @@ -104,6 +112,14 @@ + + + + + + + + @@ -112,6 +128,14 @@ + + + + + + + + diff --git a/org.eclipse.jdt.ui/META-INF/MANIFEST.MF b/org.eclipse.jdt.ui/META-INF/MANIFEST.MF index a6a36fb05c..54d9189951 100644 --- a/org.eclipse.jdt.ui/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ui/META-INF/MANIFEST.MF @@ -2,7 +2,7 @@ Manifest-Version: 1.0 Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.ui; singleton:=true -Bundle-Version: 3.9.100.qualifier +Bundle-Version: 3.10.0.qualifier Bundle-Activator: org.eclipse.jdt.internal.ui.JavaPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %providerName diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java index 71ad87b075..d2e22b8250 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,6 +12,7 @@ package org.eclipse.jdt.internal.corext.codemanipulation; import java.util.ArrayList; +import java.util.List; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; @@ -49,11 +50,10 @@ import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.search.IJavaSearchConstants; @@ -227,11 +227,16 @@ private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite containerName= qualifier.getFullyQualifiedName(); name= JavaModelUtil.concatenateName(containerName, simpleName); qualifierStart= qualifier.getStartPosition(); - } else if (nameNode.getParent().getLocationInParent() == QualifiedType.NAME_PROPERTY) { - Type qualifier= ((QualifiedType) nameNode.getParent().getParent()).getQualifier(); - containerName= ASTNodes.asString(qualifier); + } else if (nameNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) { + NameQualifiedType nameQualifiedType= (NameQualifiedType) nameNode.getParent(); + Name qualifier= nameQualifiedType.getQualifier(); + containerName= qualifier.getFullyQualifiedName(); name= JavaModelUtil.concatenateName(containerName, simpleName); qualifierStart= qualifier.getStartPosition(); + List annotations= nameQualifiedType.annotations(); + if (!annotations.isEmpty()) { // don't remove annotations + simpleNameStart= annotations.get(0).getStartPosition(); + } } else if (nameNode.getLocationInParent() == MethodInvocation.NAME_PROPERTY) { ASTNode qualifier= ((MethodInvocation) nameNode.getParent()).getExpression(); if (qualifier instanceof Name) { @@ -250,13 +255,13 @@ private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite IBinding binding= nameNode.resolveBinding(); if (binding != null && !binding.isRecovered()) { if (binding instanceof ITypeBinding) { - ITypeBinding typeBinding= (ITypeBinding) binding; + ITypeBinding typeBinding= ((ITypeBinding) binding).getTypeDeclaration(); String qualifiedBindingName= typeBinding.getQualifiedName(); if (containerName.length() > 0 && !qualifiedBindingName.equals(name)) { return null; } - ImportRewriteContext context= new ContextSensitiveImportRewriteContext(root, simpleNameStart, importRewrite); + ImportRewriteContext context= new ContextSensitiveImportRewriteContext(root, qualifierStart, importRewrite); String res= importRewrite.addImport(typeBinding, context); if (containerName.length() > 0 && !res.equals(simpleName)) { // adding import failed diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportReferencesCollector.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportReferencesCollector.java index 312120453b..f775ee0931 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportReferencesCollector.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportReferencesCollector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,17 +11,17 @@ package org.eclipse.jdt.internal.corext.codemanipulation; import java.util.Collection; -import java.util.Iterator; import java.util.List; import org.eclipse.jface.text.Region; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.CreationReference; import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; @@ -36,6 +36,7 @@ import org.eclipse.jdt.core.dom.MethodRefParameter; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.QualifiedName; @@ -44,9 +45,11 @@ import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; +import org.eclipse.jdt.core.dom.SuperMethodReference; import org.eclipse.jdt.core.dom.TagElement; import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.TypeMethodReference; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; @@ -163,7 +166,7 @@ private void possibleStaticImportFound(Name name) { ITypeBinding declaringClass= methodBinding.getDeclaringClass(); if (declaringClass != null && !declaringClass.isLocal()) { if (new ScopeAnalyzer(fASTRoot).isDeclaredInScope(methodBinding, simpleName, ScopeAnalyzer.METHODS | ScopeAnalyzer.CHECK_VISIBILITY)) - return; + return; fStaticImports.add(simpleName); } } @@ -192,20 +195,22 @@ protected boolean visitNode(ASTNode node) { } /* - * @see ASTVisitor#visit(ArrayType) + * @see ASTVisitor#visit(SimpleType) */ @Override - public boolean visit(ArrayType node) { - doVisitNode(node.getElementType()); + public boolean visit(SimpleType node) { + typeRefFound(node.getName()); + doVisitChildren(node.annotations()); return false; } - + /* - * @see ASTVisitor#visit(SimpleType) + * @see ASTVisitor#visit(NameQualifiedType) */ @Override - public boolean visit(SimpleType node) { - typeRefFound(node.getName()); + public boolean visit(NameQualifiedType node) { + possibleTypeRefFound(node.getQualifier()); + doVisitChildren(node.annotations()); return false; } @@ -214,8 +219,9 @@ public boolean visit(SimpleType node) { */ @Override public boolean visit(QualifiedType node) { - // nothing to do here, let the qualifier be visited - return true; + doVisitNode(node.getQualifier()); + doVisitChildren(node.annotations()); + return false; } /* @@ -295,6 +301,34 @@ public boolean visit(MethodInvocation node) { return false; } + @Override + public boolean visit(CreationReference node) { + doVisitNode(node.getType()); + doVisitChildren(node.typeArguments()); + return false; + } + + @Override + public boolean visit(ExpressionMethodReference node) { + evalQualifyingExpression(node.getExpression(), node.getName()); + doVisitChildren(node.typeArguments()); + return false; + } + + @Override + public boolean visit(SuperMethodReference node) { + doVisitNode(node.getQualifier()); + doVisitChildren(node.typeArguments()); + return false; + } + + @Override + public boolean visit(TypeMethodReference node) { + doVisitNode(node.getType()); + doVisitChildren(node.typeArguments()); + return false; + } + /* * @see ASTVisitor#visit(SuperConstructorInvocation) */ @@ -385,11 +419,13 @@ public boolean visit(MethodDeclaration node) { if (!node.isConstructor()) { doVisitNode(node.getReturnType2()); } + // name not visited + doVisitNode(node.getReceiverType()); + // receiverQualifier not visited: + // Enclosing class names cannot be shadowed by an import (qualification is always redundant). doVisitChildren(node.parameters()); - Iterator iter=node.thrownExceptions().iterator(); - while (iter.hasNext()) { - typeRefFound(iter.next()); - } + doVisitChildren(node.extraDimensions()); + doVisitChildren(node.thrownExceptionTypes()); if (!fSkipMethodBodies) { doVisitNode(node.getBody()); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java index fbf77579f6..7c4a714662 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java @@ -607,6 +607,7 @@ private static String evaluateTemplate(CodeTemplateContext context, Template tem /* * Don't use this method directly, use CodeGeneration. + * This method should work with all AST levels. * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, boolean, String, String[], String) */ public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isDeprecated, String targetName, String targetMethodDeclaringTypeName, @@ -671,11 +672,7 @@ public static String getMethodComment(ICompilationUnit cu, String typeName, Meth SingleVariableDeclaration elem= params.get(i); paramNames[i]= elem.getName().getIdentifier(); } - List exceptions= decl.thrownExceptions(); - String[] exceptionNames= new String[exceptions.size()]; - for (int i= 0; i < exceptionNames.length; i++) { - exceptionNames[i]= ASTNodes.getSimpleNameIdentifier(exceptions.get(i)); - } + String[] exceptionNames= getExceptionNames(decl); String returnType= null; if (!decl.isConstructor()) { @@ -692,6 +689,29 @@ public static String getMethodComment(ICompilationUnit cu, String typeName, Meth return textBuffer.get(); } + /** + * @param decl the method declaration + * @return the exception names + * @deprecated to avoid deprecation warnings + */ + private static String[] getExceptionNames(MethodDeclaration decl) { + String[] exceptionNames; + if (decl.getAST().apiLevel() >= AST.JLS8) { + List exceptions= decl.thrownExceptionTypes(); + exceptionNames= new String[exceptions.size()]; + for (int i= 0; i < exceptionNames.length; i++) { + exceptionNames[i]= ASTNodes.getTypeName(exceptions.get(i)); + } + } else { + List exceptions= decl.thrownExceptions(); + exceptionNames= new String[exceptions.size()]; + for (int i= 0; i < exceptionNames.length; i++) { + exceptionNames[i]= ASTNodes.getSimpleNameIdentifier(exceptions.get(i)); + } + } + return exceptionNames; + } + public static boolean shouldGenerateMethodTypeParameterTags(IJavaProject project) { return JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS_METHOD_TYPE_PARAMETERS, true)); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java index 0f0f334eb6..d303eaf6bb 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,9 +33,11 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IAnnotationBinding; @@ -98,6 +100,7 @@ public static void addOverrideAnnotation(IJavaProject project, ASTRewrite rewrit rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertFirst(marker, null); } + /* This method should work with all AST levels. */ public static MethodDeclaration createConstructorStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String type, int modifiers, boolean omitSuperForDefConst, boolean todo, CodeGenerationSettings settings) throws CoreException { AST ast= rewrite.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); @@ -105,30 +108,11 @@ public static MethodDeclaration createConstructorStub(ICompilationUnit unit, AST decl.setName(ast.newSimpleName(type)); decl.setConstructor(true); - ITypeBinding[] typeParams= binding.getTypeParameters(); - List typeParameters= decl.typeParameters(); - for (int i= 0; i < typeParams.length; i++) { - ITypeBinding curr= typeParams[i]; - TypeParameter newTypeParam= ast.newTypeParameter(); - newTypeParam.setName(ast.newSimpleName(curr.getName())); - ITypeBinding[] typeBounds= curr.getTypeBounds(); - if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ - List newTypeBounds= newTypeParam.typeBounds(); - for (int k= 0; k < typeBounds.length; k++) { - newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); - } - } - typeParameters.add(newTypeParam); - } + createTypeParameters(imports, context, ast, binding, decl); - List parameters= createParameters(unit.getJavaProject(), imports, context, ast, binding, decl); + List parameters= createParameters(unit.getJavaProject(), imports, context, ast, binding, null, decl); - List thrownExceptions= decl.thrownExceptions(); - ITypeBinding[] excTypes= binding.getExceptionTypes(); - for (int i= 0; i < excTypes.length; i++) { - String excTypeName= imports.addImport(excTypes[i], context); - thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); - } + createThrownExceptions(decl, binding, imports, context, ast); Block body= ast.newBlock(); decl.setBody(body); @@ -176,30 +160,11 @@ public static MethodDeclaration createConstructorStub(ICompilationUnit unit, AST List parameters= decl.parameters(); if (superConstructor != null) { - ITypeBinding[] typeParams= superConstructor.getTypeParameters(); - List typeParameters= decl.typeParameters(); - for (int i= 0; i < typeParams.length; i++) { - ITypeBinding curr= typeParams[i]; - TypeParameter newTypeParam= ast.newTypeParameter(); - newTypeParam.setName(ast.newSimpleName(curr.getName())); - ITypeBinding[] typeBounds= curr.getTypeBounds(); - if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ - List newTypeBounds= newTypeParam.typeBounds(); - for (int k= 0; k < typeBounds.length; k++) { - newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); - } - } - typeParameters.add(newTypeParam); - } + createTypeParameters(imports, context, ast, superConstructor, decl); - createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, decl); + createParameters(unit.getJavaProject(), imports, context, ast, superConstructor, null, decl); - List thrownExceptions= decl.thrownExceptions(); - ITypeBinding[] excTypes= superConstructor.getExceptionTypes(); - for (int i= 0; i < excTypes.length; i++) { - String excTypeName= imports.addImport(excTypes[i], context); - thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); - } + createThrownExceptions(decl, superConstructor, imports, context, ast); } Block body= ast.newBlock(); @@ -279,51 +244,13 @@ public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTR decl.setName(ast.newSimpleName(delegate.getName())); decl.setConstructor(false); - ITypeBinding[] typeParams= delegate.getTypeParameters(); - List typeParameters= decl.typeParameters(); - for (int i= 0; i < typeParams.length; i++) { - ITypeBinding curr= typeParams[i]; - TypeParameter newTypeParam= ast.newTypeParameter(); - newTypeParam.setName(ast.newSimpleName(curr.getName())); - ITypeBinding[] typeBounds= curr.getTypeBounds(); - if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ - List newTypeBounds= newTypeParam.typeBounds(); - for (int k= 0; k < typeBounds.length; k++) { - newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); - } - } - typeParameters.add(newTypeParam); - } + createTypeParameters(imports, context, ast, delegate, decl); decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context)); - List parameters= decl.parameters(); - ITypeBinding[] params= delegate.getParameterTypes(); - String[] paramNames= StubUtility.suggestArgumentNames(unit.getJavaProject(), delegate); - for (int i= 0; i < params.length; i++) { - SingleVariableDeclaration varDecl= ast.newSingleVariableDeclaration(); - if (params[i].isWildcardType() && !params[i].isUpperbound()) - varDecl.setType(imports.addImport(params[i].getBound(), ast, context)); - else { - if (delegate.isVarargs() && params[i].isArray() && i == params.length - 1) { - StringBuffer buffer= new StringBuffer(imports.addImport(params[i].getElementType(), context)); - for (int dim= 1; dim < params[i].getDimensions(); dim++) - buffer.append("[]"); //$NON-NLS-1$ - varDecl.setType(ASTNodeFactory.newType(ast, buffer.toString())); - varDecl.setVarargs(true); - } else - varDecl.setType(imports.addImport(params[i], ast, context)); - } - varDecl.setName(ast.newSimpleName(paramNames[i])); - parameters.add(varDecl); - } - - List thrownExceptions= decl.thrownExceptions(); - ITypeBinding[] excTypes= delegate.getExceptionTypes(); - for (int i= 0; i < excTypes.length; i++) { - String excTypeName= imports.addImport(excTypes[i], context); - thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); - } + List params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl); + + createThrownExceptions(decl, delegate, imports, context, ast); Block body= ast.newBlock(); decl.setBody(body); @@ -334,8 +261,8 @@ public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTR MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName(delegate.getName())); List arguments= invocation.arguments(); - for (int i= 0; i < params.length; i++) - arguments.add(ast.newSimpleName(paramNames[i])); + for (int i= 0; i < params.size(); i++) + arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier())); if (settings.useKeywordThis) { FieldAccess access= ast.newFieldAccess(); access.setExpression(ast.newThisExpression()); @@ -382,9 +309,14 @@ public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTR } return decl; } - + public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding binding, String type, CodeGenerationSettings settings, boolean inInterface) throws CoreException { + return createImplementationStub(unit, rewrite, imports, context, binding, null, type, settings, inInterface); + } + + public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, + ImportRewriteContext context, IMethodBinding binding, String[] parameterNames, String type, CodeGenerationSettings settings, boolean inInterface) throws CoreException { Assert.isNotNull(imports); Assert.isNotNull(rewrite); @@ -397,23 +329,14 @@ public static MethodDeclaration createImplementationStub(ICompilationUnit unit, decl.setConstructor(false); ITypeBinding bindingReturnType= binding.getReturnType(); + if (bindingReturnType.isWildcardType()) { + ITypeBinding bound= bindingReturnType.getBound(); + bindingReturnType= (bound != null) ? bound : bindingReturnType.getErasure(); + } - if (JavaModelUtil.is50OrHigher(unit.getJavaProject())) { - ITypeBinding[] typeParams= binding.getTypeParameters(); - List typeParameters= decl.typeParameters(); - for (int i= 0; i < typeParams.length; i++) { - ITypeBinding curr= typeParams[i]; - TypeParameter newTypeParam= ast.newTypeParameter(); - newTypeParam.setName(ast.newSimpleName(curr.getName())); - ITypeBinding[] typeBounds= curr.getTypeBounds(); - if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ - List newTypeBounds= newTypeParam.typeBounds(); - for (int k= 0; k < typeBounds.length; k++) { - newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); - } - } - typeParameters.add(newTypeParam); - } + IJavaProject javaProject= unit.getJavaProject(); + if (JavaModelUtil.is50OrHigher(javaProject)) { + createTypeParameters(imports, context, ast, binding, decl); } else { bindingReturnType= bindingReturnType.getErasure(); @@ -421,25 +344,22 @@ public static MethodDeclaration createImplementationStub(ICompilationUnit unit, decl.setReturnType2(imports.addImport(bindingReturnType, ast, context)); - List parameters= createParameters(unit.getJavaProject(), imports, context, ast, binding, decl); + List parameters= createParameters(javaProject, imports, context, ast, binding, parameterNames, decl); - List thrownExceptions= decl.thrownExceptions(); - ITypeBinding[] excTypes= binding.getExceptionTypes(); - for (int i= 0; i < excTypes.length; i++) { - String excTypeName= imports.addImport(excTypes[i], context); - thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); - } + createThrownExceptions(decl, binding, imports, context, ast); String delimiter= unit.findRecommendedLineSeparator(); - if (!inInterface) { - Map options= unit.getJavaProject().getOptions(true); + int modifiers= binding.getModifiers(); + if (!(inInterface && Modifier.isAbstract(modifiers))) { + // generate a method body + + Map options= javaProject.getOptions(true); Block body= ast.newBlock(); decl.setBody(body); String bodyStatement= ""; //$NON-NLS-1$ - ITypeBinding declaringType= binding.getDeclaringClass(); - if (Modifier.isAbstract(binding.getModifiers()) || declaringType.isAnnotation() || declaringType.isInterface()) { + if (Modifier.isAbstract(modifiers)) { Expression expression= ASTNodeFactory.newDefaultExpression(ast, decl.getReturnType2(), decl.getExtraDimensions()); if (expression != null) { ReturnStatement returnStatement= ast.newReturnStatement(); @@ -448,6 +368,12 @@ public static MethodDeclaration createImplementationStub(ICompilationUnit unit, } } else { SuperMethodInvocation invocation= ast.newSuperMethodInvocation(); + ITypeBinding declaringType= binding.getDeclaringClass(); + if (declaringType.isInterface()) { + String qualifier= imports.addImport(declaringType, context); + Name name= ASTNodeFactory.newName(ast, qualifier); + invocation.setQualifier(name); + } invocation.setName(ast.newSimpleName(binding.getName())); SingleVariableDeclaration varDecl= null; for (Iterator iterator= parameters.iterator(); iterator.hasNext();) { @@ -479,46 +405,122 @@ public static MethodDeclaration createImplementationStub(ICompilationUnit unit, decl.setJavadoc(javadoc); } } - if (settings != null && settings.overrideAnnotation && JavaModelUtil.is50OrHigher(unit.getJavaProject())) { - addOverrideAnnotation(unit.getJavaProject(), rewrite, decl, binding); + if (settings != null && settings.overrideAnnotation && JavaModelUtil.is50OrHigher(javaProject)) { + addOverrideAnnotation(javaProject, rewrite, decl, binding); } return decl; } - private static List createParameters(IJavaProject project, ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { + private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) { + ITypeBinding[] typeParams= binding.getTypeParameters(); + List typeParameters= decl.typeParameters(); + for (int i= 0; i < typeParams.length; i++) { + ITypeBinding curr= typeParams[i]; + TypeParameter newTypeParam= ast.newTypeParameter(); + newTypeParam.setName(ast.newSimpleName(curr.getName())); + ITypeBinding[] typeBounds= curr.getTypeBounds(); + if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$ + List newTypeBounds= newTypeParam.typeBounds(); + for (int k= 0; k < typeBounds.length; k++) { + newTypeBounds.add(imports.addImport(typeBounds[k], ast, context)); + } + } + typeParameters.add(newTypeParam); + } + } + + private static List createParameters(IJavaProject project, ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, String[] paramNames, MethodDeclaration decl) { boolean is50OrHigher= JavaModelUtil.is50OrHigher(project); List parameters= decl.parameters(); ITypeBinding[] params= binding.getParameterTypes(); - String[] paramNames= StubUtility.suggestArgumentNames(project, binding); + if (paramNames == null || paramNames.length < params.length) { + paramNames= StubUtility.suggestArgumentNames(project, binding); + } for (int i= 0; i < params.length; i++) { SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); - if (binding.isVarargs() && params[i].isArray() && i == params.length - 1) { - ITypeBinding type= params[i].getElementType(); - if (!is50OrHigher) - type= type.getErasure(); - StringBuffer buffer= new StringBuffer(imports.addImport(type, context)); - for (int dim= 1; dim < params[i].getDimensions(); dim++) - buffer.append("[]"); //$NON-NLS-1$ - var.setType(ASTNodeFactory.newType(ast, buffer.toString())); + ITypeBinding type= params[i]; + if (type.isWildcardType()) { + ITypeBinding bound= type.getBound(); + type= (bound != null) ? bound : type.getErasure(); + } + if (!is50OrHigher) { + type= type.getErasure(); + var.setType(imports.addImport(type, ast, context)); + } else if (binding.isVarargs() && type.isArray() && i == params.length - 1) { var.setVarargs(true); + /* + * Varargs annotations are special. + * Example: + * foo(@O Object @A [] @B ... arg) + * => @B is not an annotation on the array dimension that constitutes the vararg. + * It's the type annotation of the *innermost* array dimension. + */ + int dimensions= type.getDimensions(); + @SuppressWarnings("unchecked") + List[] dimensionAnnotations= (List[]) new List[dimensions]; + for (int dim= 0; dim < dimensions; dim++) { + dimensionAnnotations[dim]= new ArrayList(); + for (IAnnotationBinding annotation : type.getTypeAnnotations()) { + dimensionAnnotations[dim].add(imports.addAnnotation(annotation, ast, context)); + } + type= type.getComponentType(); + } + + Type elementType= imports.addImport(type, ast, context); + if (dimensions == 1) { + var.setType(elementType); + } else { + ArrayType arrayType= ast.newArrayType(elementType, dimensions - 1); + List dimensionNodes= arrayType.dimensions(); + for (int dim= 0; dim < dimensions - 1; dim++) { // all except the innermost dimension + Dimension dimension= dimensionNodes.get(dim); + dimension.annotations().addAll(dimensionAnnotations[dim]); + } + var.setType(arrayType); + } + List varargTypeAnnotations= dimensionAnnotations[dimensions - 1]; + var.varargsAnnotations().addAll(varargTypeAnnotations); } else { - ITypeBinding type= params[i]; - if (!is50OrHigher) - type= type.getErasure(); var.setType(imports.addImport(type, ast, context)); } var.setName(ast.newSimpleName(paramNames[i])); IAnnotationBinding[] annotations= binding.getParameterAnnotations(i); for (IAnnotationBinding annotation : annotations) { if (StubUtility2.isCopyOnInheritAnnotation(annotation.getAnnotationType(), project)) - var.modifiers().add(ASTNodeFactory.newAnnotation(ast, annotation, imports, context)); + var.modifiers().add(imports.addAnnotation(annotation, ast, context)); } parameters.add(var); } return parameters; } + private static void createThrownExceptions(MethodDeclaration decl, IMethodBinding method, ImportRewrite imports, ImportRewriteContext context, AST ast) { + ITypeBinding[] excTypes= method.getExceptionTypes(); + if (ast.apiLevel() >= AST.JLS8) { + List thrownExceptions= decl.thrownExceptionTypes(); + for (int i= 0; i < excTypes.length; i++) { + Type excType= imports.addImport(excTypes[i], ast, context); + thrownExceptions.add(excType); + } + } else { + List thrownExceptions= getThrownExceptions(decl); + for (int i= 0; i < excTypes.length; i++) { + String excTypeName= imports.addImport(excTypes[i], context); + thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); + } + } + } + + /** + * @param decl method declaration + * @return thrown exception names + * @deprecated to avoid deprecation warnings + */ + private static List getThrownExceptions(MethodDeclaration decl) { + return decl.thrownExceptions(); + } + private static IMethodBinding findMethodBinding(IMethodBinding method, List allMethods) { for (int i= 0; i < allMethods.size(); i++) { IMethodBinding curr= allMethods.get(i); @@ -538,20 +540,42 @@ private static IMethodBinding findOverridingMethod(IMethodBinding method, List visited, ArrayList allMethods, IPackageBinding currPack, ArrayList toImplement) { + private static void findUnimplementedInterfaceMethods(ITypeBinding typeBinding, HashSet visited, + ArrayList allMethods, IPackageBinding currPack, ArrayList toImplement) { + if (visited.add(typeBinding)) { IMethodBinding[] typeMethods= typeBinding.getDeclaredMethods(); - for (int i= 0; i < typeMethods.length; i++) { + + nextMethod: for (int i= 0; i < typeMethods.length; i++) { IMethodBinding curr= typeMethods[i]; - IMethodBinding impl= findMethodBinding(curr, allMethods); - if (impl == null || !Bindings.isVisibleInHierarchy(impl, currPack)) { - if (impl != null) - allMethods.remove(impl); - if (Modifier.isAbstract(curr.getModifiers())) { - toImplement.add(curr); - allMethods.add(curr); + for (Iterator allIter= allMethods.iterator(); allIter.hasNext();) { + IMethodBinding oneMethod= allIter.next(); + if (Bindings.isSubsignature(oneMethod, curr)) { + // We've already seen a method that is a subsignature of curr. + if (!Bindings.isSubsignature(curr, oneMethod)) { + // oneMethod is a true subsignature of curr; let's go with oneMethod + continue nextMethod; + } + // Subsignatures are equivalent. + // Check visibility and return types ('getErasure()' tries to achieve effect of "rename type variables") + if (Bindings.isVisibleInHierarchy(oneMethod, currPack) + && oneMethod.getReturnType().getErasure().isSubTypeCompatible(curr.getReturnType().getErasure())) { + // oneMethod is visible and curr doesn't have a stricter return type; let's go with oneMethod + continue nextMethod; + } + // curr is stricter than oneMethod, so let's remove oneMethod + allIter.remove(); + toImplement.remove(oneMethod); + } else if (Bindings.isSubsignature(curr, oneMethod)) { + // curr is a true subsignature of oneMethod. Let's remove oneMethod. + allIter.remove(); + toImplement.remove(oneMethod); } } + if (Modifier.isAbstract(curr.getModifiers())) { + toImplement.add(curr); + allMethods.add(curr); + } } ITypeBinding[] superInterfaces= typeBinding.getInterfaces(); for (int i= 0; i < superInterfaces.length; i++) @@ -640,7 +664,11 @@ private static List getImplementationModifiers(AST ast, IMeth int modifiers= method.getModifiers() & ~Modifier.ABSTRACT & ~Modifier.NATIVE & ~Modifier.PRIVATE; if (inInterface) { modifiers= modifiers & ~Modifier.PROTECTED; - modifiers= modifiers | Modifier.PUBLIC; + if (!method.getDeclaringClass().isInterface() ) { + modifiers= modifiers | Modifier.PUBLIC; + } + } else { + modifiers= modifiers & ~Modifier.DEFAULT; } IAnnotationBinding[] annotations= method.getAnnotations(); @@ -672,7 +700,7 @@ private static List getImplementationModifiers(AST ast, IMeth String qn= otherAnnotationType.getQualifiedName(); if (qn.endsWith(n) && (qn.length() == n.length() || qn.charAt(qn.length() - n.length() - 1) == '.')) { if (StubUtility2.isCopyOnInheritAnnotation(otherAnnotationType, javaProject)) - result.add(ASTNodeFactory.newAnnotation(ast, annotation, importRewrite, context)); + result.add(importRewrite.addAnnotation(annotation, ast, context)); break; } } @@ -688,7 +716,7 @@ private static List getImplementationModifiers(AST ast, IMeth for (IAnnotationBinding annotation : annotations) { if (StubUtility2.isCopyOnInheritAnnotation(annotation.getAnnotationType(), javaProject)) - result.add(ASTNodeFactory.newAnnotation(ast, annotation, importRewrite, context)); + result.add(importRewrite.addAnnotation(annotation, ast, context)); } result.addAll(ASTNodeFactory.newModifiers(ast, modifiers)); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java index 1f1fbe70c4..81c6122ce9 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,100 +15,7 @@ import org.eclipse.core.runtime.Assert; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; -import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayAccess; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.AssertStatement; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BlockComment; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.BooleanLiteral; -import org.eclipse.jdt.core.dom.BreakStatement; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CatchClause; -import org.eclipse.jdt.core.dom.CharacterLiteral; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ConditionalExpression; -import org.eclipse.jdt.core.dom.ConstructorInvocation; -import org.eclipse.jdt.core.dom.ContinueStatement; -import org.eclipse.jdt.core.dom.DoStatement; -import org.eclipse.jdt.core.dom.EmptyStatement; -import org.eclipse.jdt.core.dom.EnhancedForStatement; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IExtendedModifier; -import org.eclipse.jdt.core.dom.IfStatement; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.InfixExpression; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.InstanceofExpression; -import org.eclipse.jdt.core.dom.Javadoc; -import org.eclipse.jdt.core.dom.LabeledStatement; -import org.eclipse.jdt.core.dom.LineComment; -import org.eclipse.jdt.core.dom.MarkerAnnotation; -import org.eclipse.jdt.core.dom.MemberRef; -import org.eclipse.jdt.core.dom.MemberValuePair; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodRef; -import org.eclipse.jdt.core.dom.MethodRefParameter; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.NormalAnnotation; -import org.eclipse.jdt.core.dom.NullLiteral; -import org.eclipse.jdt.core.dom.NumberLiteral; -import org.eclipse.jdt.core.dom.PackageDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PostfixExpression; -import org.eclipse.jdt.core.dom.PrefixExpression; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.ReturnStatement; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleMemberAnnotation; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.SynchronizedStatement; -import org.eclipse.jdt.core.dom.TagElement; -import org.eclipse.jdt.core.dom.TextElement; -import org.eclipse.jdt.core.dom.ThisExpression; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.TryStatement; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.TypeDeclarationStatement; -import org.eclipse.jdt.core.dom.TypeLiteral; -import org.eclipse.jdt.core.dom.TypeParameter; -import org.eclipse.jdt.core.dom.UnionType; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; -import org.eclipse.jdt.core.dom.WhileStatement; -import org.eclipse.jdt.core.dom.WildcardType; +import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; @@ -119,6 +26,10 @@ public class ASTFlattener extends GenericVisitor { * @deprecated to avoid deprecation warnings */ private static final int JLS3= AST.JLS3; + /** + * @deprecated to avoid deprecation warnings + */ + private static final int JLS4= AST.JLS4; /** * The string buffer into which the serialized representation of the AST is @@ -179,6 +90,53 @@ private void printModifiers(List ext) { } } + private void printReferenceTypeArguments(List typeArguments) { + this.fBuffer.append("::");//$NON-NLS-1$ + if (!typeArguments.isEmpty()) { + this.fBuffer.append('<'); + for (Iterator it = typeArguments.iterator(); it.hasNext(); ) { + Type t = it.next(); + t.accept(this); + if (it.hasNext()) { + this.fBuffer.append(','); + } + } + this.fBuffer.append('>'); + } + } + + void printTypeAnnotations(AnnotatableType node) { + if (node.getAST().apiLevel() >= AST.JLS8) { + printAnnotationsList(node.annotations()); + } + } + + void printAnnotationsList(List annotations) { + for (Iterator it = annotations.iterator(); it.hasNext(); ) { + Annotation annotation = it.next(); + annotation.accept(this); + this.fBuffer.append(' '); + } + } + + /** + * @param node node + * @return component type + * @deprecated to avoid deprecation warning + */ + private static Type getComponentType(ArrayType node) { + return node.getComponentType(); + } + + /** + * @param node node + * @return thrown exception names + * @deprecated to avoid deprecation warning + */ + private static List getThrownExceptions(MethodDeclaration node) { + return node.thrownExceptions(); + } + /* * @see ASTVisitor#visit(AnnotationTypeDeclaration) * @since 3.0 @@ -298,8 +256,17 @@ public boolean visit(ArrayInitializer node) { */ @Override public boolean visit(ArrayType node) { - node.getComponentType().accept(this); - this.fBuffer.append("[]");//$NON-NLS-1$ + if (node.getAST().apiLevel() < AST.JLS8) { + getComponentType(node).accept(this); + this.fBuffer.append("[]");//$NON-NLS-1$ + } else { + node.getElementType().accept(this); + List dimensions = node.dimensions(); + for (int i = 0; i < dimensions.size() ; i++) { + Dimension dimension = dimensions.get(i); + dimension.accept(this); + } + } return false; } @@ -528,6 +495,28 @@ public boolean visit(ContinueStatement node) { return false; } + /* + * @see ASTVisitor#visit(CreationReference) + */ + @Override + public boolean visit(CreationReference node) { + node.getType().accept(this); + printReferenceTypeArguments(node.typeArguments()); + this.fBuffer.append("new");//$NON-NLS-1$ + return false; + } + + /* + * @see ASTVisitor#visit(Dimension) + */ + @Override + public boolean visit(Dimension node) { + this.fBuffer.append(" ");//$NON-NLS-1$ + printAnnotationsList(node.annotations()); + this.fBuffer.append("[]"); //$NON-NLS-1$ + return false; + } + /* * @see ASTVisitor#visit(DoStatement) */ @@ -639,6 +628,17 @@ public boolean visit(EnumDeclaration node) { return false; } + /* + * @see ASTVisitor#visit(ExpressionMethodReference) + */ + @Override + public boolean visit(ExpressionMethodReference node) { + node.getExpression().accept(this); + printReferenceTypeArguments(node.typeArguments()); + node.getName().accept(this); + return false; + } + /* * @see ASTVisitor#visit(ExpressionStatement) */ @@ -765,6 +765,21 @@ public boolean visit(InfixExpression node) { return false; } + /* + * @see ASTVisitor#visit(Initializer) + */ + @Override + public boolean visit(Initializer node) { + if (node.getJavadoc() != null) { + node.getJavadoc().accept(this); + } + if (node.getAST().apiLevel() >= JLS3) { + printModifiers(node.modifiers()); + } + node.getBody().accept(this); + return false; + } + /* * @see ASTVisitor#visit(InstanceofExpression) */ @@ -777,17 +792,17 @@ public boolean visit(InstanceofExpression node) { } /* - * @see ASTVisitor#visit(Initializer) + * @see ASTVisitor#visit(IntersectionType) */ @Override - public boolean visit(Initializer node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); + public boolean visit(IntersectionType node) { + for (Iterator it = node.types().iterator(); it.hasNext(); ) { + Type t = it.next(); + t.accept(this); + if (it.hasNext()) { + this.fBuffer.append(" & "); //$NON-NLS-1$ + } } - node.getBody().accept(this); return false; } @@ -816,6 +831,28 @@ public boolean visit(LabeledStatement node) { return false; } + /* + * @see ASTVisitor#visit(LambdaExpression) + */ + @Override + public boolean visit(LambdaExpression node) { + boolean hasParentheses= node.hasParentheses(); + if (hasParentheses) + this.fBuffer.append('('); + for (Iterator it= node.parameters().iterator(); it.hasNext(); ) { + VariableDeclaration v= it.next(); + v.accept(this); + if (it.hasNext()) { + this.fBuffer.append(",");//$NON-NLS-1$ + } + } + if (hasParentheses) + this.fBuffer.append(')'); + this.fBuffer.append(" -> "); //$NON-NLS-1$ + node.getBody().accept(this); + return false; + } + /* * @see ASTVisitor#visit(LineComment) * @since 3.0 @@ -938,6 +975,22 @@ public boolean visit(MethodDeclaration node) { } node.getName().accept(this); this.fBuffer.append("(");//$NON-NLS-1$ + if (node.getAST().apiLevel() >= AST.JLS8) { + Type receiverType= node.getReceiverType(); + if (receiverType != null) { + receiverType.accept(this); + this.fBuffer.append(' '); + SimpleName qualifier= node.getReceiverQualifier(); + if (qualifier != null) { + qualifier.accept(this); + this.fBuffer.append('.'); + } + this.fBuffer.append("this"); //$NON-NLS-1$ + if (node.parameters().size() > 0) { + this.fBuffer.append(','); + } + } + } for (Iterator it= node.parameters().iterator(); it.hasNext();) { SingleVariableDeclaration v= it.next(); v.accept(this); @@ -946,13 +999,22 @@ public boolean visit(MethodDeclaration node) { } } this.fBuffer.append(")");//$NON-NLS-1$ - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]"); //$NON-NLS-1$ + if (node.getAST().apiLevel() >= AST.JLS8) { + List dimensions = node.extraDimensions(); + for (Iterator it= dimensions.iterator(); it.hasNext(); ) { + Dimension e= it.next(); + e.accept(this); + } + } else { + for (int i= 0; i < node.getExtraDimensions(); i++) { + this.fBuffer.append("[]"); //$NON-NLS-1$ + } } - if (!node.thrownExceptions().isEmpty()) { + List thrownExceptions= node.getAST().apiLevel() >= AST.JLS8 ? node.thrownExceptionTypes() : getThrownExceptions(node); + if (!thrownExceptions.isEmpty()) { this.fBuffer.append(" throws ");//$NON-NLS-1$ - for (Iterator it= node.thrownExceptions().iterator(); it.hasNext();) { - Name n= it.next(); + for (Iterator it= thrownExceptions.iterator(); it.hasNext();) { + ASTNode n = it.next(); n.accept(this); if (it.hasNext()) { this.fBuffer.append(", ");//$NON-NLS-1$ @@ -1013,6 +1075,18 @@ public boolean visit(Modifier node) { return false; } + /* + * @see ASTVisitor#visit(NameQualifiedType) + */ + @Override + public boolean visit(NameQualifiedType node) { + node.getQualifier().accept(this); + this.fBuffer.append('.'); + printTypeAnnotations(node); + node.getName().accept(this); + return false; + } + /* * @see ASTVisitor#visit(NormalAnnotation) * @since 3.0 @@ -1127,6 +1201,7 @@ public boolean visit(PrefixExpression node) { */ @Override public boolean visit(PrimitiveType node) { + printTypeAnnotations(node); this.fBuffer.append(node.getPrimitiveTypeCode().toString()); return false; } @@ -1150,6 +1225,7 @@ public boolean visit(QualifiedName node) { public boolean visit(QualifiedType node) { node.getQualifier().accept(this); this.fBuffer.append(".");//$NON-NLS-1$ + printTypeAnnotations(node); node.getName().accept(this); return false; } @@ -1182,7 +1258,9 @@ public boolean visit(SimpleName node) { */ @Override public boolean visit(SimpleType node) { - return true; + printTypeAnnotations(node); + node.getName().accept(this); + return false; } /* @@ -1210,13 +1288,26 @@ public boolean visit(SingleVariableDeclaration node) { node.getType().accept(this); if (node.getAST().apiLevel() >= JLS3) { if (node.isVarargs()) { + if (node.getAST().apiLevel() >= AST.JLS8) { + this.fBuffer.append(' '); + List annotations= node.varargsAnnotations(); + printAnnotationsList(annotations); + } this.fBuffer.append("...");//$NON-NLS-1$ } } this.fBuffer.append(" ");//$NON-NLS-1$ node.getName().accept(this); - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]"); //$NON-NLS-1$ + if (node.getAST().apiLevel() >= AST.JLS8) { + List dimensions = node.extraDimensions(); + for (Iterator it= dimensions.iterator(); it.hasNext(); ) { + Dimension e= it.next(); + e.accept(this); + } + } else { + for (int i= 0; i < node.getExtraDimensions(); i++) { + this.fBuffer.append("[]"); //$NON-NLS-1$ + } } if (node.getInitializer() != null) { this.fBuffer.append("=");//$NON-NLS-1$ @@ -1318,6 +1409,21 @@ public boolean visit(SuperMethodInvocation node) { return false; } + /* + * @see ASTVisitor#visit(SuperMethodReference) + */ + @Override + public boolean visit(SuperMethodReference node) { + if (node.getQualifier() != null) { + node.getQualifier().accept(this); + this.fBuffer.append('.'); + } + this.fBuffer.append("super");//$NON-NLS-1$ + printReferenceTypeArguments(node.typeArguments()); + node.getName().accept(this); + return false; + } + /* * @see ASTVisitor#visit(SwitchCase) */ @@ -1443,7 +1549,7 @@ public boolean visit(ThrowStatement node) { @Override public boolean visit(TryStatement node) { this.fBuffer.append("try ");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= AST.JLS4) { + if (node.getAST().apiLevel() >= JLS4) { if (!node.resources().isEmpty()) { this.fBuffer.append("(");//$NON-NLS-1$ for (Iterator it= node.resources().iterator(); it.hasNext();) { @@ -1557,12 +1663,24 @@ public boolean visit(TypeLiteral node) { return false; } + /* + * @see ASTVisitor#visit(TypeMethodReference) + */ + @Override + public boolean visit(TypeMethodReference node) { + node.getType().accept(this); + printReferenceTypeArguments(node.typeArguments()); + node.getName().accept(this); + return false; + } + /* * @see ASTVisitor#visit(TypeParameter) * @since 3.0 */ @Override public boolean visit(TypeParameter node) { + printModifiers(node.modifiers()); node.getName().accept(this); if (!node.typeBounds().isEmpty()) { this.fBuffer.append(" extends ");//$NON-NLS-1$ @@ -1618,8 +1736,16 @@ public boolean visit(VariableDeclarationExpression node) { @Override public boolean visit(VariableDeclarationFragment node) { node.getName().accept(this); - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]");//$NON-NLS-1$ + if (node.getAST().apiLevel() >= AST.JLS8) { + List dimensions = node.extraDimensions(); + for (Iterator it= dimensions.iterator(); it.hasNext(); ) { + Dimension e= it.next(); + e.accept(this); + } + } else { + for (int i= 0; i < node.getExtraDimensions(); i++) { + this.fBuffer.append("[]"); //$NON-NLS-1$ + } } if (node.getInitializer() != null) { this.fBuffer.append("=");//$NON-NLS-1$ @@ -1649,12 +1775,25 @@ public boolean visit(VariableDeclarationStatement node) { return false; } + /* + * @see ASTVisitor#visit(WhileStatement) + */ + @Override + public boolean visit(WhileStatement node) { + this.fBuffer.append("while (");//$NON-NLS-1$ + node.getExpression().accept(this); + this.fBuffer.append(") ");//$NON-NLS-1$ + node.getBody().accept(this); + return false; + } + /* * @see ASTVisitor#visit(WildcardType) * @since 3.0 */ @Override public boolean visit(WildcardType node) { + printTypeAnnotations(node); this.fBuffer.append("?");//$NON-NLS-1$ Type bound= node.getBound(); if (bound != null) { @@ -1668,16 +1807,4 @@ public boolean visit(WildcardType node) { return false; } - /* - * @see ASTVisitor#visit(WhileStatement) - */ - @Override - public boolean visit(WhileStatement node) { - this.fBuffer.append("while (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodeFactory.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodeFactory.java index a9a0871fa0..9b046049d7 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodeFactory.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodeFactory.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,37 +17,30 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.CharacterLiteral; +import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IAnnotationBinding; import org.eclipse.jdt.core.dom.IExtendedModifier; -import org.eclipse.jdt.core.dom.IMemberValuePairBinding; +import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.InfixExpression.Operator; -import org.eclipse.jdt.core.dom.MarkerAnnotation; -import org.eclipse.jdt.core.dom.MemberValuePair; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NodeFinder; -import org.eclipse.jdt.core.dom.NormalAnnotation; +import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleMemberAnnotation; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.TypeLiteral; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.dom.UnionType; import org.eclipse.jdt.core.dom.VariableDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; @@ -55,7 +48,7 @@ /** * JDT-UI-internal helper methods to create new {@link ASTNode}s. - * Complements AST#new*(..). + * Complements AST#new*(..) and ImportRewrite#add*(..). * * @see JDTUIHelperClasses */ @@ -136,6 +129,26 @@ public static Type newType(AST ast, String content) { return (Type)result; } + /** + * Returns an {@link ArrayType} that adds one dimension to the given type node. + * If the given node is already an ArrayType, then a new {@link Dimension} + * without annotations is inserted at the first position. + * + * @param type the type to be wrapped + * @return the array type + * @since 3.10 + */ + public static ArrayType newArrayType(Type type) { + if (type instanceof ArrayType) { + Dimension dimension= type.getAST().newDimension(); + ArrayType arrayType= (ArrayType) type; + arrayType.dimensions().add(0, dimension); // first dimension is outermost + return arrayType; + } else { + return type.getAST().newArrayType(type); + } + } + /** * Returns the new type node corresponding to the type of the given declaration * including the extra dimensions. @@ -150,7 +163,7 @@ public static Type newType(AST ast, VariableDeclaration declaration) { /** * Returns the new type node corresponding to the type of the given declaration * including the extra dimensions. If the type is a {@link UnionType}, use the LUB type. - * If the importRewrite is null, the type may be fully-qualified. + * If the importRewrite is null, the type may be fully-qualified. * * @param ast The AST to create the resulting type with. * @param declaration The variable declaration to get the type from @@ -161,8 +174,11 @@ public static Type newType(AST ast, VariableDeclaration declaration) { * @since 3.7.1 */ public static Type newType(AST ast, VariableDeclaration declaration, ImportRewrite importRewrite, ImportRewriteContext context) { - Type type= ASTNodes.getType(declaration); + if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) { + return newType((LambdaExpression) declaration.getParent(), (VariableDeclarationFragment) declaration, ast, importRewrite, context); + } + Type type= ASTNodes.getType(declaration); if (declaration instanceof SingleVariableDeclaration) { Type type2= ((SingleVariableDeclaration) declaration).getType(); if (type2 instanceof UnionType) { @@ -184,14 +200,72 @@ public static Type newType(AST ast, VariableDeclaration declaration, ImportRewri return type; } } - int extraDim= declaration.getExtraDimensions(); + type= (Type) ASTNode.copySubtree(ast, type); - for (int i= 0; i < extraDim; i++) { - type= ast.newArrayType(type); + + List extraDimensions= declaration.extraDimensions(); + if (!extraDimensions.isEmpty()) { + ArrayType arrayType; + if (type instanceof ArrayType) { + arrayType= (ArrayType) type; + } else { + arrayType= ast.newArrayType(type, 0); + type= arrayType; + } + arrayType.dimensions().addAll(ASTNode.copySubtrees(ast, extraDimensions)); } return type; } + private static Type newType(LambdaExpression lambdaExpression, VariableDeclarationFragment declaration, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { + IMethodBinding method= lambdaExpression.resolveMethodBinding(); + if (method != null) { + ITypeBinding[] parameterTypes= method.getParameterTypes(); + int index= lambdaExpression.parameters().indexOf(declaration); + ITypeBinding typeBinding= parameterTypes[index]; + if (importRewrite != null) { + return importRewrite.addImport(typeBinding, ast, context); + } else { + String qualifiedName= typeBinding.getQualifiedName(); + if (qualifiedName.length() > 0) { + return newType(ast, qualifiedName); + } + } + } + // fall-back + return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ + } + + /** + * Returns the new type node representing the return type of lambdaExpression + * including the extra dimensions. + * + * @param lambdaExpression the lambda expression + * @param ast the AST to create the return type with + * @param importRewrite the import rewrite to use, or null + * @param context the import rewrite context, or null + * @return a new type node created with the given AST representing the return type of + * lambdaExpression + * + * @since 3.10 + */ + public static Type newReturnType(LambdaExpression lambdaExpression, AST ast, ImportRewrite importRewrite, ImportRewriteContext context) { + IMethodBinding method= lambdaExpression.resolveMethodBinding(); + if (method != null) { + ITypeBinding returnTypeBinding= method.getReturnType(); + if (importRewrite != null) { + return importRewrite.addImport(returnTypeBinding, ast); + } else { + String qualifiedName= returnTypeBinding.getQualifiedName(); + if (qualifiedName.length() > 0) { + return newType(ast, qualifiedName); + } + } + } + // fall-back + return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ + } + /** * Returns an expression that is assignable to the given type. null is * returned if the type is the 'void' type. @@ -280,105 +354,36 @@ public static Expression newInfixExpression(AST ast, Operator operator, ArrayLis return result; } - public static Annotation newAnnotation(AST ast, IAnnotationBinding annotation, ImportRewrite importRewrite, ImportRewriteContext context) { - Type type= importRewrite.addImport(annotation.getAnnotationType(), ast, context); - Name name; - if (type instanceof SimpleType) { - SimpleType simpleType= (SimpleType) type; - name= simpleType.getName(); - // pay ransom to allow reuse of 'name': - simpleType.setName(ast.newSimpleName("a")); //$NON-NLS-1$ - } else { - name= ast.newName(ASTNodes.asString(type)); - } - - IMemberValuePairBinding[] mvps= annotation.getDeclaredMemberValuePairs(); - if (mvps.length == 0) { - MarkerAnnotation result= ast.newMarkerAnnotation(); - result.setTypeName(name); - return result; - } else if (mvps.length == 1 && "value".equals(mvps[0].getName())) { //$NON-NLS-1$ - SingleMemberAnnotation result= ast.newSingleMemberAnnotation(); - result.setTypeName(name); - Object value= mvps[0].getValue(); - if (value != null) - result.setValue(newAnnotationValue(ast, value, importRewrite, context)); - return result; - } else { - NormalAnnotation result= ast.newNormalAnnotation(); - result.setTypeName(name); - List values= result.values(); - for (int i= 0; i < mvps.length; i++) { - IMemberValuePairBinding mvp= mvps[i]; - MemberValuePair mvpNode= ast.newMemberValuePair(); - mvpNode.setName(ast.newSimpleName(mvp.getName())); - Object value= mvp.getValue(); - if (value != null) - mvpNode.setValue(newAnnotationValue(ast, value, importRewrite, context)); - values.add(mvpNode); + public static Type newCreationType(AST ast, ITypeBinding typeBinding, ImportRewrite importRewrite, ImportRewriteContext importContext) { + if (typeBinding.isParameterizedType()) { + Type baseType= newCreationType(ast, typeBinding.getTypeDeclaration(), importRewrite, importContext); + ParameterizedType parameterizedType= ast.newParameterizedType(baseType); + for (ITypeBinding typeArgument : typeBinding.getTypeArguments()) { + parameterizedType.typeArguments().add(newCreationType(ast, typeArgument, importRewrite, importContext)); } - return result; - } - } - - public static Expression newAnnotationValue(AST ast, Object value, ImportRewrite importRewrite, ImportRewriteContext context) { - if (value instanceof Boolean) { - return ast.newBooleanLiteral(((Boolean) value).booleanValue()); - - } else if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long - || value instanceof Float || value instanceof Double) { - return ast.newNumberLiteral(value.toString()); - - } else if (value instanceof Character) { - CharacterLiteral result= ast.newCharacterLiteral(); - result.setCharValue(((Character) value).charValue()); - return result; - - } else if (value instanceof ITypeBinding) { - TypeLiteral result= ast.newTypeLiteral(); - result.setType(importRewrite.addImport((ITypeBinding) value, ast, context)); - return result; - - } else if (value instanceof String) { - StringLiteral result= ast.newStringLiteral(); - result.setLiteralValue((String) value); - return result; - - } else if (value instanceof IVariableBinding) { - IVariableBinding variable= (IVariableBinding) value; + return parameterizedType; - FieldAccess result= ast.newFieldAccess(); - result.setName(ast.newSimpleName(variable.getName())); - Type type= importRewrite.addImport(variable.getType(), ast, context); - Name name; - if (type instanceof SimpleType) { - SimpleType simpleType= (SimpleType) type; - name= simpleType.getName(); - // pay ransom to allow reuse of 'name': - simpleType.setName(ast.newSimpleName("a")); //$NON-NLS-1$ - } else { - name= ast.newName(ASTNodes.asString(type)); + } else if (typeBinding.isParameterizedType()) { + Type elementType= newCreationType(ast, typeBinding.getElementType(), importRewrite, importContext); + ArrayType arrayType= ast.newArrayType(elementType, 0); + while (typeBinding.isArray()) { + Dimension dimension= ast.newDimension(); + IAnnotationBinding[] typeAnnotations= typeBinding.getTypeAnnotations(); + for (IAnnotationBinding typeAnnotation : typeAnnotations) { + dimension.annotations().add(importRewrite.addAnnotation(typeAnnotation, ast, importContext)); + } + arrayType.dimensions().add(dimension); + typeBinding= typeBinding.getComponentType(); } - result.setExpression(name); - return result; - - } else if (value instanceof IAnnotationBinding) { - return newAnnotation(ast, (IAnnotationBinding) value, importRewrite, context); - - } else if (value instanceof Object[]) { - Object[] values= (Object[]) value; - if (values.length == 1) - return newAnnotationValue(ast, values[0], importRewrite, context); - - ArrayInitializer initializer= ast.newArrayInitializer(); - List expressions= initializer.expressions(); - for (Object val : values) - expressions.add(newAnnotationValue(ast, val, importRewrite, context)); - return initializer; + return arrayType; + + } else if (typeBinding.isWildcardType()) { + ITypeBinding bound= typeBinding.getBound(); + typeBinding= (bound != null) ? bound : typeBinding.getErasure(); + return newCreationType(ast, typeBinding, importRewrite, importContext); } else { - return null; + return importRewrite.addImport(typeBinding, ast, importContext); } } - } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java index fad83fcf74..27d347c153 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -42,6 +42,7 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; +import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Assignment; @@ -64,11 +65,14 @@ import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.InfixExpression; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.Message; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.ParenthesizedExpression; @@ -81,6 +85,7 @@ import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.UnionType; import org.eclipse.jdt.core.dom.VariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; @@ -288,8 +293,10 @@ public static VariableDeclaration findVariableDeclaration(IVariableBinding bindi /** * Returns the type node for the given declaration. + * * @param declaration the declaration - * @return the type node + * @return the type node or null if the given declaration represents a type + * inferred parameter in lambda expression */ public static Type getType(VariableDeclaration declaration) { if (declaration instanceof SingleVariableDeclaration) { @@ -302,6 +309,8 @@ else if (parent instanceof VariableDeclarationStatement) return ((VariableDeclarationStatement)parent).getType(); else if (parent instanceof FieldDeclaration) return ((FieldDeclaration)parent).getType(); + else if (parent instanceof LambdaExpression) + return null; } Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ return null; @@ -309,9 +318,20 @@ else if (parent instanceof FieldDeclaration) public static int getDimensions(VariableDeclaration declaration) { int dim= declaration.getExtraDimensions(); - Type type= getType(declaration); - if (type instanceof ArrayType) { - dim += ((ArrayType) type).getDimensions(); + if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) { + LambdaExpression lambda= (LambdaExpression) declaration.getParent(); + IMethodBinding methodBinding= lambda.resolveMethodBinding(); + if (methodBinding != null) { + ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); + int index= lambda.parameters().indexOf(declaration); + ITypeBinding typeBinding= parameterTypes[index]; + return typeBinding.getDimensions(); + } + } else { + Type type= getType(declaration); + if (type instanceof ArrayType) { + dim+= ((ArrayType) type).getDimensions(); + } } return dim; } @@ -389,6 +409,17 @@ public static ChildListPropertyDescriptor getBodyDeclarationsProperty(ASTNode no return null; } + /** + * Returns the simple name of the type, followed by array dimensions. + * Skips qualifiers, type arguments, and type annotations. + *

+ * Does not work for WildcardTypes, etc.! + * + * @param type a type that has a simple name + * @return the simple name, followed by array dimensions + * @see #getSimpleNameIdentifier(Name) + * @since 3.10 + */ public static String getTypeName(Type type) { final StringBuffer buffer= new StringBuffer(); ASTVisitor visitor= new ASTVisitor() { @@ -398,24 +429,82 @@ public boolean visit(PrimitiveType node) { return false; } @Override - public boolean visit(SimpleName node) { - buffer.append(node.getIdentifier()); + public boolean visit(SimpleType node) { + buffer.append(getSimpleNameIdentifier(node.getName())); return false; } @Override - public boolean visit(QualifiedName node) { + public boolean visit(QualifiedType node) { buffer.append(node.getName().getIdentifier()); return false; } @Override + public boolean visit(NameQualifiedType node) { + buffer.append(node.getName().getIdentifier()); + return false; + } + @Override + public boolean visit(ParameterizedType node) { + node.getType().accept(this); + return false; + } + @Override public void endVisit(ArrayType node) { - buffer.append("[]"); //$NON-NLS-1$ + for (int i= 0; i < node.dimensions().size(); i++) { + buffer.append("[]"); //$NON-NLS-1$ + } } }; type.accept(visitor); return buffer.toString(); } + /** + * Returns the (potentially qualified) name of a type, followed by array dimensions. + * Skips type arguments and type annotations. + * + * @param type a type that has a name + * @return the name, followed by array dimensions + * @since 3.10 + */ + public static String getQualifiedTypeName(Type type) { + final StringBuffer buffer= new StringBuffer(); + ASTVisitor visitor= new ASTVisitor() { + @Override + public boolean visit(SimpleType node) { + buffer.append(node.getName().getFullyQualifiedName()); + return false; + } + @Override + public boolean visit(QualifiedType node) { + node.getQualifier().accept(this); + buffer.append('.'); + buffer.append(node.getName().getIdentifier()); + return false; + } + @Override + public boolean visit(NameQualifiedType node) { + buffer.append(node.getQualifier().getFullyQualifiedName()); + buffer.append('.'); + buffer.append(node.getName().getIdentifier()); + return false; + } + @Override + public boolean visit(ParameterizedType node) { + node.getType().accept(this); + return false; + } + @Override + public void endVisit(ArrayType node) { + for (int i= 0; i < node.dimensions().size(); i++) { + buffer.append("[]"); //$NON-NLS-1$ + } + } + }; + type.accept(visitor); + return buffer.toString(); + } + public static InfixExpression.Operator convertToInfixOperator(Assignment.Operator operator) { if (operator.equals(Assignment.Operator.PLUS_ASSIGN)) return InfixExpression.Operator.PLUS; @@ -585,6 +674,13 @@ public static ASTNode findParent(ASTNode node, StructuralPropertyDescriptor[][] return null; } + /** + * For {@link Name} or {@link Type} nodes, returns the topmost {@link Type} node + * that shares the same type binding as the given node. + * + * @param node an ASTNode + * @return the normalized {@link Type} node or the original node + */ public static ASTNode getNormalizedNode(ASTNode node) { ASTNode current= node; // normalize name @@ -592,8 +688,9 @@ public static ASTNode getNormalizedNode(ASTNode node) { current= current.getParent(); } // normalize type - if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) || - SimpleType.NAME_PROPERTY.equals(current.getLocationInParent())) { + if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) + || SimpleType.NAME_PROPERTY.equals(current.getLocationInParent()) + || NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) { current= current.getParent(); } // normalize parameterized types @@ -873,23 +970,15 @@ public boolean visit(QualifiedName qualifiedName) { } } - public static SimpleType getLeftMostSimpleType(QualifiedType type) { - final SimpleType[] result= new SimpleType[1]; - ASTVisitor visitor= new ASTVisitor() { - @Override - public boolean visit(QualifiedType qualifiedType) { - Type left= qualifiedType.getQualifier(); - if (left instanceof SimpleType) - result[0]= (SimpleType)left; - else - left.accept(this); - return false; - } - }; - type.accept(visitor); - return result[0]; - } - + /** + * Returns the topmost ancestor of name that is still a {@link Name}. + *

+ * Note: The returned node may resolve to a different binding than the given name! + * + * @param name a name node + * @return the topmost name + * @see #getNormalizedNode(ASTNode) + */ public static Name getTopMostName(Name name) { Name result= name; while(result.getParent() instanceof Name) { @@ -898,12 +987,29 @@ public static Name getTopMostName(Name name) { return result; } - public static Type getTopMostType(Type type) { - Type result= type; - while(result.getParent() instanceof Type) { - result= (Type)result.getParent(); + /** + * Returns the topmost ancestor of node that is a {@link Type} (but not a {@link UnionType}). + *

+ * Note: The returned node often resolves to a different binding than the given node! + * + * @param node the starting node, can be null + * @return the topmost type or null if the node is not a descendant of a type node + * @see #getNormalizedNode(ASTNode) + */ + public static Type getTopMostType(ASTNode node) { + ASTNode result= null; + while (node instanceof Type && !(node instanceof UnionType) + || node instanceof Name + || node instanceof Annotation || node instanceof MemberValuePair + || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation + result= node; + node= node.getParent(); } - return result; + + if (result instanceof Type) + return (Type) result; + + return null; } public static int changeVisibility(int modifiers, int visibility) { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java index 437b7cbaf0..ca98fa129d 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -1084,10 +1084,16 @@ public static ITypeBinding normalizeForDeclarationUse(ITypeBinding binding, AST binding= normalizeTypeBinding(binding); if (binding == null || !binding.isWildcardType()) return binding; - if (binding.isUpperbound()) { - return binding.getBound(); + ITypeBinding bound= binding.getBound(); + if (bound == null || !binding.isUpperbound()) { + ITypeBinding[] typeBounds= binding.getTypeBounds(); + if (typeBounds.length > 0) { + return typeBounds[0]; + } else { + return binding.getErasure(); + } } else { - return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ + return bound; } } @@ -1470,4 +1476,22 @@ public static boolean isNullAnnotation(ITypeBinding annotationType, IJavaProject || qualifiedName.equals(project.getOption(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, true)); } + /** + * Returns the n-th component type of the given type, or null if + * the type binding is not an array type or has not that many dimensions. + * + * @param arrayType an array type binding + * @param n number of dimensions to cut + * @return arrayType with n dimensions removed, or null + * @since 3.10 + */ + public static ITypeBinding getComponentType(ITypeBinding arrayType, int n) { + ITypeBinding type= arrayType; + while (n > 0 && type != null) { + type= type.getComponentType(); + n--; + } + return type; + } + } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/DimensionRewrite.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/DimensionRewrite.java new file mode 100644 index 0000000000..018347e9d3 --- /dev/null +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/DimensionRewrite.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.dom; + +import java.util.ArrayList; +import java.util.List; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ArrayType; +import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; +import org.eclipse.jdt.core.dom.Dimension; +import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + +import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; + +/** + * Rewrite helper for {@link Dimension} node lists and {@link ArrayType}s. + * + * @see JDTUIHelperClasses + * @since 3.10 + */ +public class DimensionRewrite { + + /** + * Creates a {@link ASTRewrite#createCopyTarget(ASTNode) copy} of type + * and adds extraDimensions to it. + * + * @param type the type to copy + * @param extraDimensions the dimensions to add + * @param rewrite the ASTRewrite with which to create new nodes + * @return the copy target with added dimensions + */ + public static Type copyTypeAndAddDimensions(Type type, List extraDimensions, ASTRewrite rewrite) { + AST ast= rewrite.getAST(); + if (extraDimensions.isEmpty()) { + return (Type) rewrite.createCopyTarget(type); + } + + ArrayType result; + if (type instanceof ArrayType) { + ArrayType arrayType= (ArrayType) type; + Type varElementType= (Type) rewrite.createCopyTarget(arrayType.getElementType()); + result= ast.newArrayType(varElementType, 0); + result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); + result.dimensions().addAll(copyDimensions(arrayType.dimensions(), rewrite)); + } else { + Type elementType= (Type) rewrite.createCopyTarget(type); + result= ast.newArrayType(elementType, 0); + result.dimensions().addAll(copyDimensions(extraDimensions, rewrite)); + } + return result; + } + + /** + * Returns {@link ASTRewrite#createCopyTarget(ASTNode) copies} of the given dimensions. + * + * @param dimensions the dimensions to copy + * @param rewrite the ASTRewrite with which to create new nodes + * + * @return list of copy targets + */ + public static List copyDimensions(List dimensions, ASTRewrite rewrite) { + ArrayList result= new ArrayList(); + for (int i= 0; i < dimensions.size(); i++) { + result.add((Dimension) rewrite.createCopyTarget(dimensions.get(i))); + } + return result; + } + + /** + * Removes all children in node's childListProperty. + * + * @param node ASTNode + * @param childListProperty child list property + * @param rewrite rewrite that removes the nodes + * @param editGroup the edit group in which to collect the corresponding text edits, or null if ungrouped + */ + public static void removeAllChildren(ASTNode node, ChildListPropertyDescriptor childListProperty, ASTRewrite rewrite, TextEditGroup editGroup) { + ListRewrite listRewrite= rewrite.getListRewrite(node, childListProperty); + @SuppressWarnings("unchecked") + List children= (List) node.getStructuralProperty(childListProperty); + for (ASTNode child : children) { + listRewrite.remove(child, editGroup); + } + } + +} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java index e2f4e9e005..dd3d032d4e 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -33,11 +33,14 @@ import org.eclipse.jdt.core.dom.ConditionalExpression; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.ContinueStatement; +import org.eclipse.jdt.core.dom.CreationReference; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.DoStatement; import org.eclipse.jdt.core.dom.EmptyStatement; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.FieldDeclaration; @@ -47,8 +50,10 @@ import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.InstanceofExpression; +import org.eclipse.jdt.core.dom.IntersectionType; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.LabeledStatement; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.LineComment; import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.MemberRef; @@ -58,6 +63,7 @@ import org.eclipse.jdt.core.dom.MethodRef; import org.eclipse.jdt.core.dom.MethodRefParameter; import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.NullLiteral; import org.eclipse.jdt.core.dom.NumberLiteral; @@ -78,6 +84,7 @@ import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; +import org.eclipse.jdt.core.dom.SuperMethodReference; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.SynchronizedStatement; @@ -89,6 +96,7 @@ import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeDeclarationStatement; import org.eclipse.jdt.core.dom.TypeLiteral; +import org.eclipse.jdt.core.dom.TypeMethodReference; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.dom.UnionType; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; @@ -147,809 +155,747 @@ protected void endVisitNode(ASTNode node) { } @Override - public boolean visit(AnonymousClassDeclaration node) { - return visitNode(node); + public void endVisit(AnnotationTypeDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(ArrayAccess node) { - return visitNode(node); + public void endVisit(AnnotationTypeMemberDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(ArrayCreation node) { - return visitNode(node); + public void endVisit(AnonymousClassDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(ArrayInitializer node) { - return visitNode(node); + public void endVisit(ArrayAccess node) { + endVisitNode(node); } @Override - public boolean visit(ArrayType node) { - return visitNode(node); + public void endVisit(ArrayCreation node) { + endVisitNode(node); } @Override - public boolean visit(AssertStatement node) { - return visitNode(node); + public void endVisit(ArrayInitializer node) { + endVisitNode(node); } @Override - public boolean visit(Assignment node) { - return visitNode(node); + public void endVisit(ArrayType node) { + endVisitNode(node); } @Override - public boolean visit(Block node) { - return visitNode(node); + public void endVisit(AssertStatement node) { + endVisitNode(node); } @Override - public boolean visit(BooleanLiteral node) { - return visitNode(node); + public void endVisit(Assignment node) { + endVisitNode(node); } @Override - public boolean visit(BreakStatement node) { - return visitNode(node); + public void endVisit(Block node) { + endVisitNode(node); } @Override - public boolean visit(CastExpression node) { - return visitNode(node); + public void endVisit(BlockComment node) { + endVisitNode(node); } @Override - public boolean visit(CatchClause node) { - return visitNode(node); + public void endVisit(BooleanLiteral node) { + endVisitNode(node); } @Override - public boolean visit(CharacterLiteral node) { - return visitNode(node); + public void endVisit(BreakStatement node) { + endVisitNode(node); } @Override - public boolean visit(ClassInstanceCreation node) { - return visitNode(node); + public void endVisit(CastExpression node) { + endVisitNode(node); } @Override - public boolean visit(CompilationUnit node) { - return visitNode(node); + public void endVisit(CatchClause node) { + endVisitNode(node); } @Override - public boolean visit(ConditionalExpression node) { - return visitNode(node); + public void endVisit(CharacterLiteral node) { + endVisitNode(node); } @Override - public boolean visit(ConstructorInvocation node) { - return visitNode(node); + public void endVisit(ClassInstanceCreation node) { + endVisitNode(node); } @Override - public boolean visit(ContinueStatement node) { - return visitNode(node); + public void endVisit(CompilationUnit node) { + endVisitNode(node); } @Override - public boolean visit(DoStatement node) { - return visitNode(node); + public void endVisit(ConditionalExpression node) { + endVisitNode(node); } @Override - public boolean visit(EmptyStatement node) { - return visitNode(node); + public void endVisit(ConstructorInvocation node) { + endVisitNode(node); } @Override - public boolean visit(ExpressionStatement node) { - return visitNode(node); + public void endVisit(ContinueStatement node) { + endVisitNode(node); } @Override - public boolean visit(FieldAccess node) { - return visitNode(node); + public void endVisit(CreationReference node) { + endVisitNode(node); } @Override - public boolean visit(FieldDeclaration node) { - return visitNode(node); + public void endVisit(Dimension node) { + endVisitNode(node); } @Override - public boolean visit(ForStatement node) { - return visitNode(node); + public void endVisit(DoStatement node) { + endVisitNode(node); } @Override - public boolean visit(IfStatement node) { - return visitNode(node); + public void endVisit(EmptyStatement node) { + endVisitNode(node); } @Override - public boolean visit(ImportDeclaration node) { - return visitNode(node); + public void endVisit(EnhancedForStatement node) { + endVisitNode(node); } @Override - public boolean visit(InfixExpression node) { - return visitNode(node); + public void endVisit(EnumConstantDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(InstanceofExpression node) { - return visitNode(node); + public void endVisit(EnumDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(Initializer node) { - return visitNode(node); + public void endVisit(ExpressionMethodReference node) { + endVisitNode(node); } @Override - public boolean visit(Javadoc node) { - if (super.visit(node)) - return visitNode(node); - else - return false; + public void endVisit(ExpressionStatement node) { + endVisitNode(node); } @Override - public boolean visit(LabeledStatement node) { - return visitNode(node); + public void endVisit(FieldAccess node) { + endVisitNode(node); } @Override - public boolean visit(MethodDeclaration node) { - return visitNode(node); + public void endVisit(FieldDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(MethodInvocation node) { - return visitNode(node); + public void endVisit(ForStatement node) { + endVisitNode(node); } @Override - public boolean visit(NullLiteral node) { - return visitNode(node); + public void endVisit(IfStatement node) { + endVisitNode(node); } @Override - public boolean visit(NumberLiteral node) { - return visitNode(node); + public void endVisit(ImportDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(PackageDeclaration node) { - return visitNode(node); + public void endVisit(InfixExpression node) { + endVisitNode(node); } @Override - public boolean visit(ParenthesizedExpression node) { - return visitNode(node); + public void endVisit(Initializer node) { + endVisitNode(node); } @Override - public boolean visit(PostfixExpression node) { - return visitNode(node); + public void endVisit(InstanceofExpression node) { + endVisitNode(node); } @Override - public boolean visit(PrefixExpression node) { - return visitNode(node); + public void endVisit(IntersectionType node) { + endVisitNode(node); } @Override - public boolean visit(PrimitiveType node) { - return visitNode(node); + public void endVisit(Javadoc node) { + endVisitNode(node); } @Override - public boolean visit(QualifiedName node) { - return visitNode(node); + public void endVisit(LabeledStatement node) { + endVisitNode(node); } @Override - public boolean visit(ReturnStatement node) { - return visitNode(node); + public void endVisit(LambdaExpression node) { + endVisitNode(node); } @Override - public boolean visit(SimpleName node) { - return visitNode(node); + public void endVisit(LineComment node) { + endVisitNode(node); } @Override - public boolean visit(SimpleType node) { - return visitNode(node); + public void endVisit(MarkerAnnotation node) { + endVisitNode(node); } @Override - public boolean visit(StringLiteral node) { - return visitNode(node); + public void endVisit(MemberRef node) { + endVisitNode(node); } @Override - public boolean visit(SuperConstructorInvocation node) { - return visitNode(node); + public void endVisit(MemberValuePair node) { + endVisitNode(node); } @Override - public boolean visit(SuperFieldAccess node) { - return visitNode(node); + public void endVisit(MethodDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(SuperMethodInvocation node) { - return visitNode(node); + public void endVisit(MethodInvocation node) { + endVisitNode(node); } @Override - public boolean visit(SwitchCase node) { - return visitNode(node); + public void endVisit(MethodRef node) { + endVisitNode(node); } @Override - public boolean visit(SwitchStatement node) { - return visitNode(node); + public void endVisit(MethodRefParameter node) { + endVisitNode(node); } @Override - public boolean visit(SynchronizedStatement node) { - return visitNode(node); + public void endVisit(Modifier node) { + endVisitNode(node); } @Override - public boolean visit(ThisExpression node) { - return visitNode(node); + public void endVisit(NameQualifiedType node) { + endVisitNode(node); } + @Override - public boolean visit(ThrowStatement node) { - return visitNode(node); + public void endVisit(NormalAnnotation node) { + endVisitNode(node); } @Override - public boolean visit(TryStatement node) { - return visitNode(node); + public void endVisit(NullLiteral node) { + endVisitNode(node); } @Override - public boolean visit(TypeDeclaration node) { - return visitNode(node); + public void endVisit(NumberLiteral node) { + endVisitNode(node); } @Override - public boolean visit(TypeDeclarationStatement node) { - return visitNode(node); + public void endVisit(PackageDeclaration node) { + endVisitNode(node); } @Override - public boolean visit(TypeLiteral node) { - return visitNode(node); + public void endVisit(ParameterizedType node) { + endVisitNode(node); } @Override - public boolean visit(UnionType node) { - return visitNode(node); + public void endVisit(ParenthesizedExpression node) { + endVisitNode(node); } @Override - public boolean visit(SingleVariableDeclaration node) { - return visitNode(node); + public void endVisit(PostfixExpression node) { + endVisitNode(node); } @Override - public boolean visit(VariableDeclarationExpression node) { - return visitNode(node); + public void endVisit(PrefixExpression node) { + endVisitNode(node); } @Override - public boolean visit(VariableDeclarationStatement node) { - return visitNode(node); + public void endVisit(PrimitiveType node) { + endVisitNode(node); } @Override - public boolean visit(VariableDeclarationFragment node) { - return visitNode(node); + public void endVisit(QualifiedName node) { + endVisitNode(node); } @Override - public boolean visit(WhileStatement node) { - return visitNode(node); + public void endVisit(QualifiedType node) { + endVisitNode(node); } - - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) - */ @Override - public boolean visit(AnnotationTypeDeclaration node) { - return visitNode(node); + public void endVisit(ReturnStatement node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) - */ @Override - public boolean visit(AnnotationTypeMemberDeclaration node) { - return visitNode(node); + public void endVisit(SimpleName node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.BlockComment) - */ @Override - public boolean visit(BlockComment node) { - return visitNode(node); + public void endVisit(SimpleType node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnhancedForStatement) - */ @Override - public boolean visit(EnhancedForStatement node) { - return visitNode(node); + public void endVisit(SingleMemberAnnotation node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumConstantDeclaration) - */ @Override - public boolean visit(EnumConstantDeclaration node) { - return visitNode(node); + public void endVisit(SingleVariableDeclaration node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.EnumDeclaration) - */ @Override - public boolean visit(EnumDeclaration node) { - return visitNode(node); + public void endVisit(StringLiteral node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.LineComment) - */ @Override - public boolean visit(LineComment node) { - return visitNode(node); + public void endVisit(SuperConstructorInvocation node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MarkerAnnotation) - */ @Override - public boolean visit(MarkerAnnotation node) { - return visitNode(node); + public void endVisit(SuperFieldAccess node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberRef) - */ @Override - public boolean visit(MemberRef node) { - return visitNode(node); + public void endVisit(SuperMethodInvocation node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MemberValuePair) - */ @Override - public boolean visit(MemberValuePair node) { - return visitNode(node); + public void endVisit(SuperMethodReference node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRef) - */ @Override - public boolean visit(MethodRef node) { - return visitNode(node); + public void endVisit(SwitchCase node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodRefParameter) - */ @Override - public boolean visit(MethodRefParameter node) { - return visitNode(node); + public void endVisit(SwitchStatement node) { + endVisitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.Modifier) - */ @Override - public boolean visit(Modifier node) { + public void endVisit(SynchronizedStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(TagElement node) { + endVisitNode(node); + } + @Override + public void endVisit(TextElement node) { + endVisitNode(node); + } + @Override + public void endVisit(ThisExpression node) { + endVisitNode(node); + } + @Override + public void endVisit(ThrowStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(TryStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(TypeDeclaration node) { + endVisitNode(node); + } + @Override + public void endVisit(TypeDeclarationStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(TypeLiteral node) { + endVisitNode(node); + } + @Override + public void endVisit(TypeMethodReference node) { + endVisitNode(node); + } + @Override + public void endVisit(TypeParameter node) { + endVisitNode(node); + } + @Override + public void endVisit(UnionType node) { + endVisitNode(node); + } + @Override + public void endVisit(VariableDeclarationExpression node) { + endVisitNode(node); + } + @Override + public void endVisit(VariableDeclarationFragment node) { + endVisitNode(node); + } + @Override + public void endVisit(VariableDeclarationStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(WhileStatement node) { + endVisitNode(node); + } + @Override + public void endVisit(WildcardType node) { + endVisitNode(node); + } + + @Override + public boolean visit(AnnotationTypeDeclaration node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.NormalAnnotation) - */ @Override - public boolean visit(NormalAnnotation node) { + public boolean visit(AnnotationTypeMemberDeclaration node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.ParameterizedType) - */ @Override - public boolean visit(ParameterizedType node) { + public boolean visit(AnonymousClassDeclaration node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.QualifiedType) - */ @Override - public boolean visit(QualifiedType node) { + public boolean visit(ArrayAccess node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.SingleMemberAnnotation) - */ @Override - public boolean visit(SingleMemberAnnotation node) { + public boolean visit(ArrayCreation node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TagElement) - */ @Override - public boolean visit(TagElement node) { + public boolean visit(ArrayInitializer node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TextElement) - */ @Override - public boolean visit(TextElement node) { + public boolean visit(ArrayType node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.TypeParameter) - */ @Override - public boolean visit(TypeParameter node) { + public boolean visit(AssertStatement node) { return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.WildcardType) - */ @Override - public boolean visit(WildcardType node) { + public boolean visit(Assignment node) { return visitNode(node); } - @Override - public void endVisit(AnonymousClassDeclaration node) { - endVisitNode(node); + public boolean visit(Block node) { + return visitNode(node); } @Override - public void endVisit(ArrayAccess node) { - endVisitNode(node); + public boolean visit(BlockComment node) { + return visitNode(node); } @Override - public void endVisit(ArrayCreation node) { - endVisitNode(node); + public boolean visit(BooleanLiteral node) { + return visitNode(node); } @Override - public void endVisit(ArrayInitializer node) { - endVisitNode(node); + public boolean visit(BreakStatement node) { + return visitNode(node); } @Override - public void endVisit(ArrayType node) { - endVisitNode(node); + public boolean visit(CastExpression node) { + return visitNode(node); } @Override - public void endVisit(AssertStatement node) { - endVisitNode(node); + public boolean visit(CatchClause node) { + return visitNode(node); } @Override - public void endVisit(Assignment node) { - endVisitNode(node); + public boolean visit(CharacterLiteral node) { + return visitNode(node); } @Override - public void endVisit(Block node) { - endVisitNode(node); + public boolean visit(ClassInstanceCreation node) { + return visitNode(node); } @Override - public void endVisit(BooleanLiteral node) { - endVisitNode(node); + public boolean visit(CompilationUnit node) { + return visitNode(node); } @Override - public void endVisit(BreakStatement node) { - endVisitNode(node); + public boolean visit(ConditionalExpression node) { + return visitNode(node); } @Override - public void endVisit(CastExpression node) { - endVisitNode(node); + public boolean visit(ConstructorInvocation node) { + return visitNode(node); } @Override - public void endVisit(CatchClause node) { - endVisitNode(node); + public boolean visit(ContinueStatement node) { + return visitNode(node); } @Override - public void endVisit(CharacterLiteral node) { - endVisitNode(node); + public boolean visit(CreationReference node) { + return visitNode(node); } @Override - public void endVisit(ClassInstanceCreation node) { - endVisitNode(node); + public boolean visit(Dimension node) { + return visitNode(node); } @Override - public void endVisit(CompilationUnit node) { - endVisitNode(node); + public boolean visit(DoStatement node) { + return visitNode(node); } @Override - public void endVisit(ConditionalExpression node) { - endVisitNode(node); + public boolean visit(EmptyStatement node) { + return visitNode(node); } @Override - public void endVisit(ConstructorInvocation node) { - endVisitNode(node); + public boolean visit(EnhancedForStatement node) { + return visitNode(node); } @Override - public void endVisit(ContinueStatement node) { - endVisitNode(node); + public boolean visit(EnumConstantDeclaration node) { + return visitNode(node); } @Override - public void endVisit(DoStatement node) { - endVisitNode(node); + public boolean visit(EnumDeclaration node) { + return visitNode(node); } @Override - public void endVisit(EmptyStatement node) { - endVisitNode(node); + public boolean visit(ExpressionMethodReference node) { + return visitNode(node); } @Override - public void endVisit(ExpressionStatement node) { - endVisitNode(node); + public boolean visit(ExpressionStatement node) { + return visitNode(node); } @Override - public void endVisit(FieldAccess node) { - endVisitNode(node); + public boolean visit(FieldAccess node) { + return visitNode(node); } @Override - public void endVisit(FieldDeclaration node) { - endVisitNode(node); + public boolean visit(FieldDeclaration node) { + return visitNode(node); } @Override - public void endVisit(ForStatement node) { - endVisitNode(node); + public boolean visit(ForStatement node) { + return visitNode(node); } @Override - public void endVisit(IfStatement node) { - endVisitNode(node); + public boolean visit(IfStatement node) { + return visitNode(node); } @Override - public void endVisit(ImportDeclaration node) { - endVisitNode(node); + public boolean visit(ImportDeclaration node) { + return visitNode(node); } @Override - public void endVisit(InfixExpression node) { - endVisitNode(node); + public boolean visit(InfixExpression node) { + return visitNode(node); } @Override - public void endVisit(InstanceofExpression node) { - endVisitNode(node); + public boolean visit(Initializer node) { + return visitNode(node); } @Override - public void endVisit(Initializer node) { - endVisitNode(node); + public boolean visit(InstanceofExpression node) { + return visitNode(node); } @Override - public void endVisit(Javadoc node) { - endVisitNode(node); + public boolean visit(IntersectionType node) { + return visitNode(node); } @Override - public void endVisit(LabeledStatement node) { - endVisitNode(node); + public boolean visit(Javadoc node) { + if (super.visit(node)) + return visitNode(node); + else + return false; } @Override - public void endVisit(MethodDeclaration node) { - endVisitNode(node); + public boolean visit(LabeledStatement node) { + return visitNode(node); } @Override - public void endVisit(MethodInvocation node) { - endVisitNode(node); + public boolean visit(LambdaExpression node) { + return visitNode(node); } @Override - public void endVisit(NullLiteral node) { - endVisitNode(node); + public boolean visit(LineComment node) { + return visitNode(node); } @Override - public void endVisit(NumberLiteral node) { - endVisitNode(node); + public boolean visit(MarkerAnnotation node) { + return visitNode(node); } @Override - public void endVisit(PackageDeclaration node) { - endVisitNode(node); + public boolean visit(MemberRef node) { + return visitNode(node); } @Override - public void endVisit(ParenthesizedExpression node) { - endVisitNode(node); + public boolean visit(MemberValuePair node) { + return visitNode(node); } @Override - public void endVisit(PostfixExpression node) { - endVisitNode(node); + public boolean visit(MethodDeclaration node) { + return visitNode(node); } @Override - public void endVisit(PrefixExpression node) { - endVisitNode(node); + public boolean visit(MethodInvocation node) { + return visitNode(node); } @Override - public void endVisit(PrimitiveType node) { - endVisitNode(node); + public boolean visit(MethodRef node) { + return visitNode(node); } @Override - public void endVisit(QualifiedName node) { - endVisitNode(node); + public boolean visit(MethodRefParameter node) { + return visitNode(node); } @Override - public void endVisit(ReturnStatement node) { - endVisitNode(node); + public boolean visit(Modifier node) { + return visitNode(node); } @Override - public void endVisit(SimpleName node) { - endVisitNode(node); + public boolean visit(NameQualifiedType node) { + return visitNode(node); } + @Override - public void endVisit(SimpleType node) { - endVisitNode(node); + public boolean visit(NormalAnnotation node) { + return visitNode(node); } @Override - public void endVisit(StringLiteral node) { - endVisitNode(node); + public boolean visit(NullLiteral node) { + return visitNode(node); } @Override - public void endVisit(SuperConstructorInvocation node) { - endVisitNode(node); + public boolean visit(NumberLiteral node) { + return visitNode(node); } @Override - public void endVisit(SuperFieldAccess node) { - endVisitNode(node); + public boolean visit(PackageDeclaration node) { + return visitNode(node); } @Override - public void endVisit(SuperMethodInvocation node) { - endVisitNode(node); + public boolean visit(ParameterizedType node) { + return visitNode(node); } @Override - public void endVisit(SwitchCase node) { - endVisitNode(node); + public boolean visit(ParenthesizedExpression node) { + return visitNode(node); } @Override - public void endVisit(SwitchStatement node) { - endVisitNode(node); + public boolean visit(PostfixExpression node) { + return visitNode(node); } @Override - public void endVisit(SynchronizedStatement node) { - endVisitNode(node); + public boolean visit(PrefixExpression node) { + return visitNode(node); } @Override - public void endVisit(ThisExpression node) { - endVisitNode(node); + public boolean visit(PrimitiveType node) { + return visitNode(node); } @Override - public void endVisit(ThrowStatement node) { - endVisitNode(node); + public boolean visit(QualifiedName node) { + return visitNode(node); } @Override - public void endVisit(TryStatement node) { - endVisitNode(node); + public boolean visit(QualifiedType node) { + return visitNode(node); } @Override - public void endVisit(TypeDeclaration node) { - endVisitNode(node); + public boolean visit(ReturnStatement node) { + return visitNode(node); } @Override - public void endVisit(TypeDeclarationStatement node) { - endVisitNode(node); + public boolean visit(SimpleName node) { + return visitNode(node); } @Override - public void endVisit(TypeLiteral node) { - endVisitNode(node); + public boolean visit(SimpleType node) { + return visitNode(node); } @Override - public void endVisit(UnionType node) { - endVisitNode(node); + public boolean visit(SingleMemberAnnotation node) { + return visitNode(node); } @Override - public void endVisit(SingleVariableDeclaration node) { - endVisitNode(node); + public boolean visit(SingleVariableDeclaration node) { + return visitNode(node); } @Override - public void endVisit(VariableDeclarationExpression node) { - endVisitNode(node); + public boolean visit(StringLiteral node) { + return visitNode(node); } @Override - public void endVisit(VariableDeclarationStatement node) { - endVisitNode(node); + public boolean visit(SuperConstructorInvocation node) { + return visitNode(node); } @Override - public void endVisit(VariableDeclarationFragment node) { - endVisitNode(node); + public boolean visit(SuperFieldAccess node) { + return visitNode(node); } @Override - public void endVisit(WhileStatement node) { - endVisitNode(node); + public boolean visit(SuperMethodInvocation node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.AnnotationTypeDeclaration) - */ - @Override - public void endVisit(AnnotationTypeDeclaration node) { - endVisitNode(node); - } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration) - */ @Override - public void endVisit(AnnotationTypeMemberDeclaration node) { - endVisitNode(node); + public boolean visit(SuperMethodReference node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.BlockComment) - */ @Override - public void endVisit(BlockComment node) { - endVisitNode(node); + public boolean visit(SwitchCase node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnhancedForStatement) - */ @Override - public void endVisit(EnhancedForStatement node) { - endVisitNode(node); + public boolean visit(SwitchStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnumConstantDeclaration) - */ @Override - public void endVisit(EnumConstantDeclaration node) { - endVisitNode(node); + public boolean visit(SynchronizedStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.EnumDeclaration) - */ @Override - public void endVisit(EnumDeclaration node) { - endVisitNode(node); + public boolean visit(TagElement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.LineComment) - */ @Override - public void endVisit(LineComment node) { - endVisitNode(node); + public boolean visit(TextElement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MarkerAnnotation) - */ @Override - public void endVisit(MarkerAnnotation node) { - endVisitNode(node); + public boolean visit(ThisExpression node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MemberRef) - */ @Override - public void endVisit(MemberRef node) { - endVisitNode(node); + public boolean visit(ThrowStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MemberValuePair) - */ @Override - public void endVisit(MemberValuePair node) { - endVisitNode(node); + public boolean visit(TryStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MethodRef) - */ @Override - public void endVisit(MethodRef node) { - endVisitNode(node); + public boolean visit(TypeDeclaration node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.MethodRefParameter) - */ @Override - public void endVisit(MethodRefParameter node) { - endVisitNode(node); + public boolean visit(TypeDeclarationStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.Modifier) - */ @Override - public void endVisit(Modifier node) { - endVisitNode(node); + public boolean visit(TypeLiteral node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.NormalAnnotation) - */ @Override - public void endVisit(NormalAnnotation node) { - endVisitNode(node); + public boolean visit(TypeMethodReference node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.ParameterizedType) - */ @Override - public void endVisit(ParameterizedType node) { - endVisitNode(node); + public boolean visit(TypeParameter node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.QualifiedType) - */ @Override - public void endVisit(QualifiedType node) { - endVisitNode(node); + public boolean visit(UnionType node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.SingleMemberAnnotation) - */ @Override - public void endVisit(SingleMemberAnnotation node) { - endVisitNode(node); + public boolean visit(VariableDeclarationExpression node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TagElement) - */ @Override - public void endVisit(TagElement node) { - endVisitNode(node); + public boolean visit(VariableDeclarationFragment node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TextElement) - */ @Override - public void endVisit(TextElement node) { - endVisitNode(node); + public boolean visit(VariableDeclarationStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.TypeParameter) - */ @Override - public void endVisit(TypeParameter node) { - endVisitNode(node); + public boolean visit(WhileStatement node) { + return visitNode(node); } - /* (non-Javadoc) - * @see org.eclipse.jdt.core.dom.ASTVisitor#endVisit(org.eclipse.jdt.core.dom.WildcardType) - */ @Override - public void endVisit(WildcardType node) { - endVisitNode(node); + public boolean visit(WildcardType node) { + return visitNode(node); } - } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java index 0287a380cd..d332bab084 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -10,101 +10,7 @@ *******************************************************************************/ package org.eclipse.jdt.internal.corext.dom; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; -import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayAccess; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.AssertStatement; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BlockComment; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.BooleanLiteral; -import org.eclipse.jdt.core.dom.BreakStatement; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CatchClause; -import org.eclipse.jdt.core.dom.CharacterLiteral; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.Comment; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ConditionalExpression; -import org.eclipse.jdt.core.dom.ConstructorInvocation; -import org.eclipse.jdt.core.dom.ContinueStatement; -import org.eclipse.jdt.core.dom.DoStatement; -import org.eclipse.jdt.core.dom.EmptyStatement; -import org.eclipse.jdt.core.dom.EnhancedForStatement; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IfStatement; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.InfixExpression; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.InstanceofExpression; -import org.eclipse.jdt.core.dom.Javadoc; -import org.eclipse.jdt.core.dom.LabeledStatement; -import org.eclipse.jdt.core.dom.LineComment; -import org.eclipse.jdt.core.dom.MarkerAnnotation; -import org.eclipse.jdt.core.dom.MemberRef; -import org.eclipse.jdt.core.dom.MemberValuePair; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodRef; -import org.eclipse.jdt.core.dom.MethodRefParameter; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.NormalAnnotation; -import org.eclipse.jdt.core.dom.NullLiteral; -import org.eclipse.jdt.core.dom.NumberLiteral; -import org.eclipse.jdt.core.dom.PackageDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PostfixExpression; -import org.eclipse.jdt.core.dom.PrefixExpression; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.ReturnStatement; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleMemberAnnotation; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.SynchronizedStatement; -import org.eclipse.jdt.core.dom.TagElement; -import org.eclipse.jdt.core.dom.TextElement; -import org.eclipse.jdt.core.dom.ThisExpression; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.TryStatement; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.TypeDeclarationStatement; -import org.eclipse.jdt.core.dom.TypeLiteral; -import org.eclipse.jdt.core.dom.TypeParameter; -import org.eclipse.jdt.core.dom.UnionType; -import org.eclipse.jdt.core.dom.VariableDeclaration; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; -import org.eclipse.jdt.core.dom.WhileStatement; -import org.eclipse.jdt.core.dom.WildcardType; +import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; @@ -362,6 +268,16 @@ public void endVisit(CompilationUnit node) { endVisit((ASTNode)node); } + @Override + public boolean visit(Dimension node) { + return visit((ASTNode)node); + } + + @Override + public void endVisit(Dimension node) { + endVisit((ASTNode)node); + } + //---- Begin Expression Hierarchy ---------------------------------- public boolean visit(Expression node) { return visit((ASTNode)node); @@ -532,6 +448,16 @@ public void endVisit(InstanceofExpression node) { endVisit((Expression)node); } + @Override + public boolean visit(LambdaExpression node) { + return visit((Expression)node); + } + + @Override + public void endVisit(LambdaExpression node) { + endVisit((Expression)node); + } + @Override public boolean visit(MethodInvocation node) { return visit((Expression)node); @@ -542,6 +468,57 @@ public void endVisit(MethodInvocation node) { endVisit((Expression)node); } + //---- Begin MethodReference Hierarchy ---------------------------------- + public boolean visit(MethodReference node) { + return visit((Expression)node); + } + + public void endVisit(MethodReference node) { + endVisit((Expression)node); + } + + @Override + public boolean visit(CreationReference node) { + return visit((MethodReference)node); + } + + @Override + public void endVisit(CreationReference node) { + endVisit((MethodReference)node); + } + + @Override + public boolean visit(ExpressionMethodReference node) { + return visit((MethodReference)node); + } + + @Override + public void endVisit(ExpressionMethodReference node) { + endVisit((MethodReference)node); + } + + @Override + public boolean visit(SuperMethodReference node) { + return visit((MethodReference)node); + } + + @Override + public void endVisit(SuperMethodReference node) { + endVisit((MethodReference)node); + } + + @Override + public boolean visit(TypeMethodReference node) { + return visit((MethodReference)node); + } + + @Override + public void endVisit(TypeMethodReference node) { + endVisit((MethodReference)node); + } + + //---- End MethodReference Hierarchy ------------------------------------ + //---- Begin Name Hierarchy ---------------------------------- public boolean visit(Name node) { return visit((Expression)node); @@ -1017,63 +994,93 @@ public void endVisit(Type node) { endVisit((ASTNode)node); } - @Override - public boolean visit(ArrayType node) { +//---- Begin Annotatable Type Hierarchy -------------------------------------- + public boolean visit(AnnotatableType node) { return visit((Type)node); } - - @Override - public void endVisit(ArrayType node) { + + public void endVisit(AnnotatableType node) { endVisit((Type)node); } @Override - public boolean visit(ParameterizedType node) { - return visit((Type)node); + public boolean visit(NameQualifiedType node) { + return visit((AnnotatableType)node); } @Override - public void endVisit(ParameterizedType node) { - endVisit((Type)node); + public void endVisit(NameQualifiedType node) { + endVisit((AnnotatableType)node); } @Override public boolean visit(PrimitiveType node) { - return visit((Type)node); + return visit((AnnotatableType)node); } @Override public void endVisit(PrimitiveType node) { - endVisit((Type)node); + endVisit((AnnotatableType)node); } @Override public boolean visit(QualifiedType node) { - return visit((Type)node); + return visit((AnnotatableType)node); } @Override public void endVisit(QualifiedType node) { - endVisit((Type)node); + endVisit((AnnotatableType)node); } @Override public boolean visit(SimpleType node) { - return visit((Type)node); + return visit((AnnotatableType)node); } @Override public void endVisit(SimpleType node) { - endVisit((Type)node); + endVisit((AnnotatableType)node); } @Override public boolean visit(WildcardType node) { - return visit((Type)node); + return visit((AnnotatableType)node); } @Override public void endVisit(WildcardType node) { + endVisit((AnnotatableType)node); + } +//---- End Annotatable Type Hierarchy -------------------------------------- + + @Override + public boolean visit(ArrayType node) { + return visit((Type)node); + } + + @Override + public void endVisit(ArrayType node) { + endVisit((Type)node); + } + + @Override + public boolean visit(IntersectionType node) { + return visit((Type)node); + } + + @Override + public void endVisit(IntersectionType node) { + endVisit((Type)node); + } + + @Override + public boolean visit(ParameterizedType node) { + return visit((Type)node); + } + + @Override + public void endVisit(ParameterizedType node) { endVisit((Type)node); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java index 4fd38c2162..db34228722 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,6 +25,7 @@ import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; +import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; @@ -32,6 +33,7 @@ import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.Initializer; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; @@ -694,6 +696,16 @@ public boolean visit(Initializer node) { return !fBreak && isInside(node); } + @Override + public boolean visit(FieldDeclaration node) { + return !fBreak && isInside(node); + } + + @Override + public boolean visit(LambdaExpression node) { + return !fBreak && isInside(node); + } + @Override public boolean visit(Statement node) { return !fBreak && isInside(node); @@ -820,7 +832,7 @@ private boolean addLocalDeclarations(ASTNode node, int flags, IBindingRequestor private boolean addLocalDeclarations(ASTNode node, int offset, int flags, IBindingRequestor requestor) { if (hasFlag(VARIABLES, flags) || hasFlag(TYPES, flags)) { BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); - if (declaration instanceof MethodDeclaration || declaration instanceof Initializer) { + if (declaration instanceof MethodDeclaration || declaration instanceof Initializer || declaration instanceof FieldDeclaration) { ScopeAnalyzerVisitor visitor= new ScopeAnalyzerVisitor(offset, flags, requestor); declaration.accept(visitor); return visitor.fBreak; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java index 7671440b50..69b4c97b45 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpConstants.java @@ -643,6 +643,44 @@ public class CleanUpConstants { */ public static final String VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES= "cleanup.make_local_variable_final"; //$NON-NLS-1$ + /** + * Controls conversion between lambda expressions and anonymous class creations. + * For detailed settings, use {@link #USE_LAMBDA} or {@link #USE_ANONYMOUS_CLASS_CREATION} + *

+ * Possible values: {TRUE, FALSE} + * + * @see CleanUpOptions#TRUE + * @see CleanUpOptions#FALSE + * @since 3.3 + */ + public static final String CONVERT_FUNCTIONAL_INTERFACES= "cleanup.convert_functional_interfaces"; //$NON-NLS-1$ + + /** + * Replaces anonymous class creations with lambda expressions where possible in Java 8 source. + *

+ * Possible values: {TRUE, FALSE} + *

+ * Only has an effect if {@link #CONVERT_FUNCTIONAL_INTERFACES} is TRUE. + * + * @see CleanUpOptions#TRUE + * @see CleanUpOptions#FALSE + * @since 3.10 + */ + public static final String USE_LAMBDA= "cleanup.use_lambda"; //$NON-NLS-1$ + + /** + * Replaces lambda expressions with anonymous class creations. + *

+ * Possible values: {TRUE, FALSE} + *

+ * Only has an effect if {@link #CONVERT_FUNCTIONAL_INTERFACES} is TRUE. + * + * @see CleanUpOptions#TRUE + * @see CleanUpOptions#FALSE + * @since 3.10 + */ + public static final String USE_ANONYMOUS_CLASS_CREATION= "cleanup.use_anonymous_class_creation"; //$NON-NLS-1$ + /** * Adds type parameters to raw type references. *

@@ -652,9 +690,7 @@ public class CleanUpConstants { * List l; -> List<Object> l; * * - * Possible values: {TRUE, FALSE}
- * Default value: Not set
- *
+ * Possible values: {TRUE, FALSE} * * @see CleanUpOptions#TRUE * @see CleanUpOptions#FALSE @@ -1136,6 +1172,11 @@ private static void setEclipseDefaultSettings(CleanUpOptions options) { options.setOption(VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpOptions.FALSE); options.setOption(VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, CleanUpOptions.TRUE); + //Functional Interfaces + options.setOption(CONVERT_FUNCTIONAL_INTERFACES, CleanUpOptions.FALSE); + options.setOption(USE_LAMBDA, CleanUpOptions.TRUE); + options.setOption(USE_ANONYMOUS_CLASS_CREATION, CleanUpOptions.FALSE); + //Unused Code options.setOption(REMOVE_UNUSED_CODE_IMPORTS, CleanUpOptions.TRUE); options.setOption(REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpOptions.FALSE); @@ -1216,6 +1257,11 @@ private static void setSaveParticipantSettings(CleanUpOptions options) { options.setOption(VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpOptions.FALSE); options.setOption(VARIABLE_DECLARATIONS_USE_FINAL_PRIVATE_FIELDS, CleanUpOptions.TRUE); + //Functional Interfaces + options.setOption(CONVERT_FUNCTIONAL_INTERFACES, CleanUpOptions.FALSE); + options.setOption(USE_LAMBDA, CleanUpOptions.TRUE); + options.setOption(USE_ANONYMOUS_CLASS_CREATION, CleanUpOptions.FALSE); + //Unused Code options.setOption(REMOVE_UNUSED_CODE_IMPORTS, CleanUpOptions.FALSE); options.setOption(REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpOptions.FALSE); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRegistry.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRegistry.java index d3e696bd9b..1e0de6fabd 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRegistry.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRegistry.java @@ -46,6 +46,7 @@ import org.eclipse.jdt.internal.ui.fix.MapCleanUpOptions; import org.eclipse.jdt.internal.ui.preferences.cleanup.CleanUpTabPage; import org.eclipse.jdt.internal.ui.preferences.cleanup.ContributedCleanUpTabPage; +import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * The clean up registry provides a set of clean ups and there corresponding UI representatives. @@ -68,6 +69,7 @@ public Composite createContents(Composite parent) { result.setLayout(new GridLayout(1, false)); Text text= new Text(result, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY); + SWTUtil.fixReadonlyTextBackground(text); text.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false)); text.setText(Messages.format(FixMessages.CleanUpRegistry_ErrorTabPage_description, fException.getLocalizedMessage())); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java index 91d47c6775..a8aa6dc97c 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -694,7 +694,8 @@ public static boolean isIndirectStaticAccess(IProblemLocation problem) { public static boolean isNonStaticAccess(IProblemLocation problem) { return (problem.getProblemId() == IProblem.NonStaticAccessToStaticField - || problem.getProblemId() == IProblem.NonStaticAccessToStaticMethod); + || problem.getProblemId() == IProblem.NonStaticAccessToStaticMethod + || problem.getProblemId() == IProblem.NonStaticOrAlienTypeReceiver); } private static ToStaticAccessOperation[] createToStaticAccessOperations(CompilationUnit astRoot, HashMap createdBlocks, IProblemLocation problem, boolean conservative) { @@ -706,26 +707,18 @@ private static ToStaticAccessOperation[] createToStaticAccessOperations(Compilat Expression qualifier= null; IBinding accessBinding= null; - if (selectedNode instanceof QualifiedName) { - QualifiedName name= (QualifiedName) selectedNode; - qualifier= name.getQualifier(); - accessBinding= name.resolveBinding(); - } else if (selectedNode instanceof SimpleName) { - ASTNode parent= selectedNode.getParent(); - if (parent instanceof FieldAccess) { - FieldAccess fieldAccess= (FieldAccess) parent; - qualifier= fieldAccess.getExpression(); - accessBinding= fieldAccess.getName().resolveBinding(); - } else if (parent instanceof QualifiedName) { - QualifiedName qualifiedName= (QualifiedName) parent; - qualifier= qualifiedName.getQualifier(); - accessBinding= qualifiedName.getName().resolveBinding(); - } - } else if (selectedNode instanceof MethodInvocation) { - MethodInvocation methodInvocation= (MethodInvocation) selectedNode; - qualifier= methodInvocation.getExpression(); - accessBinding= methodInvocation.getName().resolveBinding(); - } else if (selectedNode instanceof FieldAccess) { + if (selectedNode instanceof SimpleName) { + selectedNode= selectedNode.getParent(); + } + if (selectedNode instanceof QualifiedName) { + QualifiedName name= (QualifiedName) selectedNode; + qualifier= name.getQualifier(); + accessBinding= name.resolveBinding(); + } else if (selectedNode instanceof MethodInvocation) { + MethodInvocation methodInvocation= (MethodInvocation) selectedNode; + qualifier= methodInvocation.getExpression(); + accessBinding= methodInvocation.getName().resolveBinding(); + } else if (selectedNode instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) selectedNode; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.java index ae8ca99c79..fef13b713a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.java @@ -9,7 +9,7 @@ * IBM Corporation - initial API and implementation * Stephan Herrmann - Contributions for * [quick fix] Add quick fixes for null annotations - https://bugs.eclipse.org/337977 - * [quick fix] The fix change parameter type to @Nonnull generated a null change - https://bugs.eclipse.org/400668 + * [quick fix] The fix change parameter type to @Nonnull generated a null change - https://bugs.eclipse.org/400668 *******************************************************************************/ package org.eclipse.jdt.internal.corext.fix; @@ -133,6 +133,8 @@ private FixMessages() { public static String ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName; public static String ExtractToNullCheckedLocalProposal_extractToCheckedLocal_proposalName; public static String ExtractToNullCheckedLocalProposal_todoHandleNullDescription; + public static String LambdaExpressionsFix_convert_to_anonymous_class_creation; + public static String LambdaExpressionsFix_convert_to_lambda_expression; static { // initialize resource bundle diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.properties b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.properties index 4344358d1e..e34d99ede7 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.properties +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/FixMessages.properties @@ -120,3 +120,5 @@ NullAnnotationsRewriteOperations_remove_redundant_nullness_annotation=Remove red ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName=Extract checked local ExtractToNullCheckedLocalProposal_extractToCheckedLocal_proposalName=Extract to checked local variable ExtractToNullCheckedLocalProposal_todoHandleNullDescription=handle null value +LambdaExpressionsFix_convert_to_anonymous_class_creation=Convert to anonymous class creation +LambdaExpressionsFix_convert_to_lambda_expression=Convert to lambda expression diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java new file mode 100644 index 0000000000..55a6915d5b --- /dev/null +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java @@ -0,0 +1,453 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.internal.corext.fix; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.text.edits.TextEditGroup; + +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; +import org.eclipse.jdt.core.dom.ArrayInitializer; +import org.eclipse.jdt.core.dom.Assignment; +import org.eclipse.jdt.core.dom.Block; +import org.eclipse.jdt.core.dom.BodyDeclaration; +import org.eclipse.jdt.core.dom.CastExpression; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.ConditionalExpression; +import org.eclipse.jdt.core.dom.ConstructorInvocation; +import org.eclipse.jdt.core.dom.EnumConstantDeclaration; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.MethodInvocation; +import org.eclipse.jdt.core.dom.ReturnStatement; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.jdt.core.dom.Statement; +import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; +import org.eclipse.jdt.core.dom.SuperConstructorInvocation; +import org.eclipse.jdt.core.dom.SuperFieldAccess; +import org.eclipse.jdt.core.dom.SuperMethodInvocation; +import org.eclipse.jdt.core.dom.ThisExpression; +import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.VariableDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; + +import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; +import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2; +import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; +import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRemover; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.util.JdtFlags; + +import org.eclipse.jdt.ui.cleanup.ICleanUpFix; + +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; + +public class LambdaExpressionsFix extends CompilationUnitRewriteOperationsFix { + + private static final class FunctionalAnonymousClassesFinder extends ASTVisitor { + + private final ArrayList fNodes= new ArrayList(); + + public static ArrayList perform(ASTNode node) { + FunctionalAnonymousClassesFinder finder= new FunctionalAnonymousClassesFinder(); + node.accept(finder); + return finder.fNodes; + } + + @Override + public boolean visit(ClassInstanceCreation node) { + if (isFunctionalAnonymous(node)) { + fNodes.add(node); + } + return true; + } + } + + private static final class LambdaExpressionsFinder extends ASTVisitor { + + private final ArrayList fNodes= new ArrayList(); + + public static ArrayList perform(ASTNode node) { + LambdaExpressionsFinder finder= new LambdaExpressionsFinder(); + node.accept(finder); + return finder.fNodes; + } + + @Override + public boolean visit(LambdaExpression node) { + ITypeBinding typeBinding= node.resolveTypeBinding(); + if (typeBinding != null && typeBinding.getFunctionalInterfaceMethod() != null) { + fNodes.add(node); + } + return true; + } + } + + private static class AbortSearchException extends RuntimeException { + private static final long serialVersionUID= 1L; + } + + private static final class SuperThisReferenceFinder extends HierarchicalASTVisitor { + + private ITypeBinding fFunctionalInterface; + private MethodDeclaration fMethodDeclaration; + + static boolean hasReference(MethodDeclaration node) { + try { + SuperThisReferenceFinder finder= new SuperThisReferenceFinder(); + ClassInstanceCreation cic= (ClassInstanceCreation) node.getParent().getParent(); + finder.fFunctionalInterface= cic.getType().resolveBinding(); + finder.fMethodDeclaration= node; + node.accept(finder); + } catch (AbortSearchException e) { + return true; + } + return false; + } + + @Override + public boolean visit(AnonymousClassDeclaration node) { + return false; + } + + @Override + public boolean visit(BodyDeclaration node) { + return false; + } + + @Override + public boolean visit(MethodDeclaration node) { + return node == fMethodDeclaration; + } + + @Override + public boolean visit(ThisExpression node) { + if (node.getQualifier() == null) + throw new AbortSearchException(); + return true; // references to outer scope are harmless + } + + @Override + public boolean visit(SuperMethodInvocation node) { + if (node.getQualifier() == null) { + throw new AbortSearchException(); + } else { + IBinding qualifierType= node.getQualifier().resolveBinding(); + if (qualifierType instanceof ITypeBinding && ((ITypeBinding) qualifierType).isInterface()) { + throw new AbortSearchException(); // JLS8: new overloaded meaning of 'interface'.super.'method'(..) + } + } + return true; // references to outer scopes are harmless + } + + @Override + public boolean visit(SuperFieldAccess node) { + throw new AbortSearchException(); + } + + @Override + public boolean visit(MethodInvocation node) { + IMethodBinding binding= node.resolveMethodBinding(); + if (binding != null && !JdtFlags.isStatic(binding) && node.getExpression() == null + && Bindings.isSuperType(binding.getDeclaringClass(), fFunctionalInterface, false)) + throw new AbortSearchException(); + return true; + } + } + + private static class CreateLambdaOperation extends CompilationUnitRewriteOperation { + + private final List fExpressions; + + public CreateLambdaOperation(List expressions) { + fExpressions= expressions; + } + + /** + * {@inheritDoc} + */ + @Override + public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { + + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + ImportRemover importRemover= cuRewrite.getImportRemover(); + AST ast= rewrite.getAST(); + + for (Iterator iterator= fExpressions.iterator(); iterator.hasNext();) { + ClassInstanceCreation classInstanceCreation= iterator.next(); + TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite); + + AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration(); + List bodyDeclarations= anonymTypeDecl.bodyDeclarations(); + + Object object= bodyDeclarations.get(0); + if (!(object instanceof MethodDeclaration)) + continue; + MethodDeclaration methodDeclaration= (MethodDeclaration) object; + List methodParameters= methodDeclaration.parameters(); + + // use short form with inferred parameter types and without parentheses if possible + LambdaExpression lambdaExpression= ast.newLambdaExpression(); + List lambdaParameters= lambdaExpression.parameters(); + lambdaExpression.setParentheses(methodParameters.size() != 1); + for (SingleVariableDeclaration methodParameter : methodParameters) { + VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment(); + lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName())); + lambdaParameters.add(lambdaParameter); + } + + Block body= methodDeclaration.getBody(); + List statements= body.statements(); + ASTNode lambdaBody= body; + if (statements.size() == 1) { + // use short form with just an expression body if possible + Statement statement= statements.get(0); + if (statement instanceof ExpressionStatement) { + lambdaBody= ((ExpressionStatement) statement).getExpression(); + } else if (statement instanceof ReturnStatement) { + Expression returnExpression= ((ReturnStatement) statement).getExpression(); + if (returnExpression != null) { + lambdaBody= returnExpression; + } + } + } + //TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface +// lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder + + lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody)); + rewrite.replace(classInstanceCreation, lambdaExpression, group); + + importRemover.registerRemovedNode(classInstanceCreation); + importRemover.registerRetainedNode(lambdaBody); + } + } + } + + private static class CreateAnonymousClassCreationOperation extends CompilationUnitRewriteOperation { + + private final List fExpressions; + + public CreateAnonymousClassCreationOperation(List changedNodes) { + fExpressions= changedNodes; + } + + /** + * {@inheritDoc} + */ + @Override + public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException { + + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + AST ast= rewrite.getAST(); + + for (Iterator iterator= fExpressions.iterator(); iterator.hasNext();) { + LambdaExpression lambdaExpression= iterator.next(); + TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_anonymous_class_creation, cuRewrite); + + ITypeBinding lambdaTypeBinding= lambdaExpression.resolveTypeBinding(); + IMethodBinding methodBinding= lambdaTypeBinding.getFunctionalInterfaceMethod(); + List parameters= lambdaExpression.parameters(); + String[] parameterNames= new String[parameters.size()]; + for (int i= 0; i < parameterNames.length; i++) { + parameterNames[i]= parameters.get(i).getName().getIdentifier(); + } + + final CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cuRewrite.getCu().getJavaProject()); + ImportRewrite importRewrite= cuRewrite.getImportRewrite(); + ImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(lambdaExpression, importRewrite); + + MethodDeclaration methodDeclaration= StubUtility2.createImplementationStub(cuRewrite.getCu(), rewrite, importRewrite, importContext, + methodBinding, parameterNames, lambdaTypeBinding.getName(), settings, false); + + Block block; + ASTNode lambdaBody= lambdaExpression.getBody(); + if (lambdaBody instanceof Block) { + block= (Block) rewrite.createCopyTarget(lambdaBody); + } else { + block= ast.newBlock(); + List statements= block.statements(); + ITypeBinding returnType= methodBinding.getReturnType(); + Expression copyTarget= (Expression) rewrite.createCopyTarget(lambdaBody); + if (Bindings.isVoidType(returnType)) { + ExpressionStatement newExpressionStatement= ast.newExpressionStatement(copyTarget); + statements.add(newExpressionStatement); + } else { + ReturnStatement returnStatement= ast.newReturnStatement(); + returnStatement.setExpression(copyTarget); + statements.add(returnStatement); + } + } + methodDeclaration.setBody(block); + + AnonymousClassDeclaration anonymousClassDeclaration= ast.newAnonymousClassDeclaration(); + List bodyDeclarations= anonymousClassDeclaration.bodyDeclarations(); + bodyDeclarations.add(methodDeclaration); + + Type creationType= ASTNodeFactory.newCreationType(ast, lambdaTypeBinding, importRewrite, importContext); + + ClassInstanceCreation classInstanceCreation= ast.newClassInstanceCreation(); + classInstanceCreation.setType(creationType); + classInstanceCreation.setAnonymousClassDeclaration(anonymousClassDeclaration); + + rewrite.replace(lambdaExpression, classInstanceCreation, group); + } + } + } + + public static LambdaExpressionsFix createConvertToLambdaFix(ClassInstanceCreation cic) { + CompilationUnit root= (CompilationUnit) cic.getRoot(); + if (!JavaModelUtil.is18OrHigher(root.getJavaElement().getJavaProject())) + return null; + + if (!LambdaExpressionsFix.isFunctionalAnonymous(cic)) + return null; + + CreateLambdaOperation op= new CreateLambdaOperation(Collections.singletonList(cic)); + return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, root, new CompilationUnitRewriteOperation[] { op }); + } + + public static IProposableFix createConvertToAnonymousClassCreationsFix(LambdaExpression lambda) { + // offer the quick assist at pre 1.8 levels as well to get rid of the compilation error (TODO: offer this as a quick fix in that case) + + if (lambda.resolveTypeBinding() == null || lambda.resolveTypeBinding().getFunctionalInterfaceMethod() == null) + return null; + + CreateAnonymousClassCreationOperation op= new CreateAnonymousClassCreationOperation(Collections.singletonList(lambda)); + CompilationUnit root= (CompilationUnit) lambda.getRoot(); + return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_anonymous_class_creation, root, new CompilationUnitRewriteOperation[] { op }); + } + + public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean useLambda, boolean useAnonymous) { + if (!JavaModelUtil.is18OrHigher(compilationUnit.getJavaElement().getJavaProject())) + return null; + + if (useLambda) { + ArrayList convertibleNodes= FunctionalAnonymousClassesFinder.perform(compilationUnit); + if (convertibleNodes.isEmpty()) + return null; + + CompilationUnitRewriteOperation op= new CreateLambdaOperation(convertibleNodes); + return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, compilationUnit, new CompilationUnitRewriteOperation[] { op }); + + } else if (useAnonymous) { + ArrayList convertibleNodes= LambdaExpressionsFinder.perform(compilationUnit); + if (convertibleNodes.isEmpty()) + return null; + + CompilationUnitRewriteOperation op= new CreateAnonymousClassCreationOperation(convertibleNodes); + return new LambdaExpressionsFix(FixMessages.LambdaExpressionsFix_convert_to_anonymous_class_creation, compilationUnit, new CompilationUnitRewriteOperation[] { op }); + + } + return null; + } + + protected LambdaExpressionsFix(String name, CompilationUnit compilationUnit, CompilationUnitRewriteOperation[] fixRewriteOperations) { + super(name, compilationUnit, fixRewriteOperations); + } + + static boolean isFunctionalAnonymous(ClassInstanceCreation node) { + ITypeBinding typeBinding= node.resolveTypeBinding(); + if (typeBinding == null) + return false; + ITypeBinding[] interfaces= typeBinding.getInterfaces(); + if (interfaces.length != 1) + return false; + if (interfaces[0].getFunctionalInterfaceMethod() == null) + return false; + + AnonymousClassDeclaration anonymTypeDecl= node.getAnonymousClassDeclaration(); + if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null) + return false; + + List bodyDeclarations= anonymTypeDecl.bodyDeclarations(); + // cannot convert if there are fields or additional methods + if (bodyDeclarations.size() != 1) + return false; + BodyDeclaration bodyDeclaration= bodyDeclarations.get(0); + if (!(bodyDeclaration instanceof MethodDeclaration)) + return false; + + MethodDeclaration methodDecl= (MethodDeclaration) bodyDeclaration; + IMethodBinding methodBinding= methodDecl.resolveBinding(); + + if (methodBinding == null) + return false; + // generic lambda expressions are not allowed + if (methodBinding.isGenericMethod()) + return false; + + // lambda cannot refer to 'this'/'super' literals + if (SuperThisReferenceFinder.hasReference(methodDecl)) + return false; + + if (!isInTargetTypeContext(node)) + return false; + + return true; + } + + private static boolean isInTargetTypeContext(ClassInstanceCreation node) { + //TODO: probably incomplete, should reuse https://bugs.eclipse.org/bugs/show_bug.cgi?id=408966#c6 + StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); + + if (locationInParent == ReturnStatement.EXPRESSION_PROPERTY) { + MethodDeclaration methodDeclaration= ASTResolving.findParentMethodDeclaration(node); + if (methodDeclaration == null) + return false; + IMethodBinding methodBinding= methodDeclaration.resolveBinding(); + if (methodBinding == null) + return false; + //TODO: could also cast to the CIC type instead of aborting... + return methodBinding.getReturnType().getFunctionalInterfaceMethod() != null; + } + + //TODO: should also check whether variable is of a functional type + return locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY + || locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY + || locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY + || locationInParent == ArrayInitializer.EXPRESSIONS_PROPERTY + + || locationInParent == MethodInvocation.ARGUMENTS_PROPERTY + || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY + || locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY + || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY + || locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY + || locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY + + || locationInParent == LambdaExpression.BODY_PROPERTY + || locationInParent == ConditionalExpression.THEN_EXPRESSION_PROPERTY + || locationInParent == ConditionalExpression.ELSE_EXPRESSION_PROPERTY + || locationInParent == CastExpression.EXPRESSION_PROPERTY; + } +} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java index dd34f48eb4..77a03eea0d 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -47,6 +47,7 @@ import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.QualifiedType; @@ -383,13 +384,18 @@ private static SimpleName getSelectedName(CompilationUnit compilationUnit, IProb Name name= null; if (selection instanceof SimpleType) { - final SimpleType type= (SimpleType) selection; - name= type.getName(); + name= ((SimpleType) selection).getName(); + } else if (selection instanceof NameQualifiedType) { + name= ((NameQualifiedType) selection).getName(); + } else if (selection instanceof QualifiedType) { + name= ((QualifiedType) selection).getName(); } else if (selection instanceof ParameterizedType) { final ParameterizedType type= (ParameterizedType) selection; final Type raw= type.getType(); if (raw instanceof SimpleType) name= ((SimpleType) raw).getName(); + else if (raw instanceof NameQualifiedType) + name= ((NameQualifiedType) raw).getName(); else if (raw instanceof QualifiedType) name= ((QualifiedType) raw).getName(); } else if (selection instanceof Name) { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java index 9bcd670cfd..11049dc33a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -454,10 +454,13 @@ public static URL getJavadocLocation(IJavaElement element, boolean includeMember String urlString= baseLocation.toExternalForm(); - StringBuffer pathBuffer= new StringBuffer(urlString); + StringBuffer urlBuffer= new StringBuffer(urlString); if (!urlString.endsWith("/")) { //$NON-NLS-1$ - pathBuffer.append('/'); + urlBuffer.append('/'); } + + StringBuffer pathBuffer= new StringBuffer(); + StringBuffer fragmentBuffer= new StringBuffer(); switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: @@ -487,14 +490,14 @@ public static URL getJavadocLocation(IJavaElement element, boolean includeMember IField field= (IField) element; appendTypePath(field.getDeclaringType(), pathBuffer); if (includeMemberReference) { - appendFieldReference(field, pathBuffer); + appendFieldReference(field, fragmentBuffer); } break; case IJavaElement.METHOD : IMethod method= (IMethod) element; appendTypePath(method.getDeclaringType(), pathBuffer); if (includeMemberReference) { - appendMethodReference(method, pathBuffer); + appendMethodReference(method, fragmentBuffer); } break; case IJavaElement.INITIALIZER : @@ -528,7 +531,15 @@ public static URL getJavadocLocation(IJavaElement element, boolean includeMember } try { - return new URL(pathBuffer.toString()); + String fragment= fragmentBuffer.length() == 0 ? null : fragmentBuffer.toString(); + try { + URI relativeURI= new URI(null, null, pathBuffer.toString(), fragment); + urlBuffer.append(relativeURI.toString()); + return new URL(urlBuffer.toString()); + } catch (URISyntaxException e) { + JavaPlugin.log(e); + return new URL(urlBuffer.append(pathBuffer).toString()); + } } catch (MalformedURLException e) { JavaPlugin.log(e); } @@ -558,25 +569,32 @@ private static void appendTypePath(IType type, StringBuffer buf) { } private static void appendFieldReference(IField field, StringBuffer buf) { - buf.append('#'); buf.append(field.getElementName()); } private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException { - buf.append('#'); buf.append(meth.getElementName()); - buf.append('('); + /* + * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs. + * This breaks all clients that directly create such URLs. + * We can't know what format is required, so we just guess by the project's compiler compliance. + */ + boolean is18OrHigher= JavaModelUtil.is18OrHigher(meth.getJavaProject()); + buf.append(is18OrHigher ? '-' : '('); String[] params= meth.getParameterTypes(); IType declaringType= meth.getDeclaringType(); boolean isVararg= Flags.isVarargs(meth.getFlags()); int lastParam= params.length - 1; for (int i= 0; i <= lastParam; i++) { if (i != 0) { - buf.append(", "); //$NON-NLS-1$ + buf.append(is18OrHigher ? "-" : ", "); //$NON-NLS-1$ //$NON-NLS-2$ } String curr= Signature.getTypeErasure(params[i]); String fullName= JavaModelUtil.getResolvedTypeName(curr, declaringType); + if (fullName == null) { // e.g. a type parameter "QE;" + fullName= Signature.toString(Signature.getElementType(curr)); + } if (fullName != null) { buf.append(fullName); int dim= Signature.getArrayCount(curr); @@ -584,7 +602,7 @@ private static void appendMethodReference(IMethod meth, StringBuffer buf) throws dim--; } while (dim > 0) { - buf.append("[]"); //$NON-NLS-1$ + buf.append(is18OrHigher ? ":A" : "[]"); //$NON-NLS-1$ //$NON-NLS-2$ dim--; } if (i == lastParam && isVararg) { @@ -592,7 +610,7 @@ private static void appendMethodReference(IMethod meth, StringBuffer buf) throws } } } - buf.append(')'); + buf.append(is18OrHigher ? '-' : ')'); } /** diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/AbstractJavaContextType.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/AbstractJavaContextType.java index daef609d82..d0ddd329e9 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/AbstractJavaContextType.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/AbstractJavaContextType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -8,6 +8,7 @@ * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids: sdavids@gmx.de - see bug 25376 + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 *******************************************************************************/ package org.eclipse.jdt.internal.corext.template.java; @@ -43,7 +44,7 @@ public AbstractIterable(String type, String description) { @Override protected String[] resolveAll(TemplateContext context) { JavaContext jc= (JavaContext) context; - Variable[] iterables= getLocalVariables(jc); + Variable[] iterables= getVariables(jc); String[] names= new String[iterables.length]; for (int i= 0; i < iterables.length; i++) names[i]= iterables[i].getName(); @@ -52,7 +53,7 @@ protected String[] resolveAll(TemplateContext context) { return names; } - abstract protected Variable[] getLocalVariables(JavaContext jc); + abstract protected Variable[] getVariables(JavaContext jc); /* * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext) @@ -62,7 +63,7 @@ public void resolve(TemplateVariable variable, TemplateContext context) { if (variable instanceof MultiVariable) { JavaContext jc= (JavaContext) context; JavaVariable jv= (JavaVariable) variable; - Variable[] iterables= getLocalVariables(jc); + Variable[] iterables= getVariables(jc); if (iterables.length > 0) { jv.setChoices(iterables); jc.markAsUsed(iterables[0].getName()); @@ -86,7 +87,7 @@ public Array() { } @Override - protected Variable[] getLocalVariables(JavaContext jc) { + protected Variable[] getVariables(JavaContext jc) { return jc.getArrays(); } } @@ -97,7 +98,7 @@ public Iterable() { } @Override - protected Variable[] getLocalVariables(JavaContext jc) { + protected Variable[] getVariables(JavaContext jc) { return jc.getIterables(); } } @@ -112,14 +113,14 @@ public AbstractIterableType(String type, String desc, String master) { @Override protected String[] resolveAll(TemplateContext context) { JavaContext jc= (JavaContext) context; - Variable[] iterables= getLocalVariables(jc); + Variable[] iterables= getVariablesInContextScope(jc); String[] types= new String[iterables.length]; for (int i= 0; i < iterables.length; i++) types[i]= iterables[i].getMemberTypeNames()[0]; return types; } - abstract protected Variable[] getLocalVariables(JavaContext jc); + abstract protected Variable[] getVariablesInContextScope(JavaContext jc); /* * @see org.eclipse.jface.text.templates.TemplateVariableResolver#resolve(org.eclipse.jface.text.templates.TemplateVariable, org.eclipse.jface.text.templates.TemplateContext) @@ -130,7 +131,7 @@ public void resolve(TemplateVariable variable, TemplateContext context) { JavaContext jc= (JavaContext) context; MultiVariable mv= (MultiVariable) variable; - Variable[] iterables= getLocalVariables(jc); + Variable[] iterables= getVariablesInContextScope(jc); if (iterables.length > 0) { for (int i= 0; i < iterables.length; i++) @@ -162,7 +163,7 @@ public ArrayType() { super("array_type", JavaTemplateMessages.JavaContextType_variable_description_array_type, "array"); //$NON-NLS-1$ //$NON-NLS-2$ } @Override - protected Variable[] getLocalVariables(JavaContext jc) { + protected Variable[] getVariablesInContextScope(JavaContext jc) { return jc.getArrays(); } } @@ -172,7 +173,7 @@ public IterableType() { super("iterable_type", JavaTemplateMessages.JavaContextType_variable_description_iterable_type, "iterable"); //$NON-NLS-1$ //$NON-NLS-2$ } @Override - protected Variable[] getLocalVariables(JavaContext jc) { + protected Variable[] getVariablesInContextScope(JavaContext jc) { return jc.getIterables(); } } @@ -267,7 +268,7 @@ public Index() { } } - protected static class Collection extends LocalVarResolver { + protected static class Collection extends VarResolver { public Collection() { super("java.util.Collection"); //$NON-NLS-1$ setType("collection"); //$NON-NLS-1$ diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitCompletion.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitCompletion.java index aed181254d..0cb0350220 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitCompletion.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitCompletion.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -7,6 +7,7 @@ * * Contributors: * IBM Corporation - initial API and implementation + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 *******************************************************************************/ package org.eclipse.jdt.internal.corext.template.java; @@ -839,19 +840,28 @@ public String[] getFieldNames() { } /** - * Returns all local arrays in the order that they appear. - * - * @return all local arrays + * Returns all arrays, visible in the current context's scope, in the order that they appear. + * + * @return all visible arrays */ - public Variable[] findLocalArrays() { + public Variable[] findArraysInCurrentScope() { List arrays= new ArrayList(); + // local variables for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) { Variable localVariable= iterator.previous(); if (localVariable.isArray()) arrays.add(localVariable); } + + // fields + for (ListIterator iterator= fFields.listIterator(fFields.size()); iterator.hasPrevious();) { + Variable field= iterator.previous(); + + if (field.isArray()) + arrays.add(field); + } return arrays.toArray(new Variable[arrays.size()]); } @@ -897,22 +907,30 @@ public Variable[] findFieldVariables(String clazz) { } /** - * Returns all local variables implementing java.lang.Iterable - * and all local arrays, in the order that they appear. That is, - * the returned variables can be used within the foreach - * language construct. - * - * @return all local Iterables and arrays + * Returns all variables, visible in the current context's scope, implementing + * java.lang.Iterable and all arrays, in the order that they appear. That + * is, the returned variables can be used within the foreach language construct. + * + * @return all visible Iterables and arrays */ - public Variable[] findLocalIterables() { + public Variable[] findIterablesInCurrentScope() { List iterables= new ArrayList(); + // local variables for (ListIterator iterator= fLocalVariables.listIterator(fLocalVariables.size()); iterator.hasPrevious();) { Variable localVariable= iterator.previous(); if (localVariable.isArray() || localVariable.isIterable()) iterables.add(localVariable); } + + // fields + for (ListIterator iterator= fFields.listIterator(fFields.size()); iterator.hasPrevious();) { + Variable field= iterator.previous(); + + if (field.isArray() || field.isIterable()) + iterables.add(field); + } return iterables.toArray(new Variable[iterables.size()]); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java index 02ca245853..297f1ee55f 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -8,6 +8,7 @@ * Contributors: * IBM Corporation - initial API and implementation * Lars Vogel - [templates][content assist] Ctrl+Space without any starting letter shows to no templates - https://bugs.eclipse.org/406463 + * Lukas Hanke - [templates][content assist] Content assist for 'for' loop should suggest member variables - https://bugs.eclipse.org/117215 *******************************************************************************/ package org.eclipse.jdt.internal.corext.template.java; @@ -378,18 +379,18 @@ private CompilationUnitCompletion getCompletion() { } /** - * Returns the names of local arrays. + * Returns the names of arrays available in the current {@link CompilationUnit}'s scope. * - * @return the names of local arrays + * @return the names of local arrays available in the current {@link CompilationUnit}'s scope */ public Variable[] getArrays() { - Variable[] localArrays= getCompletion().findLocalArrays(); - arrange(localArrays); - return localArrays; + Variable[] arrays= getCompletion().findArraysInCurrentScope(); + arrange(arrays); + return arrays; } /** - * Sorts already used locals behind any that are not yet used. + * Sorts already used variables behind any that are not yet used. * * @param variables the variables to sort * @since 3.3 @@ -433,12 +434,12 @@ public Variable[] getFields(String type) { } /** - * Returns the names of local iterables or arrays. + * Returns the names of iterables or arrays available in the current {@link CompilationUnit}'s scope. * - * @return the names of local iterables or arrays + * @return the names of iterables or arrays available in the current {@link CompilationUnit}'s scope */ public Variable[] getIterables() { - Variable[] iterables= getCompletion().findLocalIterables(); + Variable[] iterables= getCompletion().findIterablesInCurrentScope(); arrange(iterables); return iterables; } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java index c55f69ebda..b5a998e78c 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java @@ -21,6 +21,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.BodyDeclarationRewrite; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; @@ -104,6 +105,7 @@ *

    *
  • {@link CompilationUnitRewrite}
  • *
  • {@link BodyDeclarationRewrite}
  • + *
  • {@link DimensionRewrite}
  • *
  • {@link ModifierRewrite}
  • *
  • {@link ReplaceRewrite}
  • *
  • {@link StatementRewrite}
  • diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java index 46ebe531c1..c3544a00de 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java @@ -71,7 +71,7 @@ public final class JavaModelUtil { */ public static final String VERSION_LATEST; static { - VERSION_LATEST= JavaCore.VERSION_1_7; // make sure it is not inlined + VERSION_LATEST= JavaCore.VERSION_1_8; // make sure it is not inlined } /** @@ -767,6 +767,10 @@ public static boolean is17OrHigher(String compliance) { return !isVersionLessThan(compliance, JavaCore.VERSION_1_7); } + public static boolean is18OrHigher(String compliance) { + return !isVersionLessThan(compliance, JavaCore.VERSION_1_8); + } + /** * Checks if the given project or workspace has source compliance 1.5 or greater. * @@ -774,8 +778,7 @@ public static boolean is17OrHigher(String compliance) { * @return true if the given project or workspace has source compliance 1.5 or greater. */ public static boolean is50OrHigher(IJavaProject project) { - String source= project != null ? project.getOption(JavaCore.COMPILER_SOURCE, true) : JavaCore.getOption(JavaCore.COMPILER_SOURCE); - return is50OrHigher(source); + return is50OrHigher(getSourceCompliance(project)); } /** @@ -785,8 +788,22 @@ public static boolean is50OrHigher(IJavaProject project) { * @return true if the given project or workspace has source compliance 1.7 or greater. */ public static boolean is17OrHigher(IJavaProject project) { - String source= project != null ? project.getOption(JavaCore.COMPILER_SOURCE, true) : JavaCore.getOption(JavaCore.COMPILER_SOURCE); - return is17OrHigher(source); + return is17OrHigher(getSourceCompliance(project)); + } + + /** + * Checks if the given project or workspace has source compliance 1.8 or greater. + * + * @param project the project to test or null to test the workspace settings + * @return true if the given project or workspace has source compliance 1.8 or + * greater. + */ + public static boolean is18OrHigher(IJavaProject project) { + return is18OrHigher(getSourceCompliance(project)); + } + + private static String getSourceCompliance(IJavaProject project) { + return project != null ? project.getOption(JavaCore.COMPILER_SOURCE, true) : JavaCore.getOption(JavaCore.COMPILER_SOURCE); } /** @@ -811,15 +828,15 @@ public static boolean is50OrHigherJRE(IJavaProject project) throws CoreException String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null); if (compliance == null) return true; // assume 1.5 - return compliance.startsWith(JavaCore.VERSION_1_5) - || compliance.startsWith(JavaCore.VERSION_1_6) - || compliance.startsWith(JavaCore.VERSION_1_7); + return is50OrHigher(compliance); } public static String getCompilerCompliance(IVMInstall2 vMInstall, String defaultCompliance) { String version= vMInstall.getJavaVersion(); if (version == null) { return defaultCompliance; + } else if (version.startsWith(JavaCore.VERSION_1_8)) { + return JavaCore.VERSION_1_8; } else if (version.startsWith(JavaCore.VERSION_1_7)) { return JavaCore.VERSION_1_7; } else if (version.startsWith(JavaCore.VERSION_1_6)) { @@ -848,7 +865,9 @@ public static String getExecutionEnvironmentCompliance(IExecutionEnvironment exe // fallback: String desc= executionEnvironment.getId(); - if (desc.indexOf(JavaCore.VERSION_1_7) != -1) { + if (desc.indexOf(JavaCore.VERSION_1_8) != -1) { + return JavaCore.VERSION_1_8; + } else if (desc.indexOf(JavaCore.VERSION_1_7) != -1) { return JavaCore.VERSION_1_7; } else if (desc.indexOf(JavaCore.VERSION_1_6) != -1) { return JavaCore.VERSION_1_6; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java index dea5d43044..3d538cace0 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java @@ -14,13 +14,18 @@ import org.eclipse.core.runtime.Assert; import org.eclipse.jdt.core.Flags; +import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.BodyDeclaration; +import org.eclipse.jdt.core.dom.EnumConstantDeclaration; +import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; @@ -54,18 +59,61 @@ private JdtFlags(){ public static final int VISIBILITY_CODE_INVALID= -1; + public static boolean isDefaultMethod(IMethodBinding method) { + int modifiers= method.getModifiers(); + // https://bugs.eclipse.org/bugs/show_bug.cgi?id=405517#c7 + ITypeBinding declaringClass= method.getDeclaringClass(); + if (declaringClass.isInterface()) { + return !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers); + } + return false; + } + + public static boolean isDefaultMethod(IMethod method) throws JavaModelException { + return Flags.isDefaultMethod(method.getFlags()); + } + public static boolean isAbstract(IMember member) throws JavaModelException{ - if (isInterfaceOrAnnotationMethod(member)) - return true; - return Flags.isAbstract(member.getFlags()); + int flags= member.getFlags(); + if (!member.isBinary() && isInterfaceOrAnnotationMethod(member)) { + return !Flags.isStatic(flags) && !Flags.isDefaultMethod(flags); + } + return Flags.isAbstract(flags); } public static boolean isAbstract(IMethodBinding member) { - if (isInterfaceOrAnnotationMember(member)) - return true; return Modifier.isAbstract(member.getModifiers()); } + public static boolean isStatic(BodyDeclaration bodyDeclaration) { + if (isNestedInterfaceOrAnnotation(bodyDeclaration)) + return true; + int nodeType= bodyDeclaration.getNodeType(); + if (!(nodeType == ASTNode.METHOD_DECLARATION || nodeType == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION) && + isInterfaceOrAnnotationMember(bodyDeclaration)) + return true; + if (bodyDeclaration instanceof EnumConstantDeclaration) + return true; + if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration) + return true; + return Modifier.isStatic(bodyDeclaration.getModifiers()); + } + + public static boolean isStatic(IMember member) throws JavaModelException { + if (isNestedInterfaceOrAnnotation(member)) + return true; + if (member.getElementType() != IJavaElement.METHOD + && isInterfaceOrAnnotationMember(member)) + return true; + if (isEnum(member) && (member.getElementType() == IJavaElement.FIELD || member.getDeclaringType() != null)) + return true; + return Flags.isStatic(member.getFlags()); + } + + public static boolean isStatic(IMethodBinding methodBinding){ + return Modifier.isStatic(methodBinding.getModifiers()); + } + public static boolean isDeprecated(IMember member) throws JavaModelException{ return Flags.isDeprecated(member.getFlags()); } @@ -75,11 +123,24 @@ public static boolean isFinal(IMember member) throws JavaModelException{ return true; if (isAnonymousType(member)) return true; - if (isEnumConstant(member)) + if (isEnumConstant(member) || isEnumTypeFinal(member)) return true; return Flags.isFinal(member.getFlags()); } + private static boolean isEnumTypeFinal(IMember member) throws JavaModelException { + if (!(isEnum(member) && member.getElementType() == IJavaElement.TYPE)) + return false; + // An enum type is implicitly final unless it contains at least one enum constant that has a class body. + IJavaElement[] children= member.getChildren(); + for (IJavaElement child : children) { + if (isEnumConstant((IMember) child) && ((IField) child).getChildren().length != 0) { + return false; + } + } + return true; + } + public static boolean isNative(IMember member) throws JavaModelException{ return Flags.isNative(member.getFlags()); } @@ -141,30 +202,12 @@ public static boolean isPublic(BodyDeclaration bodyDeclaration) { return Modifier.isPublic(bodyDeclaration.getModifiers()); } - public static boolean isStatic(IMember member) throws JavaModelException{ - if (isNestedInterfaceOrAnnotation(member)) - return true; - if (member.getElementType() != IJavaElement.METHOD && isInterfaceOrAnnotationMember(member)) - return true; - if (isEnumConstant(member)) - return true; - return Flags.isStatic(member.getFlags()); - } - - public static boolean isStatic(IMethodBinding methodBinding){ - return Modifier.isStatic(methodBinding.getModifiers()); - } - public static boolean isStatic(IVariableBinding variableBinding){ if (isInterfaceOrAnnotationMember(variableBinding)) return true; return Modifier.isStatic(variableBinding.getModifiers()); } - public static boolean isStrictfp(IMember member) throws JavaModelException{ - return Flags.isStrictfp(member.getFlags()); - } - public static boolean isSynchronized(IMember member) throws JavaModelException{ return Flags.isSynchronized(member.getFlags()); } @@ -218,12 +261,19 @@ private static boolean isInterfaceOrAnnotationMember(IBinding binding) { } private static boolean isInterfaceOrAnnotationMember(BodyDeclaration bodyDeclaration) { - boolean isInterface= (bodyDeclaration.getParent() instanceof TypeDeclaration) && - ((TypeDeclaration)bodyDeclaration.getParent()).isInterface(); - boolean isAnnotation= bodyDeclaration.getParent() instanceof AnnotationTypeDeclaration; - return isInterface || isAnnotation; + return isInterfaceOrAnnotation(bodyDeclaration.getParent()); } + private static boolean isInterfaceOrAnnotation(ASTNode node) { + boolean isInterface= (node instanceof TypeDeclaration) && ((TypeDeclaration) node).isInterface(); + boolean isAnnotation= node instanceof AnnotationTypeDeclaration; + return isInterface || isAnnotation; + } + + private static boolean isNestedInterfaceOrAnnotation(BodyDeclaration bodyDeclaration) { + return bodyDeclaration.getParent() instanceof AbstractTypeDeclaration && isInterfaceOrAnnotation(bodyDeclaration); + } + private static boolean isNestedInterfaceOrAnnotation(IMember member) throws JavaModelException{ return member.getElementType() == IJavaElement.TYPE && member.getDeclaringType() != null && diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java index 7abe578573..285eb02521 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,7 @@ import org.eclipse.core.runtime.Assert; import org.eclipse.jdt.core.Flags; +import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; @@ -326,6 +327,12 @@ private String getVariableSubstitution(IMember context, String variableName) thr if (subst != null) { return subst; } + IJavaElement parent= type.getParent(); + if (parent instanceof IMethod) { + return getVariableSubstitution((IMethod) parent, variableName); + } else if (type.getDeclaringType() != null) { + return getVariableSubstitution(type.getDeclaringType(), variableName); + } return variableName; // not a type variable } @@ -344,6 +351,12 @@ private String getVariableErasure(IMember context, String variableName) throws J if (subst != null) { return subst; } + IJavaElement parent= type.getParent(); + if (parent instanceof IMethod) { + return getVariableErasure((IMethod) parent, variableName); + } else if (type.getDeclaringType() != null) { + return getVariableErasure(type.getDeclaringType(), variableName); + } return variableName; // not a type variable } @@ -426,7 +439,13 @@ private void computeSubstitutions(IType instantiatedType, IType instantiatingTyp computeSubstitutions(superclass, instantiatedType, superTypeArguments); } } - String[] superInterfacesTypeSignature= instantiatedType.getSuperInterfaceTypeSignatures(); + String[] superInterfacesTypeSignature; + if (instantiatedType.isAnonymous()) { + // special case: superinterface is also returned by IType#getSuperclassTypeSignature() + superInterfacesTypeSignature= new String[] { superclassTypeSignature }; + } else { + superInterfacesTypeSignature= instantiatedType.getSuperInterfaceTypeSignatures(); + } int nInterfaces= superInterfacesTypeSignature.length; if (nInterfaces > 0) { IType[] superInterfaces= fHierarchy.getSuperInterfaces(instantiatedType); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/Checks.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/Checks.java index 26f731a632..1f0ac9d926 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/Checks.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/Checks.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -310,13 +310,17 @@ private static RefactoringStatus checkForMainAndNativeMethods(IMethod[] methods) */ public static RefactoringStatus checkMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) { RefactoringStatus result= new RefactoringStatus(); - if (methodName.equals(type.getName())) - result.addWarning(RefactoringCoreMessages.Checks_methodName_constructor); IMethodBinding method= org.eclipse.jdt.internal.corext.dom.Bindings.findMethodInType(type, methodName, parameters); - if (method != null) - result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists, - new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(type.getName())}), - JavaStatusContext.create(method)); + if (method != null) { + if (method.isConstructor()) { + result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor, + new Object[] { BasicElementLabels.getJavaElementName(type.getName()) })); + } else { + result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists, + new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(type.getName()) }), + JavaStatusContext.create(method)); + } + } return result; } @@ -354,9 +358,14 @@ public static RefactoringStatus checkMethodInHierarchy(ITypeBinding type, String new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}), JavaStatusContext.create(method)); } else { - result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides, - new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}), - JavaStatusContext.create(method)); + if (method.isConstructor()) { + result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor, + new Object[] { BasicElementLabels.getJavaElementName(dc.getName()) })); + } else { + result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides, + new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName()) }), + JavaStatusContext.create(method)); + } } } return result; diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringAvailabilityTester.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringAvailabilityTester.java index 5b455a3330..a1d3757658 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringAvailabilityTester.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringAvailabilityTester.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2012 IBM Corporation and others. + * Copyright (c) 2005, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -858,8 +858,11 @@ public static boolean isMoveStaticAvailable(final IMember member) throws JavaMod return false; if (!Checks.isAvailable(member)) return false; - if (type == IJavaElement.METHOD && declaring.isInterface()) - return false; + if (type == IJavaElement.METHOD && declaring.isInterface()) { + boolean is18OrHigher= JavaModelUtil.is18OrHigher(member.getJavaProject()); + if (!is18OrHigher || !Flags.isStatic(member.getFlags())) + return false; + } if (type == IJavaElement.METHOD && !JdtFlags.isStatic(member)) return false; if (type == IJavaElement.METHOD && ((IMethod) member).isConstructor()) diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java index 597c18fa96..0627e01f6e 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -556,13 +556,17 @@ public final class RefactoringCoreMessages extends NLS { public static String ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment; + public static String ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field; + public static String ExtractMethodAnalyzer_compile_errors; public static String ExtractMethodAnalyzer_compile_errors_no_parent_binding; public static String ExtractMethodAnalyzer_leftHandSideOfAssignment; - public static String ExtractMethodAnalyzer_only_method_body; + public static String ExtractMethodAnalyzer_no_valid_destination_type; + + public static String ExtractMethodAnalyzer_invalid_selection; public static String ExtractMethodAnalyzer_parent_mismatch; @@ -1326,6 +1330,8 @@ public final class RefactoringCoreMessages extends NLS { public static String MoveMembersRefactoring_inside; + public static String MoveMembersRefactoring_member_will_be_public; + public static String MoveMembersRefactoring_move_members; public static String MoveMembersRefactoring_Move_Members; @@ -1348,6 +1354,8 @@ public final class RefactoringCoreMessages extends NLS { public static String MoveMembersRefactoring_only_public_static; + public static String MoveMembersRefactoring_only_public_static_18; + public static String MoveMembersRefactoring_read_only; public static String MoveMembersRefactoring_referenceUpdate; @@ -1412,6 +1420,8 @@ public final class RefactoringCoreMessages extends NLS { public static String PromoteTempToFieldRefactoring_initialize_method; + public static String PromoteTempToFieldRefactoring_interface_methods; + public static String PromoteTempToFieldRefactoring_method_parameters; public static String PromoteTempToFieldRefactoring_name; @@ -1810,6 +1820,8 @@ public final class RefactoringCoreMessages extends NLS { public static String RenameTempRefactoring_only_in_methods_and_initializers; + public static String RenameTempRefactoring_only_in_methods_initializers_and_lambda; + public static String RenameTempRefactoring_rename; public static String RenameTypeParameterProcessor_change_name; @@ -2386,6 +2398,8 @@ public final class RefactoringCoreMessages extends NLS { public static String UseSupertypeWherePossibleRefactoring_name; + public static String ChangeSignatureRefactoring_lambda_expression; + static { NLS.initializeMessages(BUNDLE_NAME, RefactoringCoreMessages.class); } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java index 36195fc2b4..3a962b43d1 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -54,6 +54,7 @@ import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.PrimitiveType; @@ -217,8 +218,12 @@ private boolean isError(IProblem problem, Type type) { } private int appendMethodDeclaration(StringBuffer cuString, String[] types, int parameterCount) throws JavaModelException { - if (Flags.isStatic(fMethod.getFlags())) + int flags= fMethod.getFlags(); + if (Flags.isStatic(flags)) { cuString.append("static "); //$NON-NLS-1$ + } else if (Flags.isDefaultMethod(flags)) { + cuString.append("default "); //$NON-NLS-1$ + } ITypeParameter[] methodTypeParameters= fMethod.getTypeParameters(); if (methodTypeParameters.length != 0) { @@ -265,7 +270,12 @@ public boolean visit(QualifiedName node) { } @Override public boolean visit(QualifiedType node) { - appendResolved(ASTNodes.asString(node)); + appendResolved(ASTNodes.getQualifiedTypeName(node)); + return false; + } + @Override + public boolean visit(NameQualifiedType node) { + appendResolved(ASTNodes.getQualifiedTypeName(node)); return false; } private void appendResolved(String typeName) { @@ -404,9 +414,9 @@ private static boolean isVoidArrayType(Type type){ return false; ArrayType arrayType= (ArrayType)type; - if (! arrayType.getComponentType().isPrimitiveType()) + if (! arrayType.getElementType().isPrimitiveType()) return false; - PrimitiveType primitiveType= (PrimitiveType)arrayType.getComponentType(); + PrimitiveType primitiveType= (PrimitiveType) arrayType.getElementType(); return (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID); } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/binary/StubCreator.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/binary/StubCreator.java index 625c49217f..cea24b6e28 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/binary/StubCreator.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/binary/StubCreator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2012 IBM Corporation and others. + * Copyright (c) 2006, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -134,8 +134,12 @@ protected void appendFlags(final IMember member) throws JavaModelException { } private void appendAnnotation(IAnnotation annotation) throws JavaModelException { + String name= annotation.getElementName(); + if (!fStubInvisible && name.startsWith("sun.")) //$NON-NLS-1$ + return; // skip Sun-internal annotations + fBuffer.append('@'); - fBuffer.append(annotation.getElementName()); + fBuffer.append(name); fBuffer.append('('); IMemberValuePair[] memberValuePairs= annotation.getMemberValuePairs(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java index 584ad6fe68..4868300f6c 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java @@ -790,7 +790,6 @@ private void createFieldsForAccessedLocals(CompilationUnitRewrite rewrite, IVari for (int i= 0; i < varBindings.length; i++) { VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); - fragment.setExtraDimensions(0); fragment.setInitializer(null); fragment.setName(ast.newSimpleName(fieldNames[i])); FieldDeclaration field= ast.newFieldDeclaration(fragment); @@ -869,7 +868,6 @@ private MethodDeclaration createNewConstructor(CompilationUnitRewrite rewrite, I MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setConstructor(true); - newConstructor.setExtraDimensions(0); newConstructor.setJavadoc(null); newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, fVisibility)); newConstructor.setName(ast.newSimpleName(fClassName)); @@ -940,7 +938,7 @@ private MethodDeclaration createNewConstructor(CompilationUnitRewrite rewrite, I } } - addExceptionsToNewConstructor(newConstructor); + addExceptionsToNewConstructor(newConstructor, importRewrite); if (doAddComments()) { try { @@ -1041,14 +1039,14 @@ private static boolean parameterTypesMatch(IMethodBinding m1, IMethodBinding m2) return true; } - private void addExceptionsToNewConstructor(MethodDeclaration newConstructor) { + private void addExceptionsToNewConstructor(MethodDeclaration newConstructor, ImportRewrite importRewrite) { IMethodBinding constructorBinding= getSuperConstructorBinding(); if (constructorBinding == null) return; ITypeBinding[] exceptions= constructorBinding.getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { - Name exceptionTypeName= fAnonymousInnerClassNode.getAST().newName(Bindings.getNameComponents(exceptions[i])); - newConstructor.thrownExceptions().add(exceptionTypeName); + Type exceptionType= importRewrite.addImport(exceptions[i], fAnonymousInnerClassNode.getAST()); + newConstructor.thrownExceptionTypes().add(exceptionType); } } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java index 5f3e904bcd..aaf11854e5 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExceptionAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,29 +39,29 @@ public boolean visit(ThrowStatement node) { if (exception == null) // Safety net for null bindings when compiling fails. return true; - addException(exception); + addException(exception, node.getAST()); return true; } @Override public boolean visit(MethodInvocation node) { - return handleExceptions((IMethodBinding)node.getName().resolveBinding()); + return handleExceptions((IMethodBinding)node.getName().resolveBinding(), node); } @Override public boolean visit(SuperMethodInvocation node) { - return handleExceptions((IMethodBinding)node.getName().resolveBinding()); + return handleExceptions((IMethodBinding)node.getName().resolveBinding(), node); } @Override public boolean visit(ClassInstanceCreation node) { - return handleExceptions(node.resolveConstructorBinding()); + return handleExceptions(node.resolveConstructorBinding(), node); } - private boolean handleExceptions(IMethodBinding binding) { + private boolean handleExceptions(IMethodBinding binding, ASTNode node) { if (binding == null) return true; - addExceptions(binding.getExceptionTypes()); + addExceptions(binding.getExceptionTypes(), node.getAST()); return true; } } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java index 54bde91e5c..a21a560fd0 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,6 +31,7 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; @@ -44,12 +45,14 @@ import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; +import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.LabeledStatement; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.Message; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Name; @@ -64,6 +67,7 @@ import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.TryStatement; import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; @@ -78,6 +82,7 @@ import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.LocalVariableIndex; import org.eclipse.jdt.internal.corext.dom.Selection; +import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.refactoring.Checks; import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext; @@ -86,10 +91,12 @@ import org.eclipse.jdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.code.flow.InputFlowAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.util.CodeAnalyzer; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.JavaElementLabels; +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.BindingLabelProvider; @@ -198,12 +205,31 @@ public ITypeBinding[] getTypeVariables() { //---- Activation checking --------------------------------------------------------------------------- + boolean isValidDestination(ASTNode node) { + boolean isInterface= node instanceof TypeDeclaration && ((TypeDeclaration) node).isInterface(); + return !(node instanceof AnnotationTypeDeclaration) && + !(isInterface && !JavaModelUtil.is18OrHigher(fCUnit.getJavaProject())); + } + public RefactoringStatus checkInitialConditions(ImportRewrite rewriter) { RefactoringStatus result= getStatus(); checkExpression(result); if (result.hasFatalError()) return result; + List validDestinations= new ArrayList(); + ASTNode destination= ASTResolving.findParentType(fEnclosingBodyDeclaration.getParent()); + while (destination != null) { + if (isValidDestination(destination)) { + validDestinations.add(destination); + } + destination= ASTResolving.findParentType(destination.getParent()); + } + if (validDestinations.size() == 0) { + result.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_no_valid_destination_type); + return result; + } + fReturnKind= UNDEFINED; fMaxVariableId= LocalVariableIndex.perform(fEnclosingBodyDeclaration); if (analyzeSelection(result).hasFatalError()) @@ -279,7 +305,12 @@ private void initReturnType(ImportRewrite rewriter) { } break; case RETURN_STATEMENT_VALUE: - if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { + LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode()); + if (enclosingLambdaExpr != null) { + fReturnType= ASTNodeFactory.newReturnType(enclosingLambdaExpr, ast, rewriter, null); + IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding(); + fReturnTypeBinding= methodBinding != null ? methodBinding.getReturnType() : null; + } else if (fEnclosingBodyDeclaration.getNodeType() == ASTNode.METHOD_DECLARATION) { fReturnType= ((MethodDeclaration) fEnclosingBodyDeclaration).getReturnType2(); fReturnTypeBinding= fReturnType != null ? fReturnType.resolveBinding() : null; } @@ -318,7 +349,13 @@ public void checkInput(RefactoringStatus status, String methodName, ASTNode dest ITypeBinding[] arguments= getArgumentTypes(); ITypeBinding type= ASTNodes.getEnclosingType(destination); status.merge(Checks.checkMethodInType(type, methodName, arguments)); - status.merge(Checks.checkMethodInHierarchy(type.getSuperclass(), methodName, null, arguments)); + ITypeBinding superClass= type.getSuperclass(); + if (superClass != null) { + status.merge(Checks.checkMethodInHierarchy(superClass, methodName, null, arguments)); + } + for (ITypeBinding superInterface : type.getInterfaces()) { + status.merge(Checks.checkMethodInHierarchy(superInterface, methodName, null, arguments)); + } } private ITypeBinding[] getArgumentTypes() { @@ -455,10 +492,19 @@ private Statement getParentLoopBody(ASTNode node) { } private boolean isVoidMethod() { - // if we have an initializer - if (fEnclosingMethodBinding == null) - return true; - ITypeBinding binding= fEnclosingMethodBinding.getReturnType(); + ITypeBinding binding= null; + LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode()); + if (enclosingLambdaExpr != null) { + IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding(); + if (methodBinding != null) { + binding= methodBinding.getReturnType(); + } + } else { + // if we have an initializer + if (fEnclosingMethodBinding == null) + return true; + binding= fEnclosingMethodBinding.getReturnType(); + } if (fEnclosingBodyDeclaration.getAST().resolveWellKnownType("void").equals(binding)) //$NON-NLS-1$ return true; return false; @@ -474,14 +520,29 @@ private void computeLastStatementSelected() { fIsLastStatementSelected= false; } else { Block body= null; - if (fEnclosingBodyDeclaration instanceof MethodDeclaration) { - body= ((MethodDeclaration) fEnclosingBodyDeclaration).getBody(); - } else if (fEnclosingBodyDeclaration instanceof Initializer) { - body= ((Initializer) fEnclosingBodyDeclaration).getBody(); + LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(getFirstSelectedNode()); + if (enclosingLambdaExpr != null) { + ASTNode lambdaBody= enclosingLambdaExpr.getBody(); + if (lambdaBody instanceof Block) { + body= (Block) lambdaBody; + } else { + fIsLastStatementSelected= true; + return; + } + } else { + if (fEnclosingBodyDeclaration instanceof MethodDeclaration) { + body= ((MethodDeclaration) fEnclosingBodyDeclaration).getBody(); + } else if (fEnclosingBodyDeclaration instanceof Initializer) { + body= ((Initializer) fEnclosingBodyDeclaration).getBody(); + } } if (body != null) { List statements= body.statements(); - fIsLastStatementSelected= nodes[nodes.length - 1] == statements.get(statements.size() - 1); + if (statements.size() > 0) { + fIsLastStatementSelected= nodes[nodes.length - 1] == statements.get(statements.size() - 1); + } else { + fIsLastStatementSelected= true; + } } } } @@ -698,7 +759,7 @@ public void endVisit(CompilationUnit node) { break superCall; } } - status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_only_method_body); + status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } fEnclosingBodyDeclaration= (BodyDeclaration)ASTNodes.getParent(getFirstSelectedNode(), BodyDeclaration.class); @@ -706,7 +767,7 @@ public void endVisit(CompilationUnit node) { (fEnclosingBodyDeclaration.getNodeType() != ASTNode.METHOD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.FIELD_DECLARATION && fEnclosingBodyDeclaration.getNodeType() != ASTNode.INITIALIZER)) { - status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_only_method_body); + status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_invalid_selection); break superCall; } else if (ASTNodes.getEnclosingType(fEnclosingBodyDeclaration) == null) { status.addFatalError(RefactoringCoreMessages.ExtractMethodAnalyzer_compile_errors_no_parent_binding); @@ -791,6 +852,43 @@ public boolean visit(DoStatement node) { return result; } + @Override + public boolean visit(LambdaExpression node) { + Selection selection= getSelection(); + int selectionStart= selection.getOffset(); + int selectionExclusiveEnd= selection.getExclusiveEnd(); + int lambdaStart= node.getStartPosition(); + int lambdaExclusiveEnd= lambdaStart + node.getLength(); + ASTNode body= node.getBody(); + int bodyStart= body.getStartPosition(); + int bodyExclusiveEnd= bodyStart + body.getLength(); + + boolean isValidSelection= false; + if ((body instanceof Block) && (bodyStart < selectionStart && selectionExclusiveEnd <= bodyExclusiveEnd)) { + // if selection is inside lambda body's block + isValidSelection= true; + } else if (body instanceof Expression) { + try { + TokenScanner scanner= new TokenScanner(fCUnit); + int arrowExclusiveEnd= scanner.getTokenEndOffset(ITerminalSymbols.TokenNameARROW, lambdaStart); + if (selectionStart >= arrowExclusiveEnd) { + isValidSelection= true; + } + } catch (CoreException e) { + // ignore + } + } + if (selectionStart <= lambdaStart && selectionExclusiveEnd >= lambdaExclusiveEnd) { + // if selection covers the lambda node + isValidSelection= true; + } + + if (!isValidSelection) { + return false; + } + return super.visit(node); + } + @Override public boolean visit(MethodDeclaration node) { Block body= node.getBody(); @@ -827,12 +925,24 @@ private boolean visitConstructorInvocation(ASTNode node, boolean superResult) { public boolean visit(VariableDeclarationFragment node) { boolean result= super.visit(node); if (isFirstSelectedNode(node)) { - invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node)); + if (node.getParent() instanceof FieldDeclaration) { + invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node)); + } else { + invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment, JavaStatusContext.create(fCUnit, node)); + } return false; } return result; } + @Override + public void endVisit(FieldDeclaration node) { + if (contains(getSelectedNodes(), node.fragments())) { + invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field, JavaStatusContext.create(fCUnit, node)); + } + super.endVisit(node); + } + @Override public void endVisit(ForStatement node) { if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) { diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java index 88d3675a4c..dd3edec034 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -77,7 +77,6 @@ import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.ReturnStatement; @@ -530,7 +529,7 @@ public Change createChange(IProgressMonitor pm) throws CoreException { TextEditGroup insertDesc= new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName))); result.addTextEditGroup(insertDesc); - if (fDestination == fDestinations[0]) { + if (fDestination == ASTResolving.findParentType(declaration.getParent())) { ChildListPropertyDescriptor desc= (ChildListPropertyDescriptor)declaration.getLocationInParent(); ListRewrite container= fRewriter.getListRewrite(declaration.getParent(), desc); container.insertAfter(mm, declaration, insertDesc); @@ -743,6 +742,10 @@ public boolean getGenerateJavadoc() { return fGenerateJavadoc; } + public boolean isDestinationInterface() { + return fDestination instanceof TypeDeclaration && ((TypeDeclaration) fDestination).isInterface(); + } + //---- Helper methods ------------------------------------------------------------------------ private void initializeParameterInfos() { @@ -791,29 +794,26 @@ private void initializeDuplicates() { private void initializeDestinations() { List result= new ArrayList(); BodyDeclaration decl= fAnalyzer.getEnclosingBodyDeclaration(); - ASTNode current= getNextParent(decl); - result.add(current); - if (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration) { + ASTNode current= ASTResolving.findParentType(decl.getParent()); + if (fAnalyzer.isValidDestination(current)) { + result.add(current); + } + if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) { ITypeBinding binding= ASTNodes.getEnclosingType(current); - ASTNode next= getNextParent(current); + ASTNode next= ASTResolving.findParentType(current.getParent()); while (next != null && binding != null && binding.isNested()) { - result.add(next); + if (fAnalyzer.isValidDestination(next)) { + result.add(next); + } current= next; binding= ASTNodes.getEnclosingType(current); - next= getNextParent(next); + next= ASTResolving.findParentType(next.getParent()); } } fDestinations= result.toArray(new ASTNode[result.size()]); fDestination= fDestinations[fDestinationIndex]; } - private ASTNode getNextParent(ASTNode node) { - do { - node= node.getParent(); - } while (node != null && !(node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration)); - return node; - } - private RefactoringStatus mergeTextSelectionStatus(RefactoringStatus status) { status.addFatalError(RefactoringCoreMessages.ExtractMethodRefactoring_no_set_of_statements); return status; @@ -989,18 +989,27 @@ private MethodDeclaration createNewMethodDeclaration() { MethodDeclaration result= fAST.newMethodDeclaration(); int modifiers= fVisibility; - ASTNode enclosingBodyDeclaration= fAnalyzer.getEnclosingBodyDeclaration(); - while (enclosingBodyDeclaration != null && enclosingBodyDeclaration.getParent() != fDestination) { - enclosingBodyDeclaration= enclosingBodyDeclaration.getParent(); + BodyDeclaration enclosingBodyDeclaration= fAnalyzer.getEnclosingBodyDeclaration(); + boolean isDestinationInterface= isDestinationInterface(); + if (isDestinationInterface && !(enclosingBodyDeclaration instanceof MethodDeclaration && + enclosingBodyDeclaration.getParent() == fDestination && + Modifier.isPublic(enclosingBodyDeclaration.getModifiers()))) { + modifiers= Modifier.NONE; } - if (enclosingBodyDeclaration instanceof BodyDeclaration) { // should always be the case - int enclosingModifiers= ((BodyDeclaration)enclosingBodyDeclaration).getModifiers(); - boolean shouldBeStatic= Modifier.isStatic(enclosingModifiers) - || enclosingBodyDeclaration instanceof EnumDeclaration - || fAnalyzer.getForceStatic() || forceStatic(); - if (shouldBeStatic) { - modifiers|= Modifier.STATIC; + + boolean shouldBeStatic= false; + ASTNode currentParent= enclosingBodyDeclaration; + do { + if (currentParent instanceof BodyDeclaration) { + shouldBeStatic= shouldBeStatic || JdtFlags.isStatic((BodyDeclaration) currentParent); } + currentParent= currentParent.getParent(); + } while (!shouldBeStatic && currentParent != null && currentParent != fDestination); + + if (shouldBeStatic || fAnalyzer.getForceStatic() || forceStatic()) { + modifiers|= Modifier.STATIC; + } else if (isDestinationInterface) { + modifiers|= Modifier.DEFAULT; } ITypeBinding[] typeVariables= computeLocalTypeVariables(modifiers); @@ -1033,11 +1042,11 @@ private MethodDeclaration createNewMethodDeclaration() { parameters.add(parameter); } - List exceptions= result.thrownExceptions(); + List exceptions= result.thrownExceptionTypes(); ITypeBinding[] exceptionTypes= fAnalyzer.getExceptions(fThrowRuntimeExceptions); for (int i= 0; i < exceptionTypes.length; i++) { ITypeBinding exceptionType= exceptionTypes[i]; - exceptions.add(ASTNodeFactory.newName(fAST, fImportRewriter.addImport(exceptionType, context))); + exceptions.add(fImportRewriter.addImport(exceptionType, fAST, context)); } return result; } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java index 0b274c5f0f..f7d98143da 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -61,7 +61,6 @@ import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.FieldDeclaration; @@ -672,8 +671,6 @@ private Name findConstantNameNode() { return null; if (node instanceof FieldAccess) node= ((FieldAccess) node).getName(); - if (node.getParent() instanceof EnumConstantDeclaration) - return null; if (!(node instanceof Name)) return null; Name name= (Name) node; diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java index c2930277e7..cf0ea9e99c 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceFactoryRefactoring.java @@ -743,12 +743,10 @@ private void createFactoryMethodSignature(AST ast, MethodDeclaration newMethod) } ITypeBinding[] ctorExcepts= fCtorBinding.getExceptionTypes(); - List exceptions= newMethod.thrownExceptions(); + List exceptions= newMethod.thrownExceptionTypes(); for(int i=0; i < ctorExcepts.length; i++) { - String excName= fImportRewriter.addImport(ctorExcepts[i]); - - exceptions.add(ASTNodeFactory.newName(ast, excName)); + exceptions.add(fImportRewriter.addImport(ctorExcepts[i], ast)); } copyTypeParameters(ast, newMethod); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java index 6442815d4d..a4bcc0c59d 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceIndirectionRefactoring.java @@ -948,8 +948,8 @@ private void copyTypeParameters(MethodDeclaration intermediary, CompilationUnitR private void copyExceptions(MethodDeclaration intermediary, CompilationUnitRewrite imRewrite) { ITypeBinding[] exceptionTypes= fTargetMethodBinding.getExceptionTypes(); for (int i= 0; i < exceptionTypes.length; i++) { - final String qualifiedName= imRewrite.getImportRewrite().addImport(exceptionTypes[i]); - intermediary.thrownExceptions().add(ASTNodeFactory.newName(imRewrite.getAST(), qualifiedName)); + Type exceptionType= imRewrite.getImportRewrite().addImport(exceptionTypes[i], imRewrite.getAST()); + intermediary.thrownExceptionTypes().add(exceptionType); } } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java index d0939154cb..774f96e119 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -48,6 +48,7 @@ import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConstructorInvocation; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IBinding; @@ -76,6 +77,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.dom.HierarchicalASTVisitor; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModel; @@ -97,6 +99,7 @@ import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.ui.JavaElementLabels; +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.BindingLabelProvider; @@ -328,6 +331,10 @@ public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws Core if (isTempAnExceptionInCatchBlock()) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_exceptions); + ASTNode declaringType= ASTResolving.findParentType(fTempDeclarationNode); + if (declaringType instanceof TypeDeclaration && ((TypeDeclaration) declaringType).isInterface()) + return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.PromoteTempToFieldRefactoring_interface_methods); + result.merge(checkTempTypeForLocalTypeUsage()); if (result.hasFatalError()) return result; @@ -832,7 +839,8 @@ private FieldDeclaration createNewFieldDeclaration(ASTRewrite rewrite) { SimpleName variableName= ast.newSimpleName(fFieldName); fragment.setName(variableName); addLinkedName(rewrite, variableName, false); - fragment.setExtraDimensions(fTempDeclarationNode.getExtraDimensions()); + List extraDimensions= DimensionRewrite.copyDimensions(fTempDeclarationNode.extraDimensions(), rewrite); + fragment.extraDimensions().addAll(extraDimensions); if (fInitializeIn == INITIALIZE_IN_FIELD && tempHasInitializer()){ Expression initializer= (Expression)rewrite.createCopyTarget(getTempInitializer()); fragment.setInitializer(initializer); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java index 06b797bd98..8098073567 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -60,11 +60,13 @@ import org.eclipse.jdt.core.dom.InstanceofExpression; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.LabeledStatement; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MarkerAnnotation; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.NullLiteral; import org.eclipse.jdt.core.dom.NumberLiteral; @@ -682,6 +684,16 @@ public void endVisit(LabeledStatement node) { info.removeLabel(node.getLabel()); } + @Override + public void endVisit(LambdaExpression node) { + if (skipNode(node)) + return; + GenericSequentialFlowInfo info= createSequential(node); + process(info, node.parameters()); + process(info, node.getBody()); + info.setNoReturn(); + } + @Override public void endVisit(MarkerAnnotation node) { // nothing to do for marker annotations; @@ -711,7 +723,7 @@ public void endVisit(MethodDeclaration node) { return; GenericSequentialFlowInfo info= processSequential(node, node.getReturnType2()); process(info, node.parameters()); - process(info, node.thrownExceptions()); + process(info, node.thrownExceptionTypes()); process(info, node.getBody()); } @@ -720,6 +732,13 @@ public void endVisit(MethodInvocation node) { endVisitMethodInvocation(node, node.getExpression(), node.arguments(), getMethodBinding(node.getName())); } + @Override + public void endVisit(NameQualifiedType node) { + if (skipNode(node)) + return; + processSequential(node, node.getQualifier(), node.getName()); + } + @Override public void endVisit(NormalAnnotation node) { if (skipNode(node)) diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties index b65e5b7d8f..aea9fa32d1 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2013 IBM Corporation and others. +# Copyright (c) 2000, 2014 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -33,7 +33,7 @@ Checks_cu_has_compile_errors=Code modification may not be accurate as affected r Checks_no_dot=Type name cannot contain a dot (.). Checks_cu_name_used=Compilation unit ''{0}'' already exists Checks_method_native=Method ''{1}'' in type ''{0}'' is native. Running the modified program will cause {2}. -Checks_methodName_constructor=New method name has constructor name. +Checks_methodName_constructor=New method has same name as constructor of type ''{0}''. Checks_methodName_exists=Method ''{0}'' already exists in type ''{1}''. Checks_methodName_overrides=New method ''{0}'' overrides an existing method in type ''{1}''. Checks_methodName_returnTypeClash=New method ''{0}'' overrides a method declared in type ''{1}'' that uses a different return type. @@ -104,7 +104,7 @@ LocalTypeAnalyzer_local_type_referenced_outside=A local type declared in the sel FlowAnalyzer_execution_flow=Selected statements contain a return statement but not all possible execution flows end in a return. Semantics may not be preserved if you proceed. ExtractMethodAnalyzer_assignments_to_local=Ambiguous return value: Selected block modifies more than one local variable used in subsequent code. Affected variables are:\n\n{0} -ExtractMethodAnalyzer_only_method_body=Cannot extract new method from selection. Only statements from a method body can be extracted. +ExtractMethodAnalyzer_invalid_selection=Cannot extract new method since the selection is not valid. ExtractMethodAnalyzer_after_do_keyword=Selection may not start immediately after the \'do\' keyword. ExtractMethodAnalyzer_super_or_this=Cannot extract super or this call from constructor. ExtractMethodAnalyzer_cannot_determine_return_type=Cannot determine expression's return type. Using void instead. @@ -114,6 +114,7 @@ ExtractMethodAnalyzer_branch_mismatch=Selection contains branch statement but co ExtractMethodAnalyzer_parent_mismatch=Not all selected statements are enclosed by the same parent statement. ExtractMethodAnalyzer_cannot_extract_anonymous_type=Cannot extract the body of a anonymous type declaration. Select whole declaration. ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment=Cannot extract a variable declaration fragment. Select whole declaration statement. +ExtractMethodAnalyzer_cannot_extract_variable_declaration_fragment_from_field=Cannot extract a variable declaration fragment from field declaration. ExtractMethodAnalyzer_cannot_extract_for_initializer=Cannot extract initialization part of a \'for\' statement. ExtractMethodAnalyzer_cannot_extract_for_updater=Cannot extract increment part of a \'for\' statement. ExtractMethodAnalyzer_cannot_extract_from_annotation=Cannot extract out of an annotation. @@ -121,14 +122,15 @@ ExtractMethodAnalyzer_cannot_extract_variable_declaration=Cannot extract parts o ExtractMethodAnalyzer_cannot_extract_type_reference=Cannot extract a single type reference. ExtractMethodAnalyzer_cannot_extract_switch_case=Cannot extract the expression of a case statement. ExtractMethodAnalyzer_cannot_extract_method_name_reference=Cannot extract a single method name. -ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name=Can not extract part of a qualified name +ExtractMethodAnalyzer_cannot_extract_part_of_qualified_name=Cannot extract part of a qualified name ExtractMethodAnalyzer_cannot_extract_name_in_declaration=Cannot extract the name part of a declaration. -ExtractMethodAnalyzer_compile_errors_no_parent_binding=The selection cannot cannot be analyzed because of compilation errors in the enclosing type. To perform the operation you will need to fix the errors. +ExtractMethodAnalyzer_compile_errors_no_parent_binding=The selection cannot be analyzed because of compilation errors in the enclosing type. To perform the operation you will need to fix the errors. ExtractMethodAnalyzer_ambiguous_return_value=Ambiguous return value: Expression, access to local or return statement extracted. ExtractMethodAnalyzer_compile_errors=The method''s body cannot be analyzed because of compilation errors in method ''{0}''. To perform the operation you will need to fix the errors. ExtractMethodAnalyzer_leftHandSideOfAssignment=Cannot extract the left-hand side of an assignment. ExtractMethodAnalyzer_single_expression_or_set=Can only extract a single expression or a set of statements. ExtractMethodAnalyzer_cannot_extract_null_type=Cannot extract null expression. +ExtractMethodAnalyzer_no_valid_destination_type=No valid destination type exists. ExtractMethodAnalyzer_resource_in_try_with_resources=Cannot extract a resource declared in a 'try-with-resources' statement. ExtractMethodRefactoring_name=Extract Method @@ -151,7 +153,7 @@ ExtractMethodRefactoring_error_vararg_ordering=The variable arity parameter ''{0 ExtractMethodRefactoring_descriptor_description=Extract method ''{0}'' from ''{1}'' to ''{2}'' ExtractMethodRefactoring_descriptor_description_short=Extract method ''{0}'' ExtractMethodRefactoring_destination_pattern=Destination type: ''{0}'' -ExtractMethodRefactoring_default_visibility=(default) +ExtractMethodRefactoring_default_visibility=(package) ExtractMethodRefactoring_declare_thrown_exceptions=Declare thrown runtime exceptions #-- Inline Method ------------------------------------------------------ @@ -234,7 +236,7 @@ SelfEncapsulateField_getter_pattern=Getter method name: ''{0}'' SelfEncapsulateField_setter_pattern=Setter method name: ''{0}'' SelfEncapsulateField_change_visibility=Change visibility to private SelfEncapsulateField_original_pattern=Original element: ''{0}'' -SelfEncapsulateField_default_visibility=(default) +SelfEncapsulateField_default_visibility=(package) SelfEncapsulateField_visibility_pattern=Field visibility: ''{0}'' SelfEncapsulateField_generate_comments=Generate method comments SelfEncapsulateField_add_setter=Add Setter method @@ -331,7 +333,7 @@ ExtractConstantRefactoring_visibility_pattern=Declared visibility: ''{0}'' ExtractConstantRefactoring_replace_occurrences=Replace occurrences of expression with constant ExtractConstantRefactoring_qualify_references=Qualify references to constant ExtractConstantRefactoring_declare_constant=Add constant declaration -ExtractConstantRefactoring_default_visibility=(default) +ExtractConstantRefactoring_default_visibility=(package) ExtractConstantRefactoring_replace=Replace expression with constant reference ExtractConstantRefactoring_another_variable=A variable with name ''{0}'' is already defined in the visible scope. ExtractConstantRefactoring_no_void=Cannot extract an expression of type \'void\'. @@ -534,6 +536,7 @@ ReplaceInvocationsRefactoring_cannot_replace_in_binary=Cannot replace invocation RenameTempRefactoring_must_select_local=A local variable declaration or reference must be selected to activate this refactoring RenameTempRefactoring_only_in_methods_and_initializers=Only local variables declared in methods and initializers can be renamed +RenameTempRefactoring_only_in_methods_initializers_and_lambda=Only local variables declared in methods, initializers and lambda expression can be renamed RenameTempRefactoring_lowercase=This name is discouraged. According to convention, names of local variables should start with a lowercase letter. RenameTempRefactoring_lowercase2=The variable name ''{0}'' in ''{1}'' (type ''{2}'') is discouraged. According to convention, names of local variables should start with a lowercase letter. RenameTempRefactoring_rename=Rename Local Variable @@ -612,7 +615,7 @@ PullUpRefactoring_field_not_accessible=Field ''{0}'' referenced in one of the mo PullUpRefactoring_method_not_accessible=Method ''{0}'' referenced in one of the moved elements is not accessible from type ''{1}'' PullUpRefactoring_different_method_return_type=Method ''{0}'' declared in type''{1}'' has a different return type than its moved counterpart, which will result in compile errors if you proceed PullUpRefactoring_different_field_type=Field ''{0}'' declared in type ''{1}'' has a different type than its moved counterpart -PullUpRefactoring_lower_default_visibility=Method ''{0}'' declared in type ''{1}'' has visibility lower than ''default'', which will result in compile errors if you proceed +PullUpRefactoring_lower_default_visibility=Method ''{0}'' declared in type ''{1}'' has visibility lower than ''package'', which will result in compile errors if you proceed PullUpRefactoring_lower_protected_visibility=Method ''{0}'' declared in type ''{1}'' has visibility lower than ''protected'', which will result in compile errors if you proceed PullUpRefactoring_checking=Checking preconditions... PullUpRefactoring_add_method_stub=Add method stub @@ -654,8 +657,10 @@ MoveMembersRefactoring_deleteMembers= Delete members MoveMembersRefactoring_addMembers= Add members MoveMembersRefactoring_referenceUpdate= Update reference to moved member MoveMembersRefactoring_static_declaration=Static members can be declared only in top level or static types. +MoveMembersRefactoring_member_will_be_public=Moved member will be public in the destination interface MoveMembersRefactoring_multi_var_fields=Only field declarations with single variable declaration fragments can be moved. MoveMembersRefactoring_only_public_static=Only 'public static' types and 'public static final' fields with variable initializers can be moved to an interface. +MoveMembersRefactoring_only_public_static_18=Only 'public static' types, 'public static' methods and 'public static final' fields with variable initializers can be moved to an interface. MoveMembersRefactoring_Object=Move is not allowed on members declared in 'java.lang.Object'. MoveMembersRefactoring_binary=Pull up is not allowed on members of binary types. MoveMembersRefactoring_read_only=Pull up is not allowed on members of read-only types. @@ -783,13 +788,14 @@ ChangeSignatureRefactoring_duplicate_name=Duplicate parameter name: ''{0}''. ChangeSignatureRefactoring_return_type_contains_type_variable=The return type ''{0}'' contains the type variable ''{1}'', which may not be available in related methods. ChangeSignatureRefactoring_method_name_not_empty=The method name cannot be empty. ChangeSignatureRefactoring_default_value=Enter the default value for parameter ''{0}''. -ChangeSignatureRefactoring_default_visibility=(default) +ChangeSignatureRefactoring_default_visibility=(package) ChangeSignatureRefactoring_invalid_expression=''{0}'' is not a valid expression. ChangeSignatureRefactoring_parameter_type_contains_type_variable=The type ''{0}'' of parameter ''{1}'' contains the type variable ''{2}'', which may not be available in related methods. ChangeSignatureRefactoring_old_and_new_signatures_not_sufficiently_different=The old and new method signatures do not differ sufficiently for creating a delegate method. Delegate will introduce compile errors. ChangeSignatureRefactoring_unchanged=Method signature and return type are unchanged. ChangeSignatureRefactoring_parameter_used=Removed parameter ''{0}'' is used in method ''{1}'' declared in type ''{2}''. ChangeSignatureRefactoring_anonymous_subclass=anonymous subclass of ''{0}'' +ChangeSignatureRefactoring_lambda_expression=lambda expression implemented in ''{0}'' ChangeSignatureRefactoring_removed_parameters=Removed parameters: ChangeSignatureRefactoring_removed_exceptions=Removed exceptions: ChangeSignatureRefactoring_non_virtual=Changing visibility to \'private\' will make this method non-virtual, which may affect the program\'s behavior. @@ -839,7 +845,7 @@ MoveInnerToTopRefactoring_descriptor_description_short=Move type ''{0}'' to new MoveInnerToTopRefactoring_update_constructor_reference=Update constructor occurrence MoveInnerToTopRefactoring_move_to_Top=Move Type to New File MoveInnerToTopRefactoring_parameter_pattern=Parameter name: ''{0}'' -MoveInnerToTopRefactoring_change_visibility_type_warning=The visibility of type ''{0}'' will be changed to default. +MoveInnerToTopRefactoring_change_visibility_type_warning=The visibility of type ''{0}'' will be changed to package. MoveInnerToTopRefactoring_change_qualifier=Qualify class name MoveInnerToTopRefactoring_type_exists=Type named ''{0}'' already exists in package ''{1}'' @@ -924,7 +930,7 @@ MemberVisibilityAdjustor_change_visibility_type_warning=The visibility of type ' MemberVisibilityAdjustor_change_visibility_method_warning=The visibility of method ''{0}'' will be changed to {1}. MemberVisibilityAdjustor_change_visibility_field_warning=The visibility of field ''{0}'' will be changed to {1}. #End - Do not remove -MemberVisibilityAdjustor_change_visibility_default=default +MemberVisibilityAdjustor_change_visibility_default=package MemberVisibilityAdjustor_change_visibility_public=public MemberVisibilityAdjustor_change_visibility_protected=protected MemberVisibilityAdjustor_change_visibility_private=private @@ -966,7 +972,7 @@ MovePackageFragmentRootChange_move=Move Package Fragment Root ''{0}'' to ''{1}'' PromoteTempToFieldRefactoring_name=Convert Local Variable to Field PromoteTempToFieldRefactoring_select_declaration=Select a declaration or a reference to a local variable. -PromoteTempToFieldRefactoring_default_visibility=(default) +PromoteTempToFieldRefactoring_default_visibility=(package) PromoteTempToFieldRefactoring_visibility_pattern=Declared visibility: ''{0}'' PromoteTempToFieldRefactoring_only_declared_in_methods=Only local variables declared in methods can be converted to fields. PromoteTempToFieldRefactoring_method_parameters=Cannot convert method parameters to fields. @@ -984,6 +990,7 @@ PromoteTempToFieldRefactoring_descriptor_description=Convert local variable ''{0 PromoteTempToFieldRefactoring_descriptor_description_short=Convert local variable ''{0}'' to field PromoteTempToFieldRefactoring_initialize_constructor=Initialize field in class constructor PromoteTempToFieldRefactoring_initialize_declaration=Initialize field in declaration +PromoteTempToFieldRefactoring_interface_methods=Cannot convert local variables declared in interface methods to fields. PromoteTempToFieldRefactoring_declare_final_static=Declare field 'final' and 'static' PromoteTempToFieldRefactoring_editName=Convert local variable to field @@ -1002,7 +1009,7 @@ ConvertAnonymousToNestedRefactoring_declare_final_static=Declare class \'final\' ConvertAnonymousToNestedRefactoring_extends_local_class=Cannot convert this anonymous class to a nested class since it extends a local class. ConvertAnonymousToNestedRefactoring_class_name_pattern=Class name: ''{0}'' ConvertAnonymousToNestedRefactoring_visibility_pattern=Declared visibility: ''{0}'' -ConvertAnonymousToNestedRefactoring_default_visibility=(default) +ConvertAnonymousToNestedRefactoring_default_visibility=(package) ConvertAnonymousToNestedRefactoring_original_pattern=Original element: ''{0}'' InlineConstantRefactoring_Inline=Inline Constant diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java index 8aca3a1784..7d88247d25 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/MethodOccurenceCollector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -13,9 +13,11 @@ import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; +import org.eclipse.jdt.core.search.MethodDeclarationMatch; import org.eclipse.jdt.core.search.MethodReferenceMatch; import org.eclipse.jdt.core.search.SearchMatch; @@ -58,6 +60,14 @@ public void acceptSearchMatch(ICompilationUnit unit, SearchMatch match) throws C return; } + // lambda expression + if (match instanceof MethodDeclarationMatch + && match.getElement() instanceof IMethod + && ((IMethod) match.getElement()).isLambdaMethod()) { + // don't touch the lambda + return; + } + //Not a standard reference -- use scanner to find last identifier token before left parenthesis: IScanner scanner= getScanner(unit); scanner.setSource(matchText.toCharArray()); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java index 525e0d308c..78e8e9b8d2 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,6 +27,7 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.SimpleName; @@ -63,6 +64,10 @@ public static RefactoringStatus reportProblemNodes(String modifiedWorkingCopySou return result; } + public static LambdaExpression getLambdaExpression(TextEdit edit, TextChange change, CompilationUnit cuNode) { + ASTNode decl= RefactoringAnalyzeUtil.findSimpleNameNode(RefactoringAnalyzeUtil.getNewTextRange(edit, change), cuNode); + return ((LambdaExpression) ASTNodes.getParent(decl, LambdaExpression.class)); + } public static MethodDeclaration getMethodDeclaration(TextEdit edit, TextChange change, CompilationUnit cuNode){ ASTNode decl= RefactoringAnalyzeUtil.findSimpleNameNode(RefactoringAnalyzeUtil.getNewTextRange(edit, change), cuNode); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java index 376fd243bc..c80f0b387a 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameAnalyzeUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -424,7 +424,7 @@ public static RefactoringStatus analyzeLocalRenames(LocalAnalyzePackage[] analyz return result; for (int i= 0; i < analyzePackages.length; i++) { - ASTNode enclosing= getEnclosingBlockOrMethod(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode); + ASTNode enclosing= getEnclosingBlockOrMethodOrLambda(analyzePackages[i].fDeclarationEdit, cuChange, newCUNode); // get new declaration IRegion newRegion= RefactoringAnalyzeUtil.getNewTextRange(analyzePackages[i].fDeclarationEdit, cuChange); @@ -452,10 +452,12 @@ private static VariableDeclaration getVariableDeclaration(Name node) { return null; } - private static ASTNode getEnclosingBlockOrMethod(TextEdit declarationEdit, TextChange change, CompilationUnit newCUNode) { + private static ASTNode getEnclosingBlockOrMethodOrLambda(TextEdit declarationEdit, TextChange change, CompilationUnit newCUNode) { ASTNode enclosing= RefactoringAnalyzeUtil.getBlock(declarationEdit, change, newCUNode); if (enclosing == null) enclosing= RefactoringAnalyzeUtil.getMethodDeclaration(declarationEdit, change, newCUNode); + if (enclosing == null) + enclosing= RefactoringAnalyzeUtil.getLambdaExpression(declarationEdit, change, newCUNode); return enclosing; } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java index 723445f767..354cf34555 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameLocalVariableProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,11 +41,12 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Initializer; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.VariableDeclaration; -import org.eclipse.jdt.core.refactoring.IJavaRefactorings; import org.eclipse.jdt.core.refactoring.CompilationUnitChange; +import org.eclipse.jdt.core.refactoring.IJavaRefactorings; import org.eclipse.jdt.core.refactoring.descriptors.RenameJavaElementDescriptor; import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; @@ -62,6 +63,7 @@ import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; import org.eclipse.jdt.internal.corext.refactoring.util.TextChangeManager; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.JavaElementLabels; @@ -218,9 +220,15 @@ public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws Core initAST(); if (fTempDeclarationNode == null || fTempDeclarationNode.resolveBinding() == null) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_must_select_local); - if (! Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class) - && ! Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class)) + + if (!Checks.isDeclaredIn(fTempDeclarationNode, MethodDeclaration.class) + && !Checks.isDeclaredIn(fTempDeclarationNode, Initializer.class) + && !Checks.isDeclaredIn(fTempDeclarationNode, LambdaExpression.class)) { + if (JavaModelUtil.is18OrHigher(fCu.getJavaProject())) + return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_initializers_and_lambda); + return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.RenameTempRefactoring_only_in_methods_and_initializers); + } initNames(); return new RefactoringStatus(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java index f75eb357eb..ef03139567 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,13 +53,13 @@ import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IMethodBinding; @@ -89,6 +89,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.dom.VariableDeclarationRewrite; import org.eclipse.jdt.internal.corext.refactoring.Checks; import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment; @@ -626,7 +627,8 @@ private MethodDeclaration createSetterMethod(AST ast, ASTRewrite rewriter, Strin result.parameters().add(param); param.setName(ast.newSimpleName(fArgName)); param.setType((Type)rewriter.createCopyTarget(type)); - param.setExtraDimensions(fFieldDeclaration.getExtraDimensions()); + List extraDimensions= DimensionRewrite.copyDimensions(fFieldDeclaration.extraDimensions(), rewriter); + param.extraDimensions().addAll(extraDimensions); Block block= ast.newBlock(); result.setBody(block); @@ -667,19 +669,7 @@ private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, Strin MethodDeclaration result= ast.newMethodDeclaration(); result.setName(ast.newSimpleName(fGetterName)); result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers())); - Type returnType; - if (fFieldDeclaration.getExtraDimensions() > 0) { - if (type instanceof ArrayType) { - ArrayType arrayType= (ArrayType)type; - returnType= (Type)rewriter.createCopyTarget(arrayType.getElementType()); - returnType= ast.newArrayType(returnType, fFieldDeclaration.getExtraDimensions() + arrayType.getDimensions()); - - } else { - returnType= (Type)rewriter.createCopyTarget(type); - returnType= ast.newArrayType(returnType, fFieldDeclaration.getExtraDimensions()); - } - } else - returnType= (Type)rewriter.createCopyTarget(type); + Type returnType= DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter); result.setReturnType2(returnType); Block block= ast.newBlock(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java index 00b60601e6..c7ffac2e44 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -62,13 +62,16 @@ import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConstructorInvocation; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.EnumConstantDeclaration; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.Javadoc; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MemberRef; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; @@ -86,6 +89,8 @@ import org.eclipse.jdt.core.dom.TagElement; import org.eclipse.jdt.core.dom.TextElement; import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.VariableDeclaration; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; @@ -780,11 +785,11 @@ private RefactoringStatus createExceptionInfoList() { if (nameNode == null || !(nameNode instanceof Name) || !(nameNode.getParent() instanceof MethodDeclaration)) return null; MethodDeclaration methodDeclaration= (MethodDeclaration) nameNode.getParent(); - List exceptions= methodDeclaration.thrownExceptions(); + List exceptions= methodDeclaration.thrownExceptionTypes(); List result= new ArrayList(exceptions.size()); for (int i= 0; i < exceptions.size(); i++) { - Name name= exceptions.get(i); - ITypeBinding typeBinding= name.resolveTypeBinding(); + Type type= exceptions.get(i); + ITypeBinding typeBinding= type.resolveBinding(); if (typeBinding == null) return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ChangeSignatureRefactoring_no_exception_binding); IJavaElement element= typeBinding.getJavaElement(); @@ -890,8 +895,11 @@ public String getOldMethodSignature() throws JavaModelException{ int flags= getMethod().getFlags(); buff.append(getVisibilityString(flags)); - if (Flags.isStatic(flags)) + if (Flags.isStatic(flags)) { buff.append("static "); //$NON-NLS-1$ + } else if (Flags.isDefaultMethod(flags)) { + buff.append("default "); //$NON-NLS-1$ + } if (! getMethod().isConstructor()) buff.append(fReturnTypeInfo.getOldTypeName()) .append(' '); @@ -912,8 +920,12 @@ public String getNewMethodSignature() throws JavaModelException{ StringBuffer buff= new StringBuffer(); buff.append(getVisibilityString(fVisibility)); - if (Flags.isStatic(getMethod().getFlags())) + int flags= getMethod().getFlags(); + if (Flags.isStatic(flags)) { buff.append("static "); //$NON-NLS-1$ + } else if (Flags.isDefaultMethod(flags)) { + buff.append("default "); //$NON-NLS-1$ + } if (! getMethod().isConstructor()) buff.append(getReturnTypeString()) .append(' '); @@ -1511,7 +1523,6 @@ private void addNewConstructorToSubclass(AbstractTypeDeclaration subclass, Compi MethodDeclaration newConstructor= ast.newMethodDeclaration(); newConstructor.setName(ast.newSimpleName(subclass.getName().getIdentifier())); newConstructor.setConstructor(true); - newConstructor.setExtraDimensions(0); newConstructor.setJavadoc(null); newConstructor.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getAccessModifier(subclass))); newConstructor.setReturnType2(ast.newPrimitiveType(PrimitiveType.VOID)); @@ -1649,6 +1660,12 @@ else if (node instanceof MemberRef || node instanceof MethodRef) else if (ASTNodes.getParent(node, ImportDeclaration.class) != null) return new StaticImportUpdate((ImportDeclaration) ASTNodes.getParent(node, ImportDeclaration.class), cuRewrite, result); + else if (node instanceof LambdaExpression) + return new LambdaExpressionUpdate((LambdaExpression) node, cuRewrite, result); + + else if (node instanceof ExpressionMethodReference) + return new ExpressionMethodRefUpdate((ExpressionMethodReference) node, cuRewrite, result); + else return new NullOccurrenceUpdate(node, cuRewrite, result); } @@ -1680,6 +1697,10 @@ protected final CompilationUnitRewrite getCompilationUnitRewrite() { return fCuRewrite; } + protected int getStartPosition() { + return getMethodNameNode().getStartPosition(); + } + public abstract void updateNode() throws CoreException; protected void registerImportRemoveNode(ASTNode node) { @@ -1838,10 +1859,12 @@ protected final void replaceTypeNode(Type typeNode, String newTypeName, ITypeBin protected final void changeMethodName() { if (! isMethodNameSameAsInitial()) { SimpleName nameNode= getMethodNameNode(); - SimpleName newNameNode= nameNode.getAST().newSimpleName(fMethodName); - getASTRewrite().replace(nameNode, newNameNode, fDescription); - registerImportRemoveNode(nameNode); - getTightSourceRangeComputer().addTightSourceNode(nameNode); + if (nameNode != null) { + SimpleName newNameNode= nameNode.getAST().newSimpleName(fMethodName); + getASTRewrite().replace(nameNode, newNameNode, fDescription); + registerImportRemoveNode(nameNode); + getTightSourceRangeComputer().addTightSourceNode(nameNode); + } } } @@ -1849,12 +1872,12 @@ protected final Type createNewTypeNode(String newTypeName, ITypeBinding newTypeB Type newTypeNode; if (newTypeBinding == null) { if (fDefaultValueAdvisor != null) - newTypeNode= fDefaultValueAdvisor.createType(newTypeName, getMethodNameNode().getStartPosition(), getCompilationUnitRewrite()); + newTypeNode= fDefaultValueAdvisor.createType(newTypeName, getStartPosition(), getCompilationUnitRewrite()); else newTypeNode= (Type) getASTRewrite().createStringPlaceholder(newTypeName, ASTNode.SIMPLE_TYPE); //Don't import if not resolved. } else { - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), getMethodNameNode().getStartPosition(), getImportRewrite()); + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), getStartPosition(), getImportRewrite()); newTypeNode= getImportRewrite().addImport(newTypeBinding, fCuRewrite.getAST(), importRewriteContext); getImportRemover().registerAddedImports(newTypeNode); } @@ -1979,7 +2002,194 @@ private boolean isSameMethod(IMethodBinding m1, IMethodBinding m2) { } - class DeclarationUpdate extends OccurrenceUpdate { + + class ExpressionMethodRefUpdate extends OccurrenceUpdate { + private ExpressionMethodReference fMethodRef; + + protected ExpressionMethodRefUpdate(ExpressionMethodReference decl, CompilationUnitRewrite cuRewrite, RefactoringStatus result) { + super(cuRewrite, cuRewrite.createGroupDescription(RefactoringCoreMessages.ChangeSignatureRefactoring_change_signature), result); + fMethodRef= decl; + } + + @Override + public void updateNode() throws CoreException { + if (canChangeNameAndReturnType()) + changeMethodName(); + } + + @Override + protected SimpleName getMethodNameNode() { + return fMethodRef.getName(); + } + + @Override + protected ListRewrite getParamgumentsRewrite() { + return null; + } + + @Override + protected VariableDeclaration createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) { + return null; + } + + } + + /** + * Abstraction for handling MethodDeclaration and LambdaExpression updates. + * @param type of the parameter nodes + */ + abstract class AbstractDeclarationUpdate extends OccurrenceUpdate { + + protected AbstractDeclarationUpdate(CompilationUnitRewrite cuRewrite, TextEditGroup description, RefactoringStatus result) { + super(cuRewrite, description, result); + } + + protected abstract ASTNode getNode(); + + protected abstract VariableDeclaration getParameter(int index); + + @Override + protected void changeParamgumentName(ParameterInfo info) { + VariableDeclaration param= getParameter(info.getOldIndex()); + if (!info.getOldName().equals(param.getName().getIdentifier())) + return; //don't change if original parameter name != name in rippleMethod + + String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_update_parameter_references; + TextEditGroup description= fCuRewrite.createGroupDescription(msg); + TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(param, false); + analyzer.perform(); + SimpleName[] paramOccurrences= analyzer.getReferenceAndDeclarationNodes(); // @param tags are updated in changeJavaDocTags() + for (int j= 0; j < paramOccurrences.length; j++) { + SimpleName occurence= paramOccurrences[j]; + getASTRewrite().set(occurence, SimpleName.IDENTIFIER_PROPERTY, info.getNewName(), description); + } + } + + @Override + protected void changeParamgumentType(ParameterInfo info) { + VariableDeclaration oldParam= getParameter(info.getOldIndex()); + if (oldParam instanceof SingleVariableDeclaration) { + getASTRewrite().set(oldParam, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.valueOf(info.isNewVarargs()), fDescription); + SingleVariableDeclaration oldSVDParam= (SingleVariableDeclaration) oldParam; + replaceTypeNode(oldSVDParam.getType(), ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding()); + removeExtraDimensions(oldSVDParam); + } + } + + private void removeExtraDimensions(SingleVariableDeclaration oldParam) { + ListRewrite listRewrite= getASTRewrite().getListRewrite(oldParam, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY); + for (Dimension dimension : (List) oldParam.extraDimensions()) { + listRewrite.remove(dimension, fDescription); + } + } + + //TODO: already reported as compilation error -> don't report there? + protected void checkIfDeletedParametersUsed() { + for (Iterator iter= getDeletedInfos().iterator(); iter.hasNext();) { + ParameterInfo info= iter.next(); + VariableDeclaration paramDecl= getParameter(info.getOldIndex()); + TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(paramDecl, false); + analyzer.perform(); + SimpleName[] paramRefs= analyzer.getReferenceNodes(); + + if (paramRefs.length > 0) { + RefactoringStatusContext context= JavaStatusContext.create(fCuRewrite.getCu(), paramRefs[0]); + String typeName= getFullTypeName(); + Object[] keys= new String[] { BasicElementLabels.getJavaElementName(paramDecl.getName().getIdentifier()), + BasicElementLabels.getJavaElementName(getMethod().getElementName()), + BasicElementLabels.getJavaElementName(typeName) }; + String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_parameter_used, keys); + fResult.addError(msg, context); + } + } + } + + protected String getFullTypeName() { + ASTNode node= getNode(); + while (true) { + node= node.getParent(); + if (node instanceof AbstractTypeDeclaration) { + String typeName= ((AbstractTypeDeclaration) node).getName().getIdentifier(); + if (getNode() instanceof LambdaExpression) { + return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_lambda_expression, typeName); + } + return typeName; + } else if (node instanceof ClassInstanceCreation) { + ClassInstanceCreation cic= (ClassInstanceCreation) node; + return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(cic.getType()))); + } else if (node instanceof EnumConstantDeclaration) { + EnumDeclaration ed= (EnumDeclaration) node.getParent(); + return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(ed.getName()))); + } + } + } + + protected SingleVariableDeclaration createNewSingleVariableDeclaration(ParameterInfo info) { + SingleVariableDeclaration newP= getASTRewrite().getAST().newSingleVariableDeclaration(); + newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName())); + newP.setType(createNewTypeNode(ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding())); + newP.setVarargs(info.isNewVarargs()); + return newP; + } + } + + class LambdaExpressionUpdate extends AbstractDeclarationUpdate { + private LambdaExpression fLambdaDecl; + + protected LambdaExpressionUpdate(LambdaExpression decl, CompilationUnitRewrite cuRewrite, RefactoringStatus result) { + super(cuRewrite, cuRewrite.createGroupDescription(RefactoringCoreMessages.ChangeSignatureRefactoring_change_signature), result); + fLambdaDecl= decl; + } + + @Override + public void updateNode() throws CoreException { + changeParamguments(); + + reshuffleElements(); + + if (fBodyUpdater == null || fBodyUpdater.needsParameterUsedCheck()) + checkIfDeletedParametersUsed(); + } + + /** @return {@inheritDoc} (element type: VariableDeclaration) */ + @Override + protected ListRewrite getParamgumentsRewrite() { + return getASTRewrite().getListRewrite(fLambdaDecl, LambdaExpression.PARAMETERS_PROPERTY); + } + + @Override + protected VariableDeclaration createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) { + List parameters= fLambdaDecl.parameters(); + if (!parameters.isEmpty() && parameters.get(0) instanceof SingleVariableDeclaration) { + return createNewSingleVariableDeclaration(info); + } + VariableDeclarationFragment newP= getASTRewrite().getAST().newVariableDeclarationFragment(); + newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName())); + return newP; + } + + @Override + protected int getStartPosition() { + return fLambdaDecl.getStartPosition(); + } + + @Override + protected ASTNode getNode() { + return fLambdaDecl; + } + + @Override + protected VariableDeclaration getParameter(int index) { + return (VariableDeclaration) fLambdaDecl.parameters().get(index); + } + + @Override + protected SimpleName getMethodNameNode() { + return null; + } + } + + class DeclarationUpdate extends AbstractDeclarationUpdate { private MethodDeclaration fMethDecl; protected DeclarationUpdate(MethodDeclaration decl, CompilationUnitRewrite cuRewrite, RefactoringStatus result) { @@ -2053,49 +2263,20 @@ protected ListRewrite getParamgumentsRewrite() { return getASTRewrite().getListRewrite(fMethDecl, MethodDeclaration.PARAMETERS_PROPERTY); } - @Override - protected void changeParamgumentName(ParameterInfo info) { - SingleVariableDeclaration param= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex()); - if (! info.getOldName().equals(param.getName().getIdentifier())) - return; //don't change if original parameter name != name in rippleMethod - - String msg= RefactoringCoreMessages.ChangeSignatureRefactoring_update_parameter_references; - TextEditGroup description= fCuRewrite.createGroupDescription(msg); - TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(param, false); - analyzer.perform(); - SimpleName[] paramOccurrences= analyzer.getReferenceAndDeclarationNodes(); // @param tags are updated in changeJavaDocTags() - for (int j= 0; j < paramOccurrences.length; j++) { - SimpleName occurence= paramOccurrences[j]; - getASTRewrite().set(occurence, SimpleName.IDENTIFIER_PROPERTY, info.getNewName(), description); - } - } - - @Override - protected void changeParamgumentType(ParameterInfo info) { - SingleVariableDeclaration oldParam= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex()); - getASTRewrite().set(oldParam, SingleVariableDeclaration.VARARGS_PROPERTY, Boolean.valueOf(info.isNewVarargs()), fDescription); - replaceTypeNode(oldParam.getType(), ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding()); - removeExtraDimensions(oldParam); - } - - private void removeExtraDimensions(SingleVariableDeclaration oldParam) { - if (oldParam.getExtraDimensions() != 0) { - getASTRewrite().set(oldParam, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), fDescription); - } - } - private void changeReturnType() { - if (isReturnTypeSameAsInitial()) - return; + if (isReturnTypeSameAsInitial()) + return; replaceTypeNode(fMethDecl.getReturnType2(), fReturnTypeInfo.getNewTypeName(), fReturnTypeInfo.getNewTypeBinding()); - removeExtraDimensions(fMethDecl); - //Remove expression from return statement when changed to void? No, would lose information! - //Could add return statement with default value and add todo comment, but compile error is better. + removeExtraDimensions(fMethDecl); + //Remove expression from return statement when changed to void? No, would lose information! + //Could add return statement with default value and add todo comment, but compile error is better. } private void removeExtraDimensions(MethodDeclaration methDecl) { - if (methDecl.getExtraDimensions() != 0) - getASTRewrite().set(methDecl, MethodDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), fDescription); + ListRewrite listRewrite= getASTRewrite().getListRewrite(methDecl, MethodDeclaration.EXTRA_DIMENSIONS2_PROPERTY); + for (Dimension dimension : (List) methDecl.extraDimensions()) { + listRewrite.remove(dimension, fDescription); + } } private boolean needsVisibilityUpdate() throws JavaModelException { @@ -2121,17 +2302,17 @@ private void changeExceptions() { if (info.isOld()) continue; if (info.isDeleted()) - removeExceptionFromNodeList(info, fMethDecl.thrownExceptions()); + removeExceptionFromNodeList(info, fMethDecl.thrownExceptionTypes()); else - addExceptionToNodeList(info, getASTRewrite().getListRewrite(fMethDecl, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY)); + addExceptionToNodeList(info, getASTRewrite().getListRewrite(fMethDecl, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY)); } } - private void removeExceptionFromNodeList(ExceptionInfo toRemove, List list) { + private void removeExceptionFromNodeList(ExceptionInfo toRemove, List list) { ITypeBinding typeToRemove= toRemove.getTypeBinding(); - for (Iterator iter= list.iterator(); iter.hasNext(); ) { - Name currentName= iter.next(); - ITypeBinding currentType= currentName.resolveTypeBinding(); + for (Iterator iter= list.iterator(); iter.hasNext();) { + Type currentExcType= iter.next(); + ITypeBinding currentType= currentExcType.resolveBinding(); /* Maybe remove all subclasses of typeToRemove too. * Problem: * - B extends A; @@ -2143,8 +2324,8 @@ private void removeExceptionFromNodeList(ExceptionInfo toRemove, List list if (currentType == null) continue; // newly added or unresolvable type if (Bindings.equals(currentType, typeToRemove) || toRemove.getElement().getElementName().equals(currentType.getName())) { - getASTRewrite().remove(currentName, fDescription); - registerImportRemoveNode(currentName); + getASTRewrite().remove(currentExcType, fDescription); + registerImportRemoveNode(currentExcType); } } } @@ -2152,9 +2333,9 @@ private void removeExceptionFromNodeList(ExceptionInfo toRemove, List list private void addExceptionToNodeList(ExceptionInfo exceptionInfo, ListRewrite exceptionListRewrite) { String fullyQualified= exceptionInfo.getFullyQualifiedName(); for (Iterator iter= exceptionListRewrite.getOriginalList().iterator(); iter.hasNext(); ) { - Name exName= (Name) iter.next(); + Type exType= (Type) iter.next(); //XXX: existing superclasses of the added exception are redundant and could be removed - ITypeBinding typeBinding= exName.resolveTypeBinding(); + ITypeBinding typeBinding= exType.resolveBinding(); if (typeBinding == null) continue; // newly added or unresolvable type if (typeBinding.getQualifiedName().equals(fullyQualified)) @@ -2162,7 +2343,7 @@ private void addExceptionToNodeList(ExceptionInfo exceptionInfo, ListRewrite exc } String importedType= getImportRewrite().addImport(exceptionInfo.getFullyQualifiedName()); getImportRemover().registerAddedImport(importedType); - ASTNode exNode= getASTRewrite().createStringPlaceholder(importedType, ASTNode.SIMPLE_NAME); + ASTNode exNode= getASTRewrite().createStringPlaceholder(importedType, ASTNode.SIMPLE_TYPE); exceptionListRewrite.insertLast(exNode, fDescription); } @@ -2400,8 +2581,8 @@ private void insertTag(TagElement tag, TagElement previousTag, ListRewrite tagsR /** * @param tags existing tags * @param tagName name of tag to add - * @return the TagElement just before a new TagElement with name tagName, - * or null. + * @return the TagElement just before a new TagElement with name + * tagName, or null. */ private TagElement findTagElementToInsertAfter(List tags, String tagName) { List tagOrder= Arrays.asList(new String[] { @@ -2425,59 +2606,25 @@ private TagElement findTagElementToInsertAfter(List tags, String tag for (int i= 0; i < tags.size(); i++) { int tagOrdinal= tagOrder.indexOf(tags.get(i).getTagName()); if (tagOrdinal >= goalOrdinal) - return (i == 0) ? null : (TagElement) tags.get(i-1); - } - return (tags.size() == 0) ? null : (TagElement) tags.get(tags.size()-1); - } - - //TODO: already reported as compilation error -> don't report there? - private void checkIfDeletedParametersUsed() { - for (Iterator iter= getDeletedInfos().iterator(); iter.hasNext();) { - ParameterInfo info= iter.next(); - SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) fMethDecl.parameters().get(info.getOldIndex()); - TempOccurrenceAnalyzer analyzer= new TempOccurrenceAnalyzer(paramDecl, false); - analyzer.perform(); - SimpleName[] paramRefs= analyzer.getReferenceNodes(); - - if (paramRefs.length > 0){ - RefactoringStatusContext context= JavaStatusContext.create(fCuRewrite.getCu(), paramRefs[0]); - String typeName= getFullTypeName(fMethDecl); - Object[] keys= new String[]{ BasicElementLabels.getJavaElementName(paramDecl.getName().getIdentifier()), - BasicElementLabels.getJavaElementName(fMethDecl.getName().getIdentifier()), - BasicElementLabels.getJavaElementName(typeName)}; - String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_parameter_used, keys); - fResult.addError(msg, context); - } + return (i == 0) ? null : (TagElement) tags.get(i - 1); } + return (tags.size() == 0) ? null : (TagElement) tags.get(tags.size() - 1); } - private String getFullTypeName(MethodDeclaration decl) { - ASTNode node= decl; - while (true) { - node= node.getParent(); - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration) node).getName().getIdentifier(); - } else if (node instanceof ClassInstanceCreation) { - ClassInstanceCreation cic= (ClassInstanceCreation) node; - return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(cic.getType()))); - } else if (node instanceof EnumConstantDeclaration) { - EnumDeclaration ed= (EnumDeclaration) node.getParent(); - return Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_anonymous_subclass, BasicElementLabels.getJavaElementName(ASTNodes.asString(ed.getName()))); - } - } - } @Override protected SingleVariableDeclaration createNewParamgument(ParameterInfo info, List parameterInfos, List nodes) { return createNewSingleVariableDeclaration(info); } - private SingleVariableDeclaration createNewSingleVariableDeclaration(ParameterInfo info) { - SingleVariableDeclaration newP= getASTRewrite().getAST().newSingleVariableDeclaration(); - newP.setName(getASTRewrite().getAST().newSimpleName(info.getNewName())); - newP.setType(createNewTypeNode(ParameterInfo.stripEllipsis(info.getNewTypeName()), info.getNewTypeBinding())); - newP.setVarargs(info.isNewVarargs()); - return newP; + @Override + protected ASTNode getNode() { + return fMethDecl; + } + + @Override + protected VariableDeclaration getParameter(int index) { + return (VariableDeclaration) fMethDecl.parameters().get(index); } @Override @@ -2571,8 +2718,8 @@ protected void changeParamgumentType(ParameterInfo info) { Type newTypeNode= createNewDocRefType(info); if (info.isNewVarargs()) { if (info.isOldVarargs() && ! oldParam.isVarargs()) { - // leave as array reference of old reference was not vararg - newTypeNode= getASTRewrite().getAST().newArrayType(newTypeNode); + // leave as array reference if old reference was not vararg + newTypeNode= ASTNodeFactory.newArrayType(newTypeNode); } else { getASTRewrite().set(oldParam, MethodRefParameter.VARARGS_PROPERTY, Boolean.TRUE, fDescription); } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java index 538a3ed3fd..d9967ea7bd 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java @@ -930,7 +930,7 @@ private String simpleNameSelected(SimpleName simpleName) { } else if (parent.getNodeType() == ASTNode.METHOD_DECLARATION && grandParent.getNodeType() == ASTNode.TYPE_DECLARATION) { MethodDeclaration methodDeclaration= (MethodDeclaration)parent; - if (methodDeclaration.getName().equals(simpleName) || methodDeclaration.thrownExceptions().contains(simpleName)){ + if (methodDeclaration.getName().equals(simpleName)) { return RefactoringCoreMessages.ChangeTypeRefactoring_notSupportedOnNodeType; } fMethodBinding= ((MethodDeclaration)parent).resolveBinding(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java index 93a673608d..30e5b2fb18 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java @@ -51,6 +51,7 @@ import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.ArrayCreation; import org.eclipse.jdt.core.dom.ArrayInitializer; +import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; @@ -820,11 +821,11 @@ private FieldDeclaration createParameterObjectField(ParameterObjectFactory pof, ASTNode createMoveTarget= fBaseCURewrite.getASTRewrite().createMoveTarget(expression); if (expression instanceof ArrayInitializer) { ArrayInitializer ai= (ArrayInitializer) expression; - ITypeBinding componentType= ai.resolveTypeBinding().getComponentType(); - ArrayCreation arrayCreation= ast.newArrayCreation(); - Type addImport= fBaseCURewrite.getImportRewrite().addImport(componentType, ast); + ITypeBinding type= ai.resolveTypeBinding(); + Type addImport= fBaseCURewrite.getImportRewrite().addImport(type, ast); fBaseCURewrite.getImportRemover().registerAddedImports(addImport); - arrayCreation.setType(ast.newArrayType(addImport)); + ArrayCreation arrayCreation= ast.newArrayCreation(); + arrayCreation.setType((ArrayType) addImport); arrayCreation.setInitializer((ArrayInitializer) createMoveTarget); listRewrite.insertLast(arrayCreation, null); } else { diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java index 4aee33c87d..6784bfd34e 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -833,25 +833,23 @@ protected final IField[] getExtractedFields(final ICompilationUnit unit) { } /** - * Returns the extracted methods from the compilation unit. + * Returns the extracted methods from the compilation unit except the default methods. * - * @param unit - * the compilation unit - * @return the extracted methods + * @param unit the compilation unit + * @return the extracted methods except the default method + * @throws JavaModelException if the element does not exist */ - protected final IMethod[] getExtractedMethods(final ICompilationUnit unit) { + protected final IMethod[] getExtractedMethods(final ICompilationUnit unit) throws JavaModelException { Assert.isNotNull(unit); final List list= new ArrayList(); for (int index= 0; index < fMembers.length; index++) { if (fMembers[index] instanceof IMethod) { final IJavaElement element= JavaModelUtil.findInCompilationUnit(unit, fMembers[index]); - if (element instanceof IMethod) + if (element instanceof IMethod && !JdtFlags.isDefaultMethod((IMethod) element)) list.add(element); } } - final IMethod[] methods= new IMethod[list.size()]; - list.toArray(methods); - return methods; + return list.toArray(new IMethod[list.size()]); } /* diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java index d20975e07e..513120f35c 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java @@ -55,6 +55,7 @@ import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Dimension; import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldDeclaration; @@ -64,12 +65,12 @@ import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeParameter; +import org.eclipse.jdt.core.dom.VariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ITrackedNodePosition; @@ -210,6 +211,18 @@ protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite return status; } + protected static void copyExtraDimensions(final VariableDeclaration oldVarDeclaration, final VariableDeclaration newVarDeclaration) { + final AST ast= newVarDeclaration.getAST(); + for (int index= 0, n= oldVarDeclaration.extraDimensions().size(); index < n; index++) + newVarDeclaration.extraDimensions().add(ASTNode.copySubtree(ast, (Dimension) oldVarDeclaration.extraDimensions().get(index))); + } + + protected static void copyExtraDimensions(final MethodDeclaration oldMethod, final MethodDeclaration newMethod) { + final AST ast= newMethod.getAST(); + for (int index= 0, n= oldMethod.extraDimensions().size(); index < n; index++) + newMethod.extraDimensions().add(ASTNode.copySubtree(ast, (Dimension) oldMethod.extraDimensions().get(index))); + } + protected static void copyAnnotations(final FieldDeclaration oldField, final FieldDeclaration newField) { final AST ast= newField.getAST(); for (int index= 0, n= oldField.modifiers().size(); index < n; index++) { @@ -242,8 +255,8 @@ protected static void copyJavadocNode(final ASTRewrite rewrite, final BodyDeclar protected static void copyThrownExceptions(final MethodDeclaration oldMethod, final MethodDeclaration newMethod) { final AST ast= newMethod.getAST(); - for (int index= 0, n= oldMethod.thrownExceptions().size(); index < n; index++) - newMethod.thrownExceptions().add(ASTNode.copySubtree(ast, (Name) oldMethod.thrownExceptions().get(index))); + for (int index= 0, n= oldMethod.thrownExceptionTypes().size(); index < n; index++) + newMethod.thrownExceptionTypes().add(ASTNode.copySubtree(ast, (Type) oldMethod.thrownExceptionTypes().get(index))); } protected static void copyTypeParameters(final MethodDeclaration oldMethod, final MethodDeclaration newMethod) { @@ -267,7 +280,7 @@ else if (member instanceof IInitializer) protected static FieldDeclaration createNewFieldDeclarationNode(final ASTRewrite rewrite, final CompilationUnit unit, final IField field, final VariableDeclarationFragment oldFieldFragment, final TypeVariableMaplet[] mapping, final IProgressMonitor monitor, final RefactoringStatus status, final int modifiers) throws JavaModelException { final VariableDeclarationFragment newFragment= rewrite.getAST().newVariableDeclarationFragment(); - newFragment.setExtraDimensions(oldFieldFragment.getExtraDimensions()); + copyExtraDimensions(oldFieldFragment, newFragment); if (oldFieldFragment.getInitializer() != null) { Expression newInitializer= null; if (mapping.length > 0) @@ -714,4 +727,4 @@ protected boolean needsVisibilityAdjustment(final IMember member, final boolean return true; return hasNonMovedReferences(member, monitor, status); } -} \ No newline at end of file +} diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ImportRemover.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ImportRemover.java index 9c7534d4e0..a9cad618fc 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ImportRemover.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ImportRemover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,6 +28,7 @@ import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.SimpleName; @@ -37,6 +38,19 @@ import org.eclipse.jdt.internal.corext.codemanipulation.ImportReferencesCollector; import org.eclipse.jdt.internal.corext.dom.Bindings; +/** + * Removes imports that are no longer required. + *

    + * {@link #registerRemovedNode(ASTNode)} registers nodes that got removed from the AST. + * Do not register nodes that are moved to a different place in the same AST. + *

    + * If a node is removed but some parts of it are moved to a different place in the same AST, + * then use {@link #registerRetainedNode(ASTNode)} to keep imports for the retained nodes. + *

    + * Additional imports that will be added to the AST need to be registered with one of the + * {@code register*Import*(..)} methods. Such imports have typically been created with + * {@link ImportRewrite#addImport(ITypeBinding)} etc. + */ public class ImportRemover { private static class StaticImportData { @@ -54,13 +68,17 @@ private StaticImportData(String qualifier, String member, boolean field) { } } + private final String PROPERTY_KEY= String.valueOf(System.currentTimeMillis()); + private final String REMOVED= "removed"; //$NON-NLS-1$ + private final String RETAINED= "retained"; //$NON-NLS-1$ + private Set fAddedImports= new HashSet(); private Set fAddedStaticImports= new HashSet(); private final IJavaProject fProject; - private List fRemovedNodes= new ArrayList(); + private boolean fHasRemovedNodes; private List fInlinedStaticImports= new ArrayList(); @@ -72,13 +90,55 @@ public ImportRemover(IJavaProject project, CompilationUnit root) { } private void divideTypeRefs(List importNames, List staticNames, List removedRefs, List unremovedRefs) { - int[] removedStartsEnds= new int[2 * fRemovedNodes.size()]; - for (int index= 0; index < fRemovedNodes.size(); index++) { - ASTNode node= fRemovedNodes.get(index); - int start= node.getStartPosition(); - removedStartsEnds[2 * index]= start; - removedStartsEnds[2 * index + 1]= start + node.getLength(); - } + final List removedStartsEnds= new ArrayList(); + fRoot.accept(new ASTVisitor(true) { + int fRemovingStart= -1; + @Override + public void preVisit(ASTNode node) { + Object property= node.getProperty(PROPERTY_KEY); + if (property == REMOVED) { + if (fRemovingStart == -1) { + fRemovingStart= node.getStartPosition(); + } else { + /* + * Bug in client code: REMOVED node should not be nested inside another REMOVED node without + * an intermediate RETAINED node. + * Drop REMOVED property to prevent problems later (premature end of REMOVED section). + */ + node.setProperty(PROPERTY_KEY, null); + } + } else if (property == RETAINED) { + if (fRemovingStart != -1) { + removedStartsEnds.add(new int[] { fRemovingStart, node.getStartPosition() }); + fRemovingStart= -1; + } else { + /* + * Bug in client code: RETAINED node should not be nested inside another RETAINED node without + * an intermediate REMOVED node and must have an enclosing REMOVED node. + * Drop RETAINED property to prevent problems later (premature restart of REMOVED section). + */ + node.setProperty(PROPERTY_KEY, null); + } + } + super.preVisit(node); + } + @Override + public void postVisit(ASTNode node) { + Object property= node.getProperty(PROPERTY_KEY); + if (property == RETAINED) { + int end= node.getStartPosition() + node.getLength(); + fRemovingStart= end; + } else if (property == REMOVED) { + if (fRemovingStart != -1) { + int end= node.getStartPosition() + node.getLength(); + removedStartsEnds.add(new int[] { fRemovingStart, end }); + fRemovingStart= -1; + } + } + super.postVisit(node); + } + }); + for (Iterator iterator= importNames.iterator(); iterator.hasNext();) { SimpleName name= iterator.next(); if (isInRemoved(name, removedStartsEnds)) @@ -102,6 +162,17 @@ private void divideTypeRefs(List importNames, List stati } } + private boolean isInRemoved(SimpleName ref, List removedStartsEnds) { + int start= ref.getStartPosition(); + int end= start + ref.getLength(); + for (int[] removedStartsEnd : removedStartsEnds) { + if (start >= removedStartsEnd[0] && end <= removedStartsEnd[1]) { + return true; + } + } + return false; + } + public IBinding[] getImportsToRemove() { ArrayList importNames= new ArrayList(); ArrayList staticNames= new ArrayList(); @@ -114,7 +185,7 @@ public IBinding[] getImportsToRemove() { if (removedRefs.size() == 0) return new IBinding[0]; - HashMappotentialRemoves= getPotentialRemoves(removedRefs); + HashMap potentialRemoves= getPotentialRemoves(removedRefs); for (Iterator iterator= unremovedRefs.iterator(); iterator.hasNext();) { SimpleName name= iterator.next(); potentialRemoves.remove(name.getIdentifier()); @@ -160,17 +231,7 @@ private boolean hasAddedStaticImport(String qualifier, String member, boolean fi } public boolean hasRemovedNodes() { - return fRemovedNodes.size() != 0 || fInlinedStaticImports.size() != 0; - } - - private boolean isInRemoved(SimpleName ref, int[] removedStartsEnds) { - int start= ref.getStartPosition(); - int end= start + ref.getLength(); - for (int index= 0; index < removedStartsEnds.length; index+= 2) { - if (start >= removedStartsEnds[index] && end <= removedStartsEnds[index + 1]) - return true; - } - return false; + return fHasRemovedNodes || fInlinedStaticImports.size() != 0; } public void registerAddedImport(String typeName) { @@ -188,6 +249,12 @@ private void addName(SimpleName name) { fAddedImports.add(name.getIdentifier()); } + @Override + public boolean visit(NameQualifiedType node) { + addName(node.getName()); + return false; + } + @Override public boolean visit(QualifiedName node) { addName(node.getName()); @@ -227,9 +294,13 @@ public void registerAddedStaticImport(IBinding binding) { } public void registerRemovedNode(ASTNode removed) { - fRemovedNodes.add(removed); + fHasRemovedNodes= true; + removed.setProperty(PROPERTY_KEY, REMOVED); } + public void registerRetainedNode(ASTNode retained) { + retained.setProperty(PROPERTY_KEY, RETAINED); + } public void applyRemoves(ImportRewrite importRewrite) { IBinding[] bindings= getImportsToRemove(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java index 30089e5cec..78deea2383 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -454,8 +454,8 @@ private RefactoringStatus checkDestinationType() throws JavaModelException { RefactoringStatus result= new RefactoringStatus(); - if (fDestinationType.isInterface() && ! getDeclaringType().isInterface()) - result.merge(checkFieldsForInterface()); + if (fDestinationType.isInterface()) + result.merge(checkMoveToInterface()); if (result.hasFatalError()) return result; @@ -486,23 +486,31 @@ private RefactoringStatus checkDestinationInsideTypeToMove() throws JavaModelExc return result; } - private RefactoringStatus checkFieldsForInterface() throws JavaModelException { + private RefactoringStatus checkMoveToInterface() throws JavaModelException { //could be more clever and make field final if it is only written once... + boolean is18OrHigher= JavaModelUtil.is18OrHigher(fDestinationType.getJavaProject()); RefactoringStatus result= new RefactoringStatus(); + boolean declaringIsInterface= getDeclaringType().isInterface(); + if (declaringIsInterface && is18OrHigher) + return result; + String moveMembersMsg= is18OrHigher ? RefactoringCoreMessages.MoveMembersRefactoring_only_public_static_18 : RefactoringCoreMessages.MoveMembersRefactoring_only_public_static; for (int i= 0; i < fMembersToMove.length; i++) { - if (! canMoveToInterface(fMembersToMove[i])) { - String message= RefactoringCoreMessages.MoveMembersRefactoring_only_public_static; - result.addError(message, JavaStatusContext.create(fMembersToMove[i])); + if (declaringIsInterface && !(fMembersToMove[i] instanceof IMethod) && !is18OrHigher) { + // moving from interface to interface is OK, unless method is moved to pre-18 + } else if (!canMoveToInterface(fMembersToMove[i], is18OrHigher)) { + result.addError(moveMembersMsg, JavaStatusContext.create(fMembersToMove[i])); + } else if (!Flags.isPublic(fMembersToMove[i].getFlags()) && !declaringIsInterface) { + result.addWarning(RefactoringCoreMessages.MoveMembersRefactoring_member_will_be_public, JavaStatusContext.create(fMembersToMove[i])); } } return result; } - private boolean canMoveToInterface(IMember member) throws JavaModelException { + private boolean canMoveToInterface(IMember member, boolean is18OrHigher) throws JavaModelException { int flags= member.getFlags(); switch (member.getElementType()) { case IJavaElement.FIELD: - if (!(Flags.isPublic(flags) && Flags.isStatic(flags) && Flags.isFinal(flags))) + if (!(Flags.isStatic(flags) && Flags.isFinal(flags))) return false; if (Flags.isEnum(flags)) return false; @@ -514,7 +522,10 @@ private boolean canMoveToInterface(IMember member) throws JavaModelException { IType type= (IType) member; if (type.isInterface() && !Checks.isTopLevel(type)) return true; - return Flags.isPublic(flags) && Flags.isStatic(flags); + return Flags.isStatic(flags); + } + case IJavaElement.METHOD: { + return is18OrHigher && Flags.isStatic(flags); } default: return false; @@ -944,6 +955,12 @@ private String[] getUpdatedMemberSource(RefactoringStatus status, BodyDeclaratio if ((typeDecl.getModifiers() & psModifiers) != psModifiers) { ModifierRewrite.create(fSource.getASTRewrite(), typeDecl).setModifiers(typeDecl.getModifiers() | psModifiers, null); } + } else if (declaration instanceof MethodDeclaration) { + MethodDeclaration methodDecl= (MethodDeclaration) declaration; + int psModifiers= Modifier.PUBLIC | Modifier.STATIC; + if ((methodDecl.getModifiers() & psModifiers) != psModifiers) { + ModifierRewrite.create(fSource.getASTRewrite(), methodDecl).setModifiers(methodDecl.getModifiers() | psModifiers, null); + } } } ITrackedNodePosition trackedPosition= fSource.getASTRewrite().track(declaration); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java index ad6ee2e1c6..794475f104 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java @@ -503,7 +503,7 @@ private void addMethodStubForAbstractMethod(final IMethod sourceMethod, final Co final MethodDeclaration newMethod= ast.newMethodDeclaration(); newMethod.setBody(createMethodStub(methodToCreateStubFor, ast)); newMethod.setConstructor(false); - newMethod.setExtraDimensions(methodToCreateStubFor.getExtraDimensions()); + copyExtraDimensions(methodToCreateStubFor, newMethod); newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, getModifiersWithUpdatedVisibility(sourceMethod, JdtFlags.clearFlag(Modifier.NATIVE | Modifier.ABSTRACT, methodToCreateStubFor.getModifiers()), adjustments, new SubProgressMonitor(monitor, 1), false, status))); newMethod.setName(((SimpleName) ASTNode.copySubtree(ast, methodToCreateStubFor.getName()))); final TypeVariableMaplet[] mapping= TypeVariableUtil.composeMappings(TypeVariableUtil.subTypeToSuperType(getDeclaringType(), getDestinationType()), TypeVariableUtil.superTypeToInheritedType(getDestinationType(), ((IType) typeToCreateStubIn.resolveBinding().getJavaElement()))); @@ -1023,7 +1023,7 @@ private void createAbstractMethod(final IMethod sourceMethod, final CompilationU final MethodDeclaration newMethod= targetRewrite.getAST().newMethodDeclaration(); newMethod.setBody(null); newMethod.setConstructor(false); - newMethod.setExtraDimensions(oldMethod.getExtraDimensions()); + copyExtraDimensions(oldMethod, newMethod); newMethod.setJavadoc(null); int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, Modifier.ABSTRACT | JdtFlags.clearFlag(Modifier.NATIVE | Modifier.FINAL, sourceMethod.getFlags()), adjustments, monitor, false, status); if (oldMethod.isVarargs()) @@ -1319,7 +1319,7 @@ private MethodDeclaration createNewMethodDeclarationNode(final CompilationUnitRe if (!getDestinationType().isInterface()) copyBodyOfPulledUpMethod(sourceRewrite, targetRewrite, sourceMethod, oldMethod, newMethod, mapping, monitor); newMethod.setConstructor(oldMethod.isConstructor()); - newMethod.setExtraDimensions(oldMethod.getExtraDimensions()); + copyExtraDimensions(oldMethod, newMethod); copyJavadocNode(rewrite, oldMethod, newMethod); int modifiers= getModifiersWithUpdatedVisibility(sourceMethod, sourceMethod.getFlags(), adjustments, monitor, true, status); if (fDeletedMethods.length == 0 || getDestinationType().isInterface()) { diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java index 5bdbb5e6ce..31ac997502 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java @@ -791,7 +791,7 @@ private FieldDeclaration createNewFieldDeclarationNode(MemberActionInfo info, Co IField field= (IField) info.getMember(); AST ast= rewrite.getAST(); VariableDeclarationFragment newFragment= ast.newVariableDeclarationFragment(); - newFragment.setExtraDimensions(oldFieldFragment.getExtraDimensions()); + copyExtraDimensions(oldFieldFragment, newFragment); Expression initializer= oldFieldFragment.getInitializer(); if (initializer != null) { Expression newInitializer= null; @@ -827,7 +827,7 @@ private MethodDeclaration createNewMethodDeclarationNode(MemberActionInfo info, MethodDeclaration newMethod= ast.newMethodDeclaration(); copyBodyOfPushedDownMethod(rewrite, method, oldMethod, newMethod, mapping); newMethod.setConstructor(oldMethod.isConstructor()); - newMethod.setExtraDimensions(oldMethod.getExtraDimensions()); + copyExtraDimensions(oldMethod, newMethod); if (info.copyJavadocToCopiesInSubclasses()) copyJavadocNode(rewrite, oldMethod, newMethod); final IJavaProject project= rewriter.getCu().getJavaProject(); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java index 43059e54dc..79761a7ebe 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReferenceFinderUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -27,7 +27,6 @@ import org.eclipse.jdt.core.WorkingCopyOwner; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.search.SearchEngine; @@ -162,8 +161,8 @@ public static Set getTypesUsedInDeclaration(MethodDeclaration meth result.add(binding); } - for (Iterator iter= methodDeclaration.thrownExceptions().iterator(); iter.hasNext();) { - binding = iter.next().resolveTypeBinding(); + for (Iterator iter= methodDeclaration.thrownExceptionTypes().iterator(); iter.hasNext();) { + binding= iter.next().resolveBinding(); if (binding != null) result.add(binding); } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java index 823027acf0..443c2d3cee 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeConstraintsCreator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -503,13 +503,13 @@ public final void endVisit(final MethodDeclaration node) { } } } - final List exceptions= node.thrownExceptions(); + final List exceptions= node.thrownExceptionTypes(); if (!exceptions.isEmpty()) { final ITypeBinding throwable= node.getAST().resolveWellKnownType("java.lang.Throwable"); //$NON-NLS-1$ if (throwable != null) { ancestor= fModel.createImmutableTypeVariable(throwable); if (ancestor != null) { - Name exception= null; + Type exception= null; for (int index= 0; index < exceptions.size(); index++) { exception= exceptions.get(index); descendant= (ConstraintVariable2) exception.getProperty(PROPERTY_CONSTRAINT_VARIABLE); diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java index 47942a1b65..e9e626b5ce 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ExceptionAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -25,10 +25,10 @@ import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.ThrowStatement; +import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.internal.corext.dom.Bindings; @@ -69,9 +69,9 @@ public static ITypeBinding[] perform(BodyDeclaration enclosingNode, Selection se enclosingNode.accept(analyzer); List exceptions= analyzer.getCurrentExceptions(); if (enclosingNode.getNodeType() == ASTNode.METHOD_DECLARATION) { - List thrownExceptions= ((MethodDeclaration)enclosingNode).thrownExceptions(); - for (Iterator thrown= thrownExceptions.iterator(); thrown.hasNext();) { - ITypeBinding thrownException= thrown.next().resolveTypeBinding(); + List thrownExceptions= ((MethodDeclaration) enclosingNode).thrownExceptionTypes(); + for (Iterator thrown= thrownExceptions.iterator(); thrown.hasNext();) { + ITypeBinding thrownException= thrown.next().resolveBinding(); if (thrownException != null) { for (Iterator excep= exceptions.iterator(); excep.hasNext();) { ITypeBinding exception= excep.next(); @@ -91,7 +91,7 @@ public boolean visit(ThrowStatement node) { if (!isSelected(node) || exception == null || Bindings.isRuntimeException(exception)) // Safety net for null bindings when compiling fails. return true; - addException(exception); + addException(exception, node.getAST()); return true; } @@ -99,35 +99,35 @@ public boolean visit(ThrowStatement node) { public boolean visit(MethodInvocation node) { if (!isSelected(node)) return false; - return handleExceptions(node.resolveMethodBinding()); + return handleExceptions(node.resolveMethodBinding(), node); } @Override public boolean visit(SuperMethodInvocation node) { if (!isSelected(node)) return false; - return handleExceptions(node.resolveMethodBinding()); + return handleExceptions(node.resolveMethodBinding(), node); } @Override public boolean visit(ClassInstanceCreation node) { if (!isSelected(node)) return false; - return handleExceptions(node.resolveConstructorBinding()); + return handleExceptions(node.resolveConstructorBinding(), node); } @Override public boolean visit(ConstructorInvocation node) { if (!isSelected(node)) return false; - return handleExceptions(node.resolveConstructorBinding()); + return handleExceptions(node.resolveConstructorBinding(), node); } @Override public boolean visit(SuperConstructorInvocation node) { if (!isSelected(node)) return false; - return handleExceptions(node.resolveConstructorBinding()); + return handleExceptions(node.resolveConstructorBinding(), node); } @Override @@ -137,12 +137,12 @@ public boolean visit(VariableDeclarationExpression node) { return super.visit(node); } - private boolean handleExceptions(IMethodBinding binding) { + private boolean handleExceptions(IMethodBinding binding, ASTNode node) { if (binding == null) return true; ITypeBinding[] exceptions= binding.getExceptionTypes(); for (int i= 0; i < exceptions.length; i++) { - addException(exceptions[i]); + addException(exceptions[i], node.getAST()); } return true; } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java index e0fc5dd57a..17049d81ad 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -59,7 +59,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; -import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.CodeScopeBuilder; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModel; @@ -240,7 +240,6 @@ private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String if (!fIsMultiCatch) { for (int i= 0; i < exceptions.length; i++) { ITypeBinding exception= exceptions[i]; - String type= fImportRewrite.addImport(exception, context); CatchClause catchClause= getAST().newCatchClause(); tryStatement.catchClauses().add(catchClause); SingleVariableDeclaration decl= getAST().newSingleVariableDeclaration(); @@ -248,9 +247,10 @@ private void createTryCatchStatement(org.eclipse.jdt.core.IBuffer buffer, String String name= fScope.createName(varName, false); decl.setName(getAST().newSimpleName(name)); - decl.setType(ASTNodeFactory.newType(getAST(), type)); + Type type= fImportRewrite.addImport(exception, getAST(), context); + decl.setType(type); catchClause.setException(decl); - Statement st= getCatchBody(type, name, lineDelimiter); + Statement st= getCatchBody(ASTNodes.getQualifiedTypeName(type), name, lineDelimiter); if (st != null) { catchClause.getBody().statements().add(st); } diff --git a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java index 3392963a39..82cb09cad1 100644 --- a/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java +++ b/org.eclipse.jdt.ui/core refactoring/org/eclipse/jdt/internal/corext/refactoring/util/AbstractExceptionAnalyzer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -92,11 +92,9 @@ public boolean visit(TryStatement node) { // visit try block node.getBody().accept(this); - if (node.getAST().apiLevel() >= AST.JLS4) { - List resources= node.resources(); - for (Iterator iterator= resources.iterator(); iterator.hasNext();) { - iterator.next().accept(this); - } + List resources= node.resources(); + for (Iterator iterator= resources.iterator(); iterator.hasNext();) { + iterator.next().accept(this); } // Remove those exceptions that get catch by following catch blocks @@ -106,7 +104,7 @@ public boolean visit(TryStatement node) { List current= fTryStack.pop(); fCurrentExceptions= fTryStack.peek(); for (Iterator iter= current.iterator(); iter.hasNext();) { - addException(iter.next()); + addException(iter.next(), node.getAST()); } // visit catch and finally @@ -122,13 +120,13 @@ public boolean visit(TryStatement node) { @Override public boolean visit(VariableDeclarationExpression node) { - if (node.getAST().apiLevel() >= AST.JLS4 && node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) { + if (node.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) { Type type= node.getType(); ITypeBinding resourceTypeBinding= type.resolveBinding(); if (resourceTypeBinding != null) { IMethodBinding methodBinding= Bindings.findMethodInHierarchy(resourceTypeBinding, "close", new ITypeBinding[0]); //$NON-NLS-1$ if (methodBinding != null) { - addExceptions(methodBinding.getExceptionTypes()); + addExceptions(methodBinding.getExceptionTypes(), node.getAST()); } } } @@ -136,15 +134,16 @@ public boolean visit(VariableDeclarationExpression node) { } - protected void addExceptions(ITypeBinding[] exceptions) { + protected void addExceptions(ITypeBinding[] exceptions, AST ast) { if(exceptions == null) return; for (int i= 0; i < exceptions.length;i++) { - addException(exceptions[i]); + addException(exceptions[i], ast); } } - protected void addException(ITypeBinding exception) { + protected void addException(ITypeBinding exception, AST ast) { + exception= Bindings.normalizeForDeclarationUse(exception, ast); if (!fCurrentExceptions.contains(exception)) fCurrentExceptions.add(exception); } diff --git a/org.eclipse.jdt.ui/icons/full/ovr16/default_co.gif b/org.eclipse.jdt.ui/icons/full/ovr16/default_co.gif new file mode 100644 index 0000000000..1f91965208 Binary files /dev/null and b/org.eclipse.jdt.ui/icons/full/ovr16/default_co.gif differ diff --git a/org.eclipse.jdt.ui/plugin.xml b/org.eclipse.jdt.ui/plugin.xml index 2c1e21f0fc..db0448f658 100644 --- a/org.eclipse.jdt.ui/plugin.xml +++ b/org.eclipse.jdt.ui/plugin.xml @@ -4207,7 +4207,7 @@ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/> @@ -4225,7 +4225,7 @@ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/> @@ -4242,7 +4242,7 @@ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/> @@ -4259,7 +4259,7 @@ schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"/> @@ -6642,10 +6642,15 @@ id="org.eclipse.jdt.ui.cleanup.variables" runAfter="org.eclipse.jdt.ui.cleanup.loop"> + + + runAfter="org.eclipse.jdt.ui.cleanup.lambda"> org.eclipse.jdt org.eclipse.jdt.ui - 3.9.100-SNAPSHOT + 3.10.0-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java index 2999378132..98264864c2 100644 --- a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java +++ b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java @@ -25,6 +25,7 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; @@ -71,6 +72,7 @@ public class ExtractMethodInputPage extends UserInputWizardPage { private boolean fFirstTime; private JavaSourceViewer fSignaturePreview; private IDialogSettings fSettings; + private Composite accessModifiersGroup; private static final String DESCRIPTION = RefactoringMessages.ExtractMethodInputPage_description; private static final String THROW_RUNTIME_EXCEPTIONS= "ThrowRuntimeExceptions"; //$NON-NLS-1$ @@ -122,6 +124,7 @@ public void createControl(Composite parent) { @Override public void widgetSelected(SelectionEvent e) { fRefactoring.setDestination(combo.getSelectionIndex()); + updateAccessModifiers(); updatePreview(getText()); } }); @@ -130,11 +133,11 @@ public void widgetSelected(SelectionEvent e) { label= new Label(result, SWT.NONE); label.setText(RefactoringMessages.ExtractMethodInputPage_access_Modifiers); - Composite group= new Composite(result, SWT.NONE); - group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + accessModifiersGroup= new Composite(result, SWT.NONE); + accessModifiersGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout= new GridLayout(); layout.numColumns= 4; layout.marginWidth= 0; - group.setLayout(layout); + accessModifiersGroup.setLayout(layout); String[] labels= new String[] { RefactoringMessages.ExtractMethodInputPage_public, @@ -145,7 +148,7 @@ public void widgetSelected(SelectionEvent e) { Integer[] data= new Integer[] {new Integer(Modifier.PUBLIC), new Integer(Modifier.PROTECTED), new Integer(Modifier.NONE), new Integer(Modifier.PRIVATE)}; Integer visibility= new Integer(fRefactoring.getVisibility()); for (int i= 0; i < labels.length; i++) { - Button radio= new Button(group, SWT.RADIO); + Button radio= new Button(accessModifiersGroup, SWT.RADIO); radio.setText(labels[i]); radio.setData(data[i]); if (data[i].equals(visibility)) @@ -159,7 +162,8 @@ public void widgetSelected(SelectionEvent event) { } }); } - layouter.perform(label, group, 1); + updateAccessModifiers(); + layouter.perform(label, accessModifiersGroup, 1); if (!fRefactoring.getParameterInfos().isEmpty()) { ChangeParametersControl cp= new ChangeParametersControl(result, SWT.NONE, @@ -236,7 +240,35 @@ public void widgetSelected(SelectionEvent e) { Dialog.applyDialogFont(result); PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(), IJavaHelpContextIds.EXTRACT_METHOD_WIZARD_PAGE); } - + + private void updateAccessModifiers() { + final Control[] radioButtons= accessModifiersGroup.getChildren(); + if (fRefactoring.isDestinationInterface()) { + Integer visibility= new Integer(Modifier.PUBLIC); + fRefactoring.setVisibility(visibility.intValue()); + for (int i= 0; i < radioButtons.length; i++) { + radioButtons[i].setEnabled(false); + if (radioButtons[i].getData().equals(visibility)) { + ((Button) radioButtons[i]).setSelection(true); + } else { + ((Button) radioButtons[i]).setSelection(false); + } + } + } else { + final String accessModifier= fSettings.get(ACCESS_MODIFIER); + Integer visibility= accessModifier != null ? new Integer(accessModifier) : new Integer(fRefactoring.getVisibility()); + fRefactoring.setVisibility(visibility.intValue()); + for (int i= 0; i < radioButtons.length; i++) { + radioButtons[i].setEnabled(true); + if (radioButtons[i].getData().equals(visibility)) { + ((Button) radioButtons[i]).setSelection(true); + } else { + ((Button) radioButtons[i]).setSelection(false); + } + } + } + } + private String getLabel(ASTNode node) { if (node instanceof AbstractTypeDeclaration) { return ((AbstractTypeDeclaration)node).getName().getIdentifier(); diff --git a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties index 81aad03dc0..719f269f0b 100644 --- a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties +++ b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2012 IBM Corporation and others. +# Copyright (c) 2000, 2013 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -57,7 +57,7 @@ ExtractMethodWizard_extract_method=Extract Method ExtractMethodInputPage_access_Modifiers=&Access modifier: ExtractMethodInputPage_public=public -ExtractMethodInputPage_default=default +ExtractMethodInputPage_default=package ExtractMethodInputPage_protected=protected ExtractMethodInputPage_private=private ExtractMethodInputPage_signature_preview=Method signature preview: @@ -92,7 +92,7 @@ SelfEncapsulateFieldInputPage_first_method=As first method SelfEncapsulateFieldInputPage_access_Modifiers=Access modifier: SelfEncapsulateFieldInputPage_configure_link=Configure naming conventions... SelfEncapsulateFieldInputPage_public=&public -SelfEncapsulateFieldInputPage_default=defa&ult +SelfEncapsulateFieldInputPage_default=p&ackage SelfEncapsulateFieldInputPage_protected=pro&tected SelfEncapsulateFieldInputPage_private=pri&vate SelfEncapsulateFieldInputPage_generateJavadocComment=Generate method &comments @@ -198,7 +198,7 @@ PullUpInputPage_see_log=An unexpected exception occurred. See the error log for ##Change Signature ChangeSignatureInputPage_change=Change the signature of the selected method and all its overriding methods. ChangeSignatureInputPage_access_modifier=A&ccess modifier: -ChangeSignatureInputPage_default=default +ChangeSignatureInputPage_default=package ChangeSignatureInputPage_return_type=Return &type: ChangeSignatureInputPage_method_name=Method &name: ChangeSignatureInputPage_parameters=Pa&rameters @@ -340,7 +340,7 @@ UseSupertypeInputPage_updates_possible_in_files={0} - updates possible in {1} fi UseSupertypeWizard_Use_Super_Type_Where_Possible=Use Super Type Where Possible VisibilityControlUtil_Access_modifier=Access modifier -VisibilityControlUtil_defa_ult_4=d&efault +VisibilityControlUtil_defa_ult_4=packag&e PullUpWizard_defaultPageTitle=Pull Up PullUpWizard_select_all_label=Select &All diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java index 73ff08fc07..267fc5efe1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,7 +14,10 @@ import java.util.Iterator; import java.util.LinkedHashMap; +import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.packageadmin.PackageAdmin; import org.osgi.service.prefs.BackingStoreException; import org.eclipse.swt.widgets.Display; @@ -25,6 +28,7 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.preferences.InstanceScope; @@ -267,6 +271,8 @@ protected boolean removeEldestEntry(java.util.Map.Entry eldest) { */ private IPropertyChangeListener fThemeListener; + private BundleContext fBundleContext; + public static JavaPlugin getDefault() { return fgJavaPlugin; } @@ -358,6 +364,7 @@ public JavaPlugin() { @Override public void start(BundleContext context) throws Exception { super.start(context); + fBundleContext= context; WorkingCopyOwner.setPrimaryBufferProvider(new WorkingCopyOwner() { @Override @@ -1092,4 +1099,28 @@ public static final String getAdditionalInfoAffordanceString() { return JavaUIMessages.JavaPlugin_additionalInfo_affordance; } + + /** + * Returns the bundles for a given bundle name and version range, + * regardless whether the bundle is resolved or not. + * + * @param bundleName the bundle name + * @param version the version of the bundle, or null for all bundles + * @return the bundles of the given name belonging to the given version range + * @since 3.10 + */ + public Bundle[] getBundles(String bundleName, String version) { + Bundle[] bundles= Platform.getBundles(bundleName, version); + if (bundles != null) + return bundles; + + // Accessing unresolved bundle + ServiceReference serviceRef= fBundleContext.getServiceReference(PackageAdmin.class); + PackageAdmin admin= fBundleContext.getService(serviceRef); + bundles= admin.getBundles(bundleName, version); + if (bundles != null && bundles.length > 0) + return bundles; + return null; + } + } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPluginImages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPluginImages.java index bcd1be2527..4e6050a98e 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPluginImages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPluginImages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -370,6 +370,8 @@ public class JavaPluginImages { public static final ImageDescriptor DESC_OBJ_OVERRIDES= createUnManaged(T_OBJ, "over_co.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_OBJ_IMPLEMENTS= createUnManaged(T_OBJ, "implm_co.gif"); //$NON-NLS-1$ + // Image descriptor used for default methods and annotation type elements with a default value + public static final ImageDescriptor DESC_OVR_ANNOTATION_DEFAULT_METHOD= createUnManagedCached(T_OVR, "default_co.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_OVR_STATIC= createUnManagedCached(T_OVR, "static_co.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_OVR_FINAL= createUnManagedCached(T_OVR, "final_co.gif"); //$NON-NLS-1$ public static final ImageDescriptor DESC_OVR_ABSTRACT= createUnManagedCached(T_OVR, "abstract_co.gif"); //$NON-NLS-1$ diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.java index 457306a941..bfb4c44103 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -180,6 +180,7 @@ private JavaUIMessages() { public static String JavaElementLabels_declseparator_string; public static String JavaElementLabels_category_separator_string; public static String JavaElementLabels_onClassPathOf; + public static String JavaElementLinks_title; public static String StatusBarUpdater_num_elements_selected; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.properties index c37b3e2cba..7cba18b327 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaUIMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2010 IBM Corporation and others. +# Copyright (c) 2000, 2014 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -184,6 +184,7 @@ JavaElementLabels_default_package=(default package) JavaElementLabels_import_container=import declarations JavaElementLabels_initializer={...} JavaElementLabels_onClassPathOf=\ (from {0} of {1}) +JavaElementLinks_title=in {0} StatusBarUpdater_num_elements_selected={0} items selected diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties index 900b01711f..91e0a2b229 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties @@ -127,7 +127,7 @@ SourceActionDialog_enterAt_label=&Insertion point: SourceActionDialog_modifier_group=Access modifier SourceActionDialog_modifier_public=&public SourceActionDialog_modifier_protected=protec&ted -SourceActionDialog_modifier_default=d&efault +SourceActionDialog_modifier_default=packag&e SourceActionDialog_modifier_private=pri&vate SourceActionDialog_modifier_synchronized=s&ynchronized SourceActionDialog_modifier_final=&final diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/CopyQualifiedNameAction.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/CopyQualifiedNameAction.java index 85e068123e..40ce6adf2d 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/CopyQualifiedNameAction.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/CopyQualifiedNameAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -65,13 +65,14 @@ import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.PackageDeclaration; -import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.TypeParameter; import org.eclipse.jdt.core.dom.VariableDeclaration; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; + import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.SharedASTProvider; @@ -360,12 +361,10 @@ private Object getSelectedElement(JavaEditor editor) { * @since 3.7 */ private IBinding getConstructorBindingIfAvailable(Name nameNode) { - StructuralPropertyDescriptor loc= nameNode.getLocationInParent(); - if (loc == SimpleType.NAME_PROPERTY) { - ASTNode parent= nameNode.getParent(); - loc= parent.getLocationInParent(); - if (loc == ClassInstanceCreation.TYPE_PROPERTY) - return ((ClassInstanceCreation)parent.getParent()).resolveConstructorBinding(); + ASTNode type= ASTNodes.getNormalizedNode(nameNode); + StructuralPropertyDescriptor loc= type.getLocationInParent(); + if (loc == ClassInstanceCreation.TYPE_PROPERTY) { + return ((ClassInstanceCreation) type.getParent()).resolveConstructorBinding(); } return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateToStringDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateToStringDialog.java index 752e598b44..dba0c64701 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateToStringDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateToStringDialog.java @@ -634,6 +634,7 @@ protected Control createDialogArea(Composite parent) { label.setText(JavaUIMessages.GenerateToStringDialog_templatesManagerPreview); templateTextControl= new Text(composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY); + SWTUtil.fixReadonlyTextBackground(templateTextControl); GridData gd= new GridData(SWT.FILL, SWT.FILL, true, true); gd.heightHint= 80; gd.widthHint= 450; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TableTextCellEditor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TableTextCellEditor.java index e19714c838..a4f9938052 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TableTextCellEditor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TableTextCellEditor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2011 IBM Corporation and others. + * Copyright (c) 2005, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -250,6 +250,8 @@ public void mouseUp(MouseEvent e) { public void focusLost(FocusEvent e) { e.display.asyncExec(new Runnable() { public void run() { + if (text.isDisposed()) + return; // without the asyncExec, focus has not had a chance to go to the content assist proposals TableTextCellEditor.this.focusLost(); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/CustomFiltersDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/CustomFiltersDialog.java index ea40f07112..5c8e2771a6 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/CustomFiltersDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/CustomFiltersDialog.java @@ -196,6 +196,7 @@ private void createCheckBoxList(Composite parent) { info= new Label(parent, SWT.LEFT); info.setText(FilterMessages.CustomFiltersDialog_description_label); final Text description= new Text(parent, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER | SWT.V_SCROLL); + SWTUtil.fixReadonlyTextBackground(description); data = new GridData(GridData.FILL_HORIZONTAL); data.heightHint= convertHeightInCharsToPixels(3); description.setLayoutData(data); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/LambdaExpressionsCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/LambdaExpressionsCleanUp.java new file mode 100644 index 0000000000..f7be12978e --- /dev/null +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/LambdaExpressionsCleanUp.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * Copyright (c) 2013 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.internal.ui.fix; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.eclipse.core.runtime.CoreException; + +import org.eclipse.jdt.core.dom.CompilationUnit; + +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; +import org.eclipse.jdt.internal.corext.fix.LambdaExpressionsFix; + +import org.eclipse.jdt.ui.cleanup.CleanUpContext; +import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; +import org.eclipse.jdt.ui.cleanup.ICleanUpFix; + +public class LambdaExpressionsCleanUp extends AbstractCleanUp { + + public LambdaExpressionsCleanUp(Map options) { + super(options); + } + + public LambdaExpressionsCleanUp() { + super(); + } + + /** + * {@inheritDoc} + */ + @Override + public CleanUpRequirements getRequirements() { + return new CleanUpRequirements(requireAST(), false, false, null); + } + + private boolean requireAST() { + boolean convertFunctionalInterfaces= isEnabled(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + if (!convertFunctionalInterfaces) + return false; + + return isEnabled(CleanUpConstants.USE_LAMBDA) + || isEnabled(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + } + + /** + * {@inheritDoc} + */ + @Override + public ICleanUpFix createFix(CleanUpContext context) throws CoreException { + CompilationUnit compilationUnit= context.getAST(); + if (compilationUnit == null) + return null; + + boolean convertFunctionalInterfaces= isEnabled(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + if (!convertFunctionalInterfaces) + return null; + + return LambdaExpressionsFix.createCleanUp(compilationUnit, + isEnabled(CleanUpConstants.USE_LAMBDA), + isEnabled(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION)); + } + + /** + * {@inheritDoc} + */ + @Override + public String[] getStepDescriptions() { + List result= new ArrayList(); + if (isEnabled(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES)) { + if (isEnabled(CleanUpConstants.USE_LAMBDA)) { + result.add(MultiFixMessages.LambdaExpressionsCleanUp_use_lambda_where_possible); + } + if (isEnabled(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION)) { + result.add(MultiFixMessages.LambdaExpressionsCleanUp_use_anonymous); + } + } + + return result.toArray(new String[result.size()]); + } + + /** + * {@inheritDoc} + */ + @Override + public String getPreview() { + StringBuffer buf= new StringBuffer(); + + boolean convert= isEnabled(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES); + boolean useLambda= isEnabled(CleanUpConstants.USE_LAMBDA); + boolean useAnonymous= isEnabled(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION); + + boolean firstLambda= convert && useLambda; + boolean secondLambda= !(convert && useAnonymous); + + if (firstLambda) { + buf.append("IntConsumer c = i -> {\n"); //$NON-NLS-1$ + buf.append(" System.out.println(i);\n"); //$NON-NLS-1$ + buf.append("};\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + } else { + buf.append("IntConsumer c = new IntConsumer() {\n"); //$NON-NLS-1$ + buf.append(" @Override public void accept(int value) {\n"); //$NON-NLS-1$ + buf.append(" System.out.println(i);\n"); //$NON-NLS-1$ + buf.append(" }\n"); //$NON-NLS-1$ + buf.append("};\n"); //$NON-NLS-1$ + } + + if (secondLambda) { + buf.append("Runnable r = () -> { /* do something */ };\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + buf.append("\n"); //$NON-NLS-1$ + } else { + buf.append("Runnable r = new Runnable() {\n"); //$NON-NLS-1$ + buf.append(" @Override public void run() {\n"); //$NON-NLS-1$ + buf.append(" //do something\n"); //$NON-NLS-1$ + buf.append(" }\n"); //$NON-NLS-1$ + buf.append("};\n"); //$NON-NLS-1$ + } + return buf.toString(); + } + +} diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java index 9f05b024c8..00066795ed 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -94,6 +94,8 @@ private MultiFixMessages() { public static String CodeFormatCleanUp_description; public static String CodeFormatFix_description; + public static String LambdaExpressionsCleanUp_use_lambda_where_possible; + public static String LambdaExpressionsCleanUp_use_anonymous; public static String NullAnnotationsCleanUp_add_nullable_annotation; public static String NullAnnotationsCleanUp_add_nonnull_annotation; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties index 21e948553f..76c4ba560b 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/MultiFixMessages.properties @@ -78,6 +78,8 @@ CleanUpRefactoringWizard_CustomCleanUpsDialog_title=Custom Clean Ups CodeFormatFix_description=Format code CodeFormatCleanUp_description=Format source code ImportsCleanUp_OrganizeImports_Description=Organize imports +LambdaExpressionsCleanUp_use_lambda_where_possible=Use lambda where possible +LambdaExpressionsCleanUp_use_anonymous=Use anonymous class creations SortMembersCleanUp_AllMembers_description=Sort all members SortMembersCleanUp_Excluding_description=Sort members excluding fields, enum constants, and initializers SortMembersCleanUp_RemoveMarkersWarning0=The file ''{0}'' in project ''{1}'' contains markers which may be removed by Sort Members diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java index e2345629b2..8c2abc07d5 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -144,7 +144,7 @@ private void createExtraOptionsGroup(Composite composite) { fSourceCombo= createCombo(inner, SWT.NONE, fStore.getSource(), createGridData(1)); String[] versions= { "-", //$NON-NLS-1$ - JavaCore.VERSION_1_3, JavaCore.VERSION_1_4, JavaCore.VERSION_1_5, JavaCore.VERSION_1_6, JavaCore.VERSION_1_7 }; + JavaCore.VERSION_1_3, JavaCore.VERSION_1_4, JavaCore.VERSION_1_5, JavaCore.VERSION_1_6, JavaCore.VERSION_1_7, JavaCore.VERSION_1_8 }; fSourceCombo.setItems(versions); fSourceCombo.setText(fStore.getSource()); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ASTProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ASTProvider.java index 48b5340e43..5abbaa7979 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ASTProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ASTProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -202,7 +202,7 @@ private boolean isJavaEditor(IWorkbenchPartReference ref) { } } - public static final int SHARED_AST_LEVEL= AST.JLS4; + public static final int SHARED_AST_LEVEL= AST.JLS8; public static final boolean SHARED_AST_STATEMENT_RECOVERY= true; public static final boolean SHARED_BINDING_RECOVERY= true; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightings.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightings.java index 726169a054..8b7ed5f332 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightings.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightings.java @@ -35,18 +35,18 @@ import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.PrefixExpression; import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; -import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.ui.PreferenceConstants; @@ -480,12 +480,15 @@ private boolean isAutoUnBoxing(Expression node) { return isAutoUnBoxingExpression((Expression) parent); } // B) constructor invocations - if (desc == SimpleType.NAME_PROPERTY || desc == QualifiedType.NAME_PROPERTY) { + if (desc == QualifiedName.NAME_PROPERTY) { + node= (Expression) node.getParent(); + desc= node.getLocationInParent(); + } + if (desc == SimpleType.NAME_PROPERTY || desc == NameQualifiedType.NAME_PROPERTY) { ASTNode parent= node.getParent(); if (parent != null && parent.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { parent= parent.getParent(); - if (parent instanceof Expression) - return isAutoUnBoxingExpression((Expression) parent); + return isAutoUnBoxingExpression((ClassInstanceCreation) parent); } } return false; @@ -908,54 +911,9 @@ public String getDisplayName() { */ @Override public boolean consumes(SemanticToken token) { - IBinding binding= getMethodBinding(token); + IBinding binding= getBinding(token); return binding != null && binding.getKind() == IBinding.METHOD; } - - /** - * Extracts the method binding from the token's simple name. The method - * binding is either the token's binding (if the parent of token is a - * method call or declaration) or the constructor binding of a class - * instance creation if the node is the type name of a class instance - * creation. - * - * @param token the token to extract the method binding from - * @return the corresponding method binding, or null - */ - private IBinding getMethodBinding(SemanticToken token) { - IBinding binding= null; - // work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605 - ASTNode node= token.getNode(); - ASTNode parent= node.getParent(); - while (isTypePath(node, parent)) { - node= parent; - parent= parent.getParent(); - } - - if (parent != null && node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) - binding= ((ClassInstanceCreation) parent).resolveConstructorBinding(); - else - binding= token.getBinding(); - return binding; - } - - /** - * Returns true if the given child/parent nodes are valid - * sub nodes of a Type ASTNode. - * @param child the child node - * @param parent the parent node - * @return true if the nodes may be the sub nodes of a type node, false otherwise - */ - private boolean isTypePath(ASTNode child, ASTNode parent) { - if (parent instanceof Type) { - StructuralPropertyDescriptor location= child.getLocationInParent(); - return location == ParameterizedType.TYPE_PROPERTY || location == SimpleType.NAME_PROPERTY; - } else if (parent instanceof QualifiedName) { - StructuralPropertyDescriptor location= child.getLocationInParent(); - return location == QualifiedName.NAME_PROPERTY; - } - return false; - } } /** @@ -1230,7 +1188,7 @@ public String getDisplayName() { */ @Override public boolean consumes(SemanticToken token) { - IBinding binding= getMethodBinding(token); + IBinding binding= getBinding(token); if (binding != null) { if (binding.isDeprecated()) return true; @@ -1251,51 +1209,6 @@ public boolean consumes(SemanticToken token) { } return false; } - - /** - * Extracts the method binding from the token's simple name. The method - * binding is either the token's binding (if the parent of token is a - * method call or declaration) or the constructor binding of a class - * instance creation if the node is the type name of a class instance - * creation. - * - * @param token the token to extract the method binding from - * @return the corresponding method binding, or null - */ - private IBinding getMethodBinding(SemanticToken token) { - IBinding binding= null; - // work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605 - ASTNode node= token.getNode(); - ASTNode parent= node.getParent(); - while (isTypePath(node, parent)) { - node= parent; - parent= parent.getParent(); - } - - if (parent != null && node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) - binding= ((ClassInstanceCreation) parent).resolveConstructorBinding(); - else - binding= token.getBinding(); - return binding; - } - - /** - * Returns true if the given child/parent nodes are valid - * sub nodes of a Type ASTNode. - * @param child the child node - * @param parent the parent node - * @return true if the nodes may be the sub nodes of a type node, false otherwise - */ - private boolean isTypePath(ASTNode child, ASTNode parent) { - if (parent instanceof Type) { - StructuralPropertyDescriptor location= child.getLocationInParent(); - return location == ParameterizedType.TYPE_PROPERTY || location == SimpleType.NAME_PROPERTY; - } else if (parent instanceof QualifiedName) { - StructuralPropertyDescriptor location= child.getLocationInParent(); - return location == QualifiedName.NAME_PROPERTY; - } - return false; - } } /** @@ -2191,9 +2104,9 @@ private static void convertMethodHighlightingPreferences(IPreferenceStore store) String italickey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ITALIC_SUFFIX; String enabledkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + METHOD + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX; - String oldColorkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR; - String oldBoldkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD; - String oldItalickey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC; + @SuppressWarnings("deprecation") String oldColorkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR; + @SuppressWarnings("deprecation") String oldBoldkey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD; + @SuppressWarnings("deprecation") String oldItalickey= PreferenceConstants.EDITOR_JAVA_METHOD_NAME_ITALIC; if (conditionalReset(store, oldColorkey, colorkey) || conditionalReset(store, oldBoldkey, boldkey) @@ -2225,11 +2138,11 @@ private static void convertAnnotationHighlightingPreferences(IPreferenceStore st String underlineKey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_UNDERLINE_SUFFIX; String enabledkey= PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_PREFIX + ANNOTATION + PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED_SUFFIX; - String oldColorkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_COLOR; - String oldBoldkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_BOLD; - String oldItalickey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_ITALIC; - String oldStrikethroughKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_STRIKETHROUGH; - String oldUnderlineKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_UNDERLINE; + @SuppressWarnings("deprecation") String oldColorkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_COLOR; + @SuppressWarnings("deprecation") String oldBoldkey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_BOLD; + @SuppressWarnings("deprecation") String oldItalickey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_ITALIC; + @SuppressWarnings("deprecation") String oldStrikethroughKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_STRIKETHROUGH; + @SuppressWarnings("deprecation") String oldUnderlineKey= PreferenceConstants.EDITOR_JAVA_ANNOTATION_UNDERLINE; if (conditionalReset(store, oldColorkey, colorkey) || conditionalReset(store, oldBoldkey, boldkey) @@ -2286,6 +2199,23 @@ private static void setDefaultAndFireEvent(IPreferenceStore store, String key, R store.firePropertyChangeEvent(key, oldValue, newValue); } + /** + * Extracts the binding from the token's simple name. + * Works around bug 62605 to return the correct constructor binding in a ClassInstanceCreation. + * + * @param token the token to extract the binding from + * @return the token's binding, or null + */ + private static IBinding getBinding(SemanticToken token) { + ASTNode node= token.getNode(); + ASTNode normalized= ASTNodes.getNormalizedNode(node); + if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { + // work around: https://bugs.eclipse.org/bugs/show_bug.cgi?id=62605 + return ((ClassInstanceCreation) normalized.getParent()).resolveConstructorBinding(); + } + return token.getBinding(); + } + /** * Do not instantiate */ diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java index dd85deac42..46975e39a1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -102,6 +102,7 @@ public class ComplianceConfigurationBlock extends OptionsConfigurationBlock { private static final Key PREF_LINE_NUMBER_ATTR= getJDTCoreKey(JavaCore.COMPILER_LINE_NUMBER_ATTR); private static final Key PREF_SOURCE_FILE_ATTR= getJDTCoreKey(JavaCore.COMPILER_SOURCE_FILE_ATTR); private static final Key PREF_CODEGEN_UNUSED_LOCAL= getJDTCoreKey(JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL); + private static final Key PREF_CODEGEN_METHOD_PARAMETERS_ATTR= getJDTCoreKey(JavaCore.COMPILER_CODEGEN_METHOD_PARAMETERS_ATTR); // values private static final String GENERATE= JavaCore.GENERATE; @@ -119,6 +120,7 @@ public class ComplianceConfigurationBlock extends OptionsConfigurationBlock { private static final String VERSION_1_5= JavaCore.VERSION_1_5; private static final String VERSION_1_6= JavaCore.VERSION_1_6; private static final String VERSION_1_7= JavaCore.VERSION_1_7; + private static final String VERSION_1_8= JavaCore.VERSION_1_8; private static final String VERSION_JSR14= "jsr14"; //$NON-NLS-1$ private static final String ERROR= JavaCore.ERROR; @@ -137,14 +139,16 @@ public class ComplianceConfigurationBlock extends OptionsConfigurationBlock { private PixelConverter fPixelConverter; /** - * Remembered user compliance (stored when {@link #INTR_DEFAULT_COMPLIANCE} is switched to {@link #DEFAULT_CONF}). - * Elements are identified by IDX_* constants. + * Remembered user compliance (stored when {@link #INTR_DEFAULT_COMPLIANCE} is switched to + * {@link #DEFAULT_CONF}). Elements are identified by IDX_* constants. + * * @see #IDX_ASSERT_AS_IDENTIFIER * @see #IDX_ENUM_AS_IDENTIFIER * @see #IDX_SOURCE_COMPATIBILITY * @see #IDX_CODEGEN_TARGET_PLATFORM * @see #IDX_COMPLIANCE * @see #IDX_INLINE_JSR_BYTECODE + * @see #IDX_METHOD_PARAMETERS_ATTR */ private String[] fRememberedUserCompliance; @@ -157,6 +161,7 @@ public class ComplianceConfigurationBlock extends OptionsConfigurationBlock { * @see #IDX_CODEGEN_TARGET_PLATFORM * @see #IDX_COMPLIANCE * @see #IDX_INLINE_JSR_BYTECODE + * @see #IDX_METHOD_PARAMETERS_ATTR */ private String[] fOriginalStoredCompliance; @@ -166,6 +171,7 @@ public class ComplianceConfigurationBlock extends OptionsConfigurationBlock { private static final int IDX_CODEGEN_TARGET_PLATFORM= 3; private static final int IDX_COMPLIANCE= 4; private static final int IDX_INLINE_JSR_BYTECODE= 5; + private static final int IDX_METHOD_PARAMETERS_ATTR= 6; private IStatus fComplianceStatus; @@ -192,6 +198,7 @@ public ComplianceConfigurationBlock(IStatusChangeListener context, IProject proj getValue(PREF_CODEGEN_TARGET_PLATFORM), getValue(PREF_COMPLIANCE), getValue(PREF_CODEGEN_INLINE_JSR_BYTECODE), + getValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR) }; } @@ -199,7 +206,7 @@ private static Key[] getKeys(boolean projectSpecific) { Key[] keys= new Key[] { PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, PREF_CODEGEN_INLINE_JSR_BYTECODE, INTR_DEFAULT_COMPLIANCE, PREF_COMPLIANCE, PREF_SOURCE_COMPATIBILITY, - PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_ENUM_AS_IDENTIFIER + PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_ENUM_AS_IDENTIFIER, PREF_CODEGEN_METHOD_PARAMETERS_ATTR }; if (projectSpecific) { @@ -254,13 +261,14 @@ public void enablePreferenceContent(boolean enable) { private Composite createComplianceTabContent(Composite folder) { - String[] values3456= new String[] { VERSION_1_3, VERSION_1_4, VERSION_1_5, VERSION_1_6, VERSION_1_7 }; + String[] values3456= new String[] { VERSION_1_3, VERSION_1_4, VERSION_1_5, VERSION_1_6, VERSION_1_7, VERSION_1_8 }; String[] values3456Labels= new String[] { PreferencesMessages.ComplianceConfigurationBlock_version13, PreferencesMessages.ComplianceConfigurationBlock_version14, PreferencesMessages.ComplianceConfigurationBlock_version15, PreferencesMessages.ComplianceConfigurationBlock_version16, - PreferencesMessages.ComplianceConfigurationBlock_version17 + PreferencesMessages.ComplianceConfigurationBlock_version17, + PreferencesMessages.ComplianceConfigurationBlock_version18, }; final ScrolledPageContent sc1 = new ScrolledPageContent(folder); @@ -325,16 +333,17 @@ public void widgetSelected(SelectionEvent e) { int indent= LayoutUtil.getIndent(); - String[] versions= new String[] { VERSION_CLDC_1_1, VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4, VERSION_1_5, VERSION_1_6, VERSION_1_7 }; + String[] versions= new String[] { VERSION_CLDC_1_1, VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4, VERSION_1_5, VERSION_1_6, VERSION_1_7, VERSION_1_8 }; String[] versionsLabels= new String[] { - PreferencesMessages.ComplianceConfigurationBlock_versionCLDC11, - PreferencesMessages.ComplianceConfigurationBlock_version11, - PreferencesMessages.ComplianceConfigurationBlock_version12, - PreferencesMessages.ComplianceConfigurationBlock_version13, - PreferencesMessages.ComplianceConfigurationBlock_version14, - PreferencesMessages.ComplianceConfigurationBlock_version15, - PreferencesMessages.ComplianceConfigurationBlock_version16, - PreferencesMessages.ComplianceConfigurationBlock_version17 + PreferencesMessages.ComplianceConfigurationBlock_versionCLDC11, + PreferencesMessages.ComplianceConfigurationBlock_version11, + PreferencesMessages.ComplianceConfigurationBlock_version12, + PreferencesMessages.ComplianceConfigurationBlock_version13, + PreferencesMessages.ComplianceConfigurationBlock_version14, + PreferencesMessages.ComplianceConfigurationBlock_version15, + PreferencesMessages.ComplianceConfigurationBlock_version16, + PreferencesMessages.ComplianceConfigurationBlock_version17, + PreferencesMessages.ComplianceConfigurationBlock_version18 }; boolean showJsr14= ComplianceConfigurationBlock.VERSION_JSR14.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)); @@ -395,6 +404,9 @@ public void widgetSelected(SelectionEvent e) { label= PreferencesMessages.ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label; addCheckBox(group, label, PREF_CODEGEN_INLINE_JSR_BYTECODE, enableDisableValues, 0); + label= PreferencesMessages.ComplianceConfigurationBlock_codegen_method_parameters_attr; + addCheckBox(group, label, PREF_CODEGEN_METHOD_PARAMETERS_ATTR, generateValues, 0); + Composite infoComposite= new Composite(fControlsComposite, SWT.NONE); infoComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); infoComposite.setLayout(new GridLayout(2, false)); @@ -502,6 +514,7 @@ protected void validateSettings(Key changedKey, String oldValue, String newValue } updateControls(); updateInlineJSREnableState(); + updateStoreMethodParamNamesEnableState(); updateAssertEnumAsIdentifierEnableState(); fComplianceStatus= validateCompliance(); } else if (PREF_PB_ENUM_AS_IDENTIFIER.equals(changedKey) || @@ -516,6 +529,7 @@ protected void validateSettings(Key changedKey, String oldValue, String newValue updateComplianceEnableState(); updateAssertEnumAsIdentifierEnableState(); updateInlineJSREnableState(); + updateStoreMethodParamNamesEnableState(); fComplianceStatus= validateCompliance(); validateComplianceStatus(); } @@ -532,6 +546,7 @@ public void refreshComplianceSettings() { getOriginalStoredValue(PREF_CODEGEN_TARGET_PLATFORM), getOriginalStoredValue(PREF_COMPLIANCE), getOriginalStoredValue(PREF_CODEGEN_INLINE_JSR_BYTECODE), + getOriginalStoredValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR) }; } else { @@ -542,6 +557,7 @@ public void refreshComplianceSettings() { getOriginalStoredValue(PREF_CODEGEN_TARGET_PLATFORM), getOriginalStoredValue(PREF_COMPLIANCE), getOriginalStoredValue(PREF_CODEGEN_INLINE_JSR_BYTECODE), + getOriginalStoredValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR) }; if (!Arrays.equals(fOriginalStoredCompliance, storedCompliance)) { // compliance changed on disk -> override user modifications @@ -554,6 +570,7 @@ public void refreshComplianceSettings() { setValue(PREF_CODEGEN_TARGET_PLATFORM, storedCompliance[IDX_CODEGEN_TARGET_PLATFORM]); setValue(PREF_COMPLIANCE, storedCompliance[IDX_COMPLIANCE]); setValue(PREF_CODEGEN_INLINE_JSR_BYTECODE, storedCompliance[IDX_INLINE_JSR_BYTECODE]); + setValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR, storedCompliance[IDX_METHOD_PARAMETERS_ATTR]); } @@ -562,6 +579,7 @@ public void refreshComplianceSettings() { updateComplianceEnableState(); validateComplianceStatus(); updateInlineJSREnableState(); + updateStoreMethodParamNamesEnableState(); } } } @@ -592,6 +610,13 @@ private void validateComplianceStatus() { isVisible= true; } } + +// String source= getValue(PREF_SOURCE_COMPATIBILITY); +// if (VERSION_1_8.equals(source)) { +// fJRE50InfoText.setText("This is an implementation of an early-draft specification developed under the Java Community Process (JCP) and is made available for testing and evaluation purposes only. The code is not compatible with any specification of the JCP."); //$NON-NLS-1$ +// isVisible= true; +// } + fJRE50InfoText.setVisible(isVisible); fJRE50InfoImage.setImage(isVisible ? JFaceResources.getImage(Dialog.DLG_IMG_MESSAGE_WARNING) : null); fJRE50InfoImage.getParent().layout(); @@ -756,6 +781,33 @@ private void updateInlineJSREnableState() { } } + private void updateStoreMethodParamNamesEnableState() { + String target= getValue(PREF_CODEGEN_TARGET_PLATFORM); + boolean enabled= JavaModelUtil.is18OrHigher(target); + Button checkBox= getCheckBox(PREF_CODEGEN_METHOD_PARAMETERS_ATTR); + boolean wasCheckBoxEnabled= checkBox.isEnabled(); + checkBox.setEnabled(enabled); + + if (enabled) { + if (!wasCheckBoxEnabled) { + String val= fRememberedUserCompliance[IDX_METHOD_PARAMETERS_ATTR]; + if (GENERATE.equals(val)) { + setValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR, val); + updateCheckBox(checkBox); + } + } + } else { + String val= getValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR); + if (wasCheckBoxEnabled) + fRememberedUserCompliance[IDX_METHOD_PARAMETERS_ATTR]= val; + + if (GENERATE.equals(val)) { + setValue(PREF_CODEGEN_METHOD_PARAMETERS_ATTR, DO_NOT_GENERATE); + updateCheckBox(checkBox); + } + } + } + /** * Sets the default compliance values derived from the chosen level or restores the user * compliance settings. @@ -822,6 +874,11 @@ private void updateComplianceDefaultSettings(boolean rememberOld, String oldComp enumAsId= ERROR; source= VERSION_1_7; target= VERSION_1_7; + } else if (VERSION_1_8.equals(complianceLevel)) { + assertAsId= ERROR; + enumAsId= ERROR; + source= VERSION_1_8; + target= VERSION_1_8; } else { assertAsId= IGNORE; enumAsId= IGNORE; @@ -838,6 +895,7 @@ private void updateComplianceDefaultSettings(boolean rememberOld, String oldComp } else { updateInlineJSREnableState(); updateAssertEnumAsIdentifierEnableState(); + updateStoreMethodParamNamesEnableState(); return; } } @@ -848,6 +906,7 @@ private void updateComplianceDefaultSettings(boolean rememberOld, String oldComp updateControls(); updateInlineJSREnableState(); updateAssertEnumAsIdentifierEnableState(); + updateStoreMethodParamNamesEnableState(); } /** @@ -882,7 +941,12 @@ private String getCurrentCompliance() { && ERROR.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER)) && ERROR.equals(getValue(PREF_PB_ENUM_AS_IDENTIFIER)) && VERSION_1_7.equals(getValue(PREF_SOURCE_COMPATIBILITY)) - && VERSION_1_7.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))) { + && VERSION_1_7.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM))) + || (VERSION_1_8.equals(complianceLevel) + && ERROR.equals(getValue(PREF_PB_ASSERT_AS_IDENTIFIER)) + && ERROR.equals(getValue(PREF_PB_ENUM_AS_IDENTIFIER)) + && VERSION_1_8.equals(getValue(PREF_SOURCE_COMPATIBILITY)) + && VERSION_1_8.equals(getValue(PREF_CODEGEN_TARGET_PLATFORM)))) { return DEFAULT_CONF; } return USER_CONF; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java index b6cd40d59a..17c8f0a679 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorHoverConfigurationBlock.java @@ -351,6 +351,7 @@ public void modifyText(ModifyEvent e) { gd.horizontalSpan= 2; descriptionLabel.setLayoutData(gd); fDescription= new Text(hoverComposite, SWT.LEFT | SWT.WRAP | SWT.MULTI | SWT.READ_ONLY | SWT.BORDER); + SWTUtil.fixReadonlyTextBackground(fDescription); gd= new GridData(GridData.FILL_BOTH); gd.horizontalSpan= 2; fDescription.setLayoutData(gd); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java index 2a89e8996d..9348506871 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocConfigurationPropertyPage.java @@ -59,6 +59,7 @@ import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; +import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.ArchiveFileFilter; @@ -166,6 +167,7 @@ protected Control createContents(Composite parent) { label.setText(PreferencesMessages.JavadocConfigurationPropertyPage_location_path); Text location= new Text(inner, SWT.READ_ONLY | SWT.WRAP); + SWTUtil.fixReadonlyTextBackground(location); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= convertWidthInCharsToPixels(80); location.setLayoutData(gd); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NativeLibrariesPropertyPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NativeLibrariesPropertyPage.java index 3d260b148f..8e0c83ea78 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NativeLibrariesPropertyPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NativeLibrariesPropertyPage.java @@ -56,6 +56,7 @@ import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; +import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.ArchiveFileFilter; @@ -147,6 +148,7 @@ protected Control createContents(Composite parent) { label.setText(PreferencesMessages.NativeLibrariesPropertyPage_location_path); Text location= new Text(inner, SWT.READ_ONLY | SWT.WRAP); + SWTUtil.fixReadonlyTextBackground(location); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= convertWidthInCharsToPixels(80); location.setLayoutData(gd); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java index 4b64667058..a5583f709b 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java @@ -492,6 +492,7 @@ private PreferencesMessages() { public static String ComplianceConfigurationBlock_codegen_unused_local_label; public static String ComplianceConfigurationBlock_cldc11_requires_source13_compliance_se14; public static String ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label; + public static String ComplianceConfigurationBlock_codegen_method_parameters_attr; public static String ComplianceConfigurationBlock_compiler_compliance_label; public static String ComplianceConfigurationBlock_default_settings_label; public static String ComplianceConfigurationBlock_source_compatibility_label; @@ -787,6 +788,7 @@ private PreferencesMessages() { public static String CodeAssistConfigurationBlock_matchCamelCase_label; public static String ComplianceConfigurationBlock_version16; public static String ComplianceConfigurationBlock_version17; + public static String ComplianceConfigurationBlock_version18; public static String ComplianceConfigurationBlock_versionCLDC11; public static String ComplianceConfigurationBlock_src_greater_compliance; public static String ComplianceConfigurationBlock_classfile_greater_compliance; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties index f1a4df09ab..9c50ddb688 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties @@ -495,7 +495,7 @@ JavadocProblemsPreferencePage_title=Javadoc Comments JavadocProblemsConfigurationBlock_allStandardTags=Validate all standard tags JavadocProblemsConfigurationBlock_public=Public JavadocProblemsConfigurationBlock_protected=Protected -JavadocProblemsConfigurationBlock_default=Default +JavadocProblemsConfigurationBlock_default=Package JavadocProblemsConfigurationBlock_private=Private JavadocProblemsConfigurationBlock_error=Error @@ -541,6 +541,7 @@ ComplianceConfigurationBlock_version14=1.4 ComplianceConfigurationBlock_version15=1.5 ComplianceConfigurationBlock_version16=1.6 ComplianceConfigurationBlock_version17=1.7 +ComplianceConfigurationBlock_version18=1.8 ComplianceConfigurationBlock_versionCLDC11=CLDC 1.1 ComplianceConfigurationBlock_needsbuild_title=Compiler Settings Changed @@ -553,6 +554,7 @@ ComplianceConfigurationBlock_source_file_attr_label=Add source &file name to gen ComplianceConfigurationBlock_src_greater_compliance=Source compatibility must be equal or less than compliance level. ComplianceConfigurationBlock_codegen_unused_local_label=Pr&eserve unused (never read) local variables ComplianceConfigurationBlock_codegen_inline_jsr_bytecode_label=Inline finally blo&cks (larger class files, but improved performance) +ComplianceConfigurationBlock_codegen_method_parameters_attr=&Store method parameter names (usable via reflection) ComplianceConfigurationBlock_compiler_compliance_label=Comp&iler compliance level: ComplianceConfigurationBlock_default_settings_label=Use defaul&t compliance settings ComplianceConfigurationBlock_source_compatibility_label=Source co&mpatibility: @@ -633,7 +635,7 @@ MembersOrderPreferencePage_types_label=Types MembersOrderPreferencePage_public_label=Public MembersOrderPreferencePage_private_label=Private MembersOrderPreferencePage_protected_label=Protected -MembersOrderPreferencePage_default_label=Default +MembersOrderPreferencePage_default_label=Package MembersOrderPreferencePage_usevisibilitysort_label=&Sort members in same category by visibility CodeTemplateBlock_templates_comment_node=Comments CodeTemplateBlock_templates_code_node=Code diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.java index 092b8c0cba..8c6f042950 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.java @@ -52,6 +52,7 @@ import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; +import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock; @@ -153,6 +154,7 @@ private Control createMessageContent(Composite composite, String message, IPacka message= message + "\n\n" + PreferencesMessages.SourceAttachmentPropertyPage_location_path; //$NON-NLS-1$ Text location= new Text(inner, SWT.READ_ONLY | SWT.WRAP); + SWTUtil.fixReadonlyTextBackground(location); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= convertWidthInCharsToPixels(80); location.setLayoutData(gd); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java index 47a5578aad..88540a37b4 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -53,15 +53,22 @@ public class CleanUpMessages extends NLS { public static String CodeStyleTabPage_CheckboxName_UseFinalForFields; public static String CodeStyleTabPage_CheckboxName_UseFinalForLocals; public static String CodeStyleTabPage_CheckboxName_UseFinalForParameters; + public static String CodeStyleTabPage_CheckboxName_UseParentheses; public static String CodeStyleTabPage_GroupName_ControlStatments; public static String CodeStyleTabPage_GroupName_Expressions; + public static String CodeStyleTabPage_GroupName_VariableDeclarations; public static String CodeStyleTabPage_RadioName_AlwaysUseBlocks; public static String CodeStyleTabPage_RadioName_AlwaysUseParantheses; public static String CodeStyleTabPage_RadioName_NeverUseBlocks; public static String CodeStyleTabPage_RadioName_NeverUseParantheses; public static String CodeStyleTabPage_RadioName_UseBlocksSpecial; + + public static String CodeStyleTabPage_GroupName_FunctionalInterfaces; + public static String CodeStyleTabPage_CheckboxName_ConvertFunctionalInterfaces; + public static String CodeStyleTabPage_RadioName_UseLambdaWherePossible; + public static String CodeStyleTabPage_RadioName_UseAnonymous; public static String ContributedCleanUpTabPage_ErrorPage_message; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties index 4221d23c4a..cdc8b20dd3 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CleanUpMessages.properties @@ -47,6 +47,10 @@ CodeStyleTabPage_CheckboxName_ConvertForLoopToEnhanced=Conver&t 'for' loops to e CodeStyleTabPage_GroupName_ControlStatments=Control statements CodeStyleTabPage_RadioName_UseBlocksSpecial=Always &except for single 'return' or 'throw' statements CodeStyleTabPage_CheckboxName_UseParentheses=Use parent&heses in expressions +CodeStyleTabPage_GroupName_FunctionalInterfaces=Functional interface instances +CodeStyleTabPage_CheckboxName_ConvertFunctionalInterfaces=Con&vert functional interface instances +CodeStyleTabPage_RadioName_UseLambdaWherePossible=Use lambda where possible +CodeStyleTabPage_RadioName_UseAnonymous=Use anonymous class ContributedCleanUpTabPage_ErrorPage_message=An error occurred while creating this page. See the error log for details MemberAccessesTabPage_GroupName_NonStaticAccesses=Non static accesses diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java index 6db7e4b9d4..902014c378 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/cleanup/CodeStyleTabPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -21,6 +21,7 @@ import org.eclipse.jdt.internal.ui.fix.ControlStatementsCleanUp; import org.eclipse.jdt.internal.ui.fix.ConvertLoopCleanUp; import org.eclipse.jdt.internal.ui.fix.ExpressionsCleanUp; +import org.eclipse.jdt.internal.ui.fix.LambdaExpressionsCleanUp; import org.eclipse.jdt.internal.ui.fix.VariableDeclarationCleanUp; public final class CodeStyleTabPage extends AbstractCleanUpTabPage { @@ -37,7 +38,8 @@ protected AbstractCleanUp[] createPreviewCleanUps(Map values) { new ControlStatementsCleanUp(values), new ConvertLoopCleanUp(values), new ExpressionsCleanUp(values), - new VariableDeclarationCleanUp(values) + new VariableDeclarationCleanUp(values), + new LambdaExpressionsCleanUp(values) }; } @@ -74,5 +76,13 @@ protected void doCreatePreferences(Composite composite, int numColumns) { final CheckboxPreference useFinalParametersPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForParameters, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_PARAMETERS, CleanUpModifyDialog.FALSE_TRUE); final CheckboxPreference useFinalVariablesPref= createCheckboxPref(variableGroup, 1, CleanUpMessages.CodeStyleTabPage_CheckboxName_UseFinalForLocals, CleanUpConstants.VARIABLE_DECLARATIONS_USE_FINAL_LOCAL_VARIABLES, CleanUpModifyDialog.FALSE_TRUE); registerSlavePreference(useFinalPref, new CheckboxPreference[] {useFinalFieldsPref, useFinalParametersPref, useFinalVariablesPref}); - } + + Group functionalInterfacesGroup= createGroup(numColumns, composite, CleanUpMessages.CodeStyleTabPage_GroupName_FunctionalInterfaces); + + CheckboxPreference convertFunctionalInterfaces= createCheckboxPref(functionalInterfacesGroup, numColumns, CleanUpMessages.CodeStyleTabPage_CheckboxName_ConvertFunctionalInterfaces, CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES, CleanUpModifyDialog.FALSE_TRUE); + intent(functionalInterfacesGroup); + RadioPreference useLambdaPref= createRadioPref(functionalInterfacesGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_UseLambdaWherePossible, CleanUpConstants.USE_LAMBDA, CleanUpModifyDialog.FALSE_TRUE); + RadioPreference useAnonymousPref= createRadioPref(functionalInterfacesGroup, 1, CleanUpMessages.CodeStyleTabPage_RadioName_UseAnonymous, CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION, CleanUpModifyDialog.FALSE_TRUE); + registerSlavePreference(convertFunctionalInterfaces, new RadioPreference[] { useLambdaPref, useAnonymousPref }); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/BracesTabPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/BracesTabPage.java index 39092ec0e1..270abaeb1c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/BracesTabPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/BracesTabPage.java @@ -42,6 +42,9 @@ public class BracesTabPage extends FormatterTabPage { " int [] myArray= {1,2,3,4,5,6};" + //$NON-NLS-1$ " int [] emptyArray= new int[] {};" + //$NON-NLS-1$ " Example() {" + //$NON-NLS-1$ + " Runnable r = () -> {"+ //$NON-NLS-1$ + " fField.set(20);"+ //$NON-NLS-1$ + " };"+ //$NON-NLS-1$ " }" + //$NON-NLS-1$ " void bar(int p) {" + //$NON-NLS-1$ " for (int i= 0; i<10; i++) {" + //$NON-NLS-1$ @@ -65,12 +68,6 @@ public class BracesTabPage extends FormatterTabPage { private final String [] fBracePositions= { - DefaultCodeFormatterConstants.END_OF_LINE, - DefaultCodeFormatterConstants.NEXT_LINE, - DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED - }; - - private final String [] fExtendedBracePositions= { DefaultCodeFormatterConstants.END_OF_LINE, DefaultCodeFormatterConstants.NEXT_LINE, DefaultCodeFormatterConstants.NEXT_LINE_SHIFTED, @@ -78,12 +75,6 @@ public class BracesTabPage extends FormatterTabPage { }; private final String [] fBracePositionNames= { - FormatterMessages.BracesTabPage_position_same_line, - FormatterMessages.BracesTabPage_position_next_line, - FormatterMessages.BracesTabPage_position_next_line_indented - }; - - private final String [] fExtendedBracePositionNames= { FormatterMessages.BracesTabPage_position_same_line, FormatterMessages.BracesTabPage_position_next_line, FormatterMessages.BracesTabPage_position_next_line_indented, @@ -105,15 +96,15 @@ public BracesTabPage(ModifyDialog modifyDialog, Map workingValue protected void doCreatePreferences(Composite composite, int numColumns) { final Group group= createGroup(numColumns, composite, FormatterMessages.BracesTabPage_group_brace_positions_title); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_anonymous_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_constructor_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_method_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enumconst_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_annotation_type_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); - createExtendedBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks_in_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_anonymous_class_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANONYMOUS_TYPE_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_constructor_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_CONSTRUCTOR_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_method_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_METHOD_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enum_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_enumconst_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ENUM_CONSTANT); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_annotation_type_declaration, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ANNOTATION_TYPE_DECLARATION); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK); + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_blocks_in_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_BLOCK_IN_CASE); createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_switch_case, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_SWITCH); ComboPreference arrayInitOption= createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_array_initializer, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_ARRAY_INITIALIZER); @@ -125,6 +116,8 @@ public void update(Observable o, Object arg) { } }); updateOptionEnablement(arrayInitOption, arrayInitCheckBox); + + createBracesCombo(group, numColumns, FormatterMessages.BracesTabPage_option_lambda_body, DefaultCodeFormatterConstants.FORMATTER_BRACE_POSITION_FOR_LAMBDA_BODY); } protected final void updateOptionEnablement(ComboPreference arrayInitOption, CheckboxPreference arrayInitCheckBox) { @@ -146,10 +139,6 @@ private ComboPreference createBracesCombo(Composite composite, int numColumns, S return createComboPref(composite, numColumns, message, key, fBracePositions, fBracePositionNames); } - private ComboPreference createExtendedBracesCombo(Composite composite, int numColumns, String message, String key) { - return createComboPref(composite, numColumns, message, key, fExtendedBracePositions, fExtendedBracePositionNames); - } - private CheckboxPreference createIndentedCheckboxPref(Composite composite, int numColumns, String message, String key, String [] values) { CheckboxPreference pref= createCheckboxPref(composite, numColumns, message, key, values); GridData data= (GridData) pref.getControl().getLayoutData(); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.java index ca0d05a689..160ba95772 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation * istvan@benedek-home.de - 103706 [formatter] indent empty lines @@ -162,6 +162,8 @@ private FormatterMessages() { public static String WhiteSpaceOptions_after; public static String WhiteSpaceOptions_operator; public static String WhiteSpaceOptions_assignment_operator; + public static String WhiteSpaceOptions_lambda_after_arrow_operator; + public static String WhiteSpaceOptions_lambda_before_arrow_operator; public static String WhiteSpaceOptions_binary_operator; public static String WhiteSpaceOptions_unary_operator; public static String WhiteSpaceOptions_prefix_operator; @@ -205,6 +207,7 @@ private FormatterMessages() { public static String WhiteSpaceOptions_array_element_access; public static String WhiteSpaceOptions_array_alloc; public static String WhiteSpaceOptions_array_init; + public static String WhiteSpaceOptions_arrow_operator; public static String WhiteSpaceOptions_arguments; public static String WhiteSpaceOptions_initialization; public static String WhiteSpaceOptions_incrementation; @@ -220,6 +223,7 @@ private FormatterMessages() { public static String WhiteSpaceOptions_conditional; public static String WhiteSpaceOptions_wildcard; public static String WhiteSpaceOptions_label; + public static String WhiteSpaceOptions_lambda; public static String WhiteSpaceOptions_comma; public static String WhiteSpaceOptions_semicolon; public static String WhiteSpaceOptions_question_mark; @@ -355,6 +359,7 @@ private FormatterMessages() { public static String BracesTabPage_option_enum_declaration; public static String BracesTabPage_option_enumconst_declaration; public static String BracesTabPage_option_annotation_type_declaration; + public static String BracesTabPage_option_lambda_body; public static String CodingStyleConfigurationBlock_preview_title; @@ -452,6 +457,7 @@ private FormatterMessages() { public static String NewLinesTabPage_annotations_group_paramters; public static String NewLinesTabPage_annotations_group_packages; public static String NewLinesTabPage_annotations_group_types; + public static String NewLinesTabPage_annotations_group_type_annotations; public static String NewLinesTabPage_annotations_group_fields; public static String NewLinesTabPage_annotations_group_methods; public static String NewLinesTabPage_annotations_group_title; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.properties index 3c2ed08a93..69e3a56f21 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/FormatterMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2011 IBM Corporation and others. +# Copyright (c) 2000, 2013 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -174,6 +174,8 @@ WhiteSpaceOptions_after=After WhiteSpaceOptions_operator=Operator WhiteSpaceOptions_assignment_operator=Assignment operator +WhiteSpaceOptions_lambda_after_arrow_operator=after arrow operator +WhiteSpaceOptions_lambda_before_arrow_operator=before arrow operator WhiteSpaceOptions_binary_operator=Binary operator WhiteSpaceOptions_unary_operator=Unary operator WhiteSpaceOptions_prefix_operator=Prefix operator @@ -223,6 +225,7 @@ WhiteSpaceOptions_array_decl=Array declaration WhiteSpaceOptions_array_element_access=Array element access WhiteSpaceOptions_array_alloc=Array allocation WhiteSpaceOptions_array_init=Array initializer +WhiteSpaceOptions_arrow_operator=Arrow operator WhiteSpaceOptions_arguments=Arguments WhiteSpaceOptions_initialization=Initialization @@ -242,6 +245,7 @@ WhiteSpaceOptions_colon=Colon WhiteSpaceOptions_conditional=Conditional WhiteSpaceOptions_wildcard=Wildcard type WhiteSpaceOptions_label=Label +WhiteSpaceOptions_lambda=Lambda WhiteSpaceOptions_comma=Comma WhiteSpaceOptions_semicolon=Semicolon @@ -383,7 +387,7 @@ BracesTabPage_position_next_line_indented=Next line indented BracesTabPage_position_next_line_on_wrap=Next line on wrap BracesTabPage_group_brace_positions_title=Brace positions -BracesTabPage_option_class_declaration=&Class or interface declaration: +BracesTabPage_option_class_declaration=Class or inter&face declaration: BracesTabPage_option_anonymous_class_declaration=Anon&ymous class declaration: BracesTabPage_option_method_declaration=Met&hod declaration: BracesTabPage_option_constructor_declaration=Constr&uctor declaration: @@ -393,8 +397,9 @@ BracesTabPage_option_switch_case='&switch' statement: BracesTabPage_option_array_initializer=Array initiali&zer: BracesTabPage_option_keep_empty_array_initializer_on_one_line=Keep empty array &initializer on one line BracesTabPage_option_enum_declaration=&Enum declaration: -BracesTabPage_option_enumconst_declaration=Enum c&onstant body: +BracesTabPage_option_enumconst_declaration=Enum &constant body: BracesTabPage_option_annotation_type_declaration=&Annotation type declaration: +BracesTabPage_option_lambda_body=Lambda b&ody: CodingStyleConfigurationBlock_preview_title=A sample source file for the code formatter preview CommentsTabPage_group1_title=General settings @@ -501,6 +506,7 @@ NewLinesTabPage_annotations_group_local_variables=Insert new line after annotati NewLinesTabPage_annotations_group_paramters=Insert new line after annotations on parameters NewLinesTabPage_annotations_group_packages=Insert new line after annotations on packages NewLinesTabPage_annotations_group_types=Insert new line after annotations on types +NewLinesTabPage_annotations_group_type_annotations=Insert new line after type annotations NewLinesTabPage_annotations_group_fields=Insert new line after annotations on fields NewLinesTabPage_annotations_group_methods=Insert new line after annotations on methods NewLinesTabPage_annotations_group_title=Ann&otations diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/NewLinesTabPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/NewLinesTabPage.java index 3467026ef4..b591d137a9 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/NewLinesTabPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/NewLinesTabPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -32,7 +32,7 @@ public class NewLinesTabPage extends FormatterTabPage { " Listener fListener= new Listener() {" + //$NON-NLS-1$ " };\n" + //$NON-NLS-1$ " @Deprecated @Override " + //$NON-NLS-1$ - " public void\nbar\n(@SuppressWarnings(\"unused\")\n int i)\n {\n@SuppressWarnings(\"unused\") int k;\n}\n" + //$NON-NLS-1$ + " public void\nbar\n(@SuppressWarnings(\"unused\")\n int i)\n {\n@SuppressWarnings(\"unused\") final @Positive int k;\n}\n" + //$NON-NLS-1$ " void foo() {" + //$NON-NLS-1$ " ;;" + //$NON-NLS-1$ " label:" + //$NON-NLS-1$ @@ -83,8 +83,9 @@ protected void doCreatePreferences(Composite composite, int numColumns) { createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_types, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_TYPE, DO_NOT_INSERT_INSERT); createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_fields, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_FIELD, DO_NOT_INSERT_INSERT); createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_methods, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_METHOD, DO_NOT_INSERT_INSERT); - createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_paramters, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_PARAMETER, DO_NOT_INSERT_INSERT); createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_local_variables, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_LOCAL_VARIABLE, DO_NOT_INSERT_INSERT); + createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_paramters, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_ANNOTATION_ON_PARAMETER, DO_NOT_INSERT_INSERT); + createPref(annotationsGroup, numColumns, FormatterMessages.NewLinesTabPage_annotations_group_type_annotations, DefaultCodeFormatterConstants.FORMATTER_INSERT_NEW_LINE_AFTER_TYPE_ANNOTATION, DO_NOT_INSERT_INSERT); } @Override diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java index 73ce3e974f..ddcd963a63 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/WhiteSpaceOptions.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -322,6 +322,10 @@ public void getCheckedLeafs(List list) { CodeFormatter.K_CLASS_BODY_DECLARATIONS, "Map, Y> t;" //$NON-NLS-1$ ); + + private final PreviewSnippet LAMBDA_EXPR_PREVIEW= new PreviewSnippet( + CodeFormatter.K_STATEMENTS, + "Runnable r = ()->process();"); //$NON-NLS-1$ /** * Create the tree, in this order: syntax element - position - abstract element @@ -539,6 +543,7 @@ public ArrayList createTreeByJavaElement(Map workingValues createAnnotationTree(workingValues, declarations); createEnumTree(workingValues, declarations); createAnnotationTypeTree(workingValues, declarations); + createLambdaTree(workingValues, declarations); final InnerNode statements= new InnerNode(null, workingValues, FormatterMessages.WhiteSpaceTabPage_statements); createOption(statements, workingValues, FormatterMessages.WhiteSpaceOptions_before_semicolon, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_SEMICOLON, SEMICOLON_PREVIEW); @@ -583,6 +588,13 @@ public ArrayList createTreeByJavaElement(Map workingValues return roots; } + private InnerNode createLambdaTree(Map workingValues, InnerNode parent) { + final InnerNode root= new InnerNode(parent, workingValues, FormatterMessages.WhiteSpaceOptions_lambda); + createOption(root, workingValues, FormatterMessages.WhiteSpaceOptions_lambda_before_arrow_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_LAMBDA_ARROW, LAMBDA_EXPR_PREVIEW); + createOption(root, workingValues, FormatterMessages.WhiteSpaceOptions_lambda_after_arrow_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_LAMBDA_ARROW, LAMBDA_EXPR_PREVIEW); + return root; + } + private void createBeforeQuestionTree(Map workingValues, final InnerNode parent) { createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_conditional, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_CONDITIONAL, CONDITIONAL_PREVIEW); createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_wildcard, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_QUESTION_IN_WILDCARD, WILDCARD_PREVIEW); @@ -656,6 +668,7 @@ private void createBeforeOperatorTree(Map workingValues, final I createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_binary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_BINARY_OPERATOR, OPERATOR_PREVIEW); createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_prefix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_PREFIX_OPERATOR, OPERATOR_PREVIEW); createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_postfix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_POSTFIX_OPERATOR, OPERATOR_PREVIEW); + createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_arrow_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_BEFORE_LAMBDA_ARROW, LAMBDA_EXPR_PREVIEW); } private void createBeforeClosingBracketTree(Map workingValues, final InnerNode parent) { @@ -832,6 +845,7 @@ private void createAfterOperatorTree(Map workingValues, final In createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_binary_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_BINARY_OPERATOR, OPERATOR_PREVIEW); createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_prefix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_PREFIX_OPERATOR, OPERATOR_PREVIEW); createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_postfix_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_POSTFIX_OPERATOR, OPERATOR_PREVIEW); + createOption(parent, workingValues, FormatterMessages.WhiteSpaceOptions_arrow_operator, DefaultCodeFormatterConstants.FORMATTER_INSERT_SPACE_AFTER_LAMBDA_ARROW, LAMBDA_EXPR_PREVIEW); } private void createAfterOpenBracketTree(Map workingValues, final InnerNode parent) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/ExceptionOccurrencesFinder.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/ExceptionOccurrencesFinder.java index b989651a60..cbc57b08ee 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/ExceptionOccurrencesFinder.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/ExceptionOccurrencesFinder.java @@ -1,10 +1,10 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html - * + * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ @@ -14,8 +14,6 @@ import java.util.Iterator; import java.util.List; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTMatcher; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; @@ -36,6 +34,7 @@ import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperMethodInvocation; +import org.eclipse.jdt.core.dom.TagElement; import org.eclipse.jdt.core.dom.ThrowStatement; import org.eclipse.jdt.core.dom.TryStatement; import org.eclipse.jdt.core.dom.Type; @@ -48,6 +47,7 @@ import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.util.Messages; +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; public class ExceptionOccurrencesFinder extends ASTVisitor implements IOccurrencesFinder { @@ -57,7 +57,7 @@ public class ExceptionOccurrencesFinder extends ASTVisitor implements IOccurrenc public static final String IS_EXCEPTION= "isException"; //$NON-NLS-1$ private CompilationUnit fASTRoot; - private Name fSelectedName; + private ASTNode fSelectedNode; private ITypeBinding fException; private ASTNode fStart; @@ -76,27 +76,55 @@ public String initialize(CompilationUnit root, int offset, int length) { public String initialize(CompilationUnit root, ASTNode node) { fASTRoot= root; - if (!(node instanceof Name)) { + if (node == null) return SearchMessages.ExceptionOccurrencesFinder_no_exception; + + MethodDeclaration method= ASTResolving.findParentMethodDeclaration(node); + if (method == null) + return SearchMessages.ExceptionOccurrencesFinder_no_exception; + + // The ExceptionOccurrencesFinder selects the whole type, no matter what part of it was selected. MethodExitsFinder behaves similar. + + if (node instanceof Name) { + node= ASTNodes.getTopMostName((Name) node); } - fSelectedName= ASTNodes.getTopMostName((Name)node); - ASTNode parent= fSelectedName.getParent(); - MethodDeclaration decl= resolveMethodDeclaration(parent); - if (decl != null && methodThrowsException(decl, fSelectedName)) { - fException= fSelectedName.resolveTypeBinding(); - fStart= decl.getBody(); - } else if (parent instanceof Type) { - parent= parent.getParent(); - if (parent instanceof UnionType) { - parent= parent.getParent(); + ASTNode parent= node.getParent(); + if (node.getLocationInParent() == TagElement.FRAGMENTS_PROPERTY) { + // in Javadoc tag: + TagElement tagElement= (TagElement) parent; + String tagName= tagElement.getTagName(); + if (node instanceof Name + && node == tagElement.fragments().get(0) + && (TagElement.TAG_EXCEPTION.equals(tagName) || TagElement.TAG_THROWS.equals(tagName))) { + fSelectedNode= node; + fException= ((Name) node).resolveTypeBinding(); + fStart= method; } - if (parent instanceof SingleVariableDeclaration && parent.getParent() instanceof CatchClause) { - CatchClause catchClause= (CatchClause)parent.getParent(); - fTryStatement= (TryStatement)catchClause.getParent(); - if (fTryStatement != null) { - fException= fSelectedName.resolveTypeBinding(); - fStart= fTryStatement.getBody(); - } + + } else { + Type type= ASTNodes.getTopMostType(node); + if (type == null) { + return SearchMessages.ExceptionOccurrencesFinder_no_exception; + } + + // in method's "throws" list: + if (type.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { + fSelectedNode= type; + fException= type.resolveBinding(); + fStart= method; + } + + // in catch clause: + Type topType= type; + if (type.getLocationInParent() == UnionType.TYPES_PROPERTY) { + topType= (Type) type.getParent(); + } + if (topType.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY + && topType.getParent().getLocationInParent() == CatchClause.EXCEPTION_PROPERTY) { + fSelectedNode= type; + fException= type.resolveBinding(); + fTryStatement= (TryStatement) topType.getParent().getParent().getParent(); + fStart= fTryStatement.getBody(); } } if (fException == null || fStart == null) @@ -105,67 +133,44 @@ public String initialize(CompilationUnit root, ASTNode node) { return null; } - private MethodDeclaration resolveMethodDeclaration(ASTNode node) { - if (node instanceof MethodDeclaration) - return (MethodDeclaration)node; - Javadoc doc= (Javadoc) ASTNodes.getParent(node, ASTNode.JAVADOC); - if (doc == null) - return null; - if (doc.getParent() instanceof MethodDeclaration) - return (MethodDeclaration) doc.getParent(); - return null; - } - - private boolean methodThrowsException(MethodDeclaration method, Name exception) { - ASTMatcher matcher = new ASTMatcher(); - for (Iterator iter = method.thrownExceptions().iterator(); iter.hasNext();) { - Name thrown = iter.next(); - if (exception.subtreeMatch(matcher, thrown)) - return true; - } - return false; - } - private void performSearch() { fCaughtExceptions= new ArrayList(); fStart.accept(this); if (fTryStatement != null) { handleResourceDeclarations(fTryStatement); } - if (fSelectedName != null) { - fResult.add(new OccurrenceLocation(fSelectedName.getStartPosition(), fSelectedName.getLength(), F_EXCEPTION_DECLARATION, fDescription)); + if (fSelectedNode != null) { + fResult.add(new OccurrenceLocation(fSelectedNode.getStartPosition(), fSelectedNode.getLength(), F_EXCEPTION_DECLARATION, fDescription)); } } private void handleResourceDeclarations(TryStatement tryStatement) { - if (tryStatement.getAST().apiLevel() >= AST.JLS4) { - List resources= tryStatement.resources(); - for (Iterator iterator= resources.iterator(); iterator.hasNext();) { - iterator.next().accept(this); - } + List resources= tryStatement.resources(); + for (Iterator iterator= resources.iterator(); iterator.hasNext();) { + iterator.next().accept(this); + } - //check if the exception is thrown as a result of resource#close() - boolean exitMarked= false; - for (VariableDeclarationExpression variable : resources) { - Type type= variable.getType(); - IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$ - if (methodBinding != null) { - ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes(); - for (int j= 0; j < exceptionTypes.length; j++) { - if (matches(exceptionTypes[j])) { // a close() throws the caught exception - // mark name of resource - for (VariableDeclarationFragment fragment : (List) variable.fragments()) { - SimpleName name= fragment.getName(); - fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription)); - } - if (!exitMarked) { - // mark exit position - exitMarked= true; - Block body= tryStatement.getBody(); - int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block - fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description, - BasicElementLabels.getJavaElementName(fException.getName())))); - } + //check if the exception is thrown as a result of resource#close() + boolean exitMarked= false; + for (VariableDeclarationExpression variable : resources) { + Type type= variable.getType(); + IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$ + if (methodBinding != null) { + ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes(); + for (int j= 0; j < exceptionTypes.length; j++) { + if (matches(exceptionTypes[j])) { // a close() throws the caught exception + // mark name of resource + for (VariableDeclarationFragment fragment : (List) variable.fragments()) { + SimpleName name= fragment.getName(); + fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription)); + } + if (!exitMarked) { + // mark exit position + exitMarked= true; + Block body= tryStatement.getBody(); + int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block + fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description, + BasicElementLabels.getJavaElementName(fException.getName())))); } } } @@ -195,8 +200,8 @@ public String getJobLabel() { } public String getElementName() { - if (fSelectedName != null) { - return ASTNodes.asString(fSelectedName); + if (fSelectedNode != null) { + return ASTNodes.asString(fSelectedNode); } return null; } @@ -241,6 +246,37 @@ public boolean visit(ConstructorInvocation node) { return super.visit(node); } + @Override + public boolean visit(MethodDeclaration node) { + Javadoc javadoc= node.getJavadoc(); + if (javadoc != null) { + List tags= javadoc.tags(); + for (TagElement tag : tags) { + String tagName= tag.getTagName(); + if (TagElement.TAG_EXCEPTION.equals(tagName) || TagElement.TAG_THROWS.equals(tagName)) { + ASTNode name= (ASTNode) tag.fragments().get(0); + if (name instanceof Name) { + if (name != fSelectedNode && Bindings.equals(fException, ((Name) name).resolveBinding())) { + fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription)); + } + } + } + } + } + List thrownExceptionTypes= node.thrownExceptionTypes(); + for (Iterator iter= thrownExceptionTypes.iterator(); iter.hasNext(); ) { + Type type = iter.next(); + if (type != fSelectedNode && Bindings.equals(fException, type.resolveBinding())) { + fResult.add(new OccurrenceLocation(type.getStartPosition(), type.getLength(), 0, fDescription)); + } + } + Block body= node.getBody(); + if (body != null) { + node.getBody().accept(this); + } + return false; + } + @Override public boolean visit(MethodInvocation node) { if (matches(node.resolveMethodBinding())) { @@ -249,7 +285,7 @@ public boolean visit(MethodInvocation node) { } return super.visit(node); } - + @Override public boolean visit(SuperConstructorInvocation node) { if (matches(node.resolveConstructorBinding())) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/MethodExitsFinder.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/MethodExitsFinder.java index 9208804968..77f71ac1ee 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/MethodExitsFinder.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/MethodExitsFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -14,7 +14,6 @@ import java.util.Iterator; import java.util.List; -import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; @@ -29,7 +28,6 @@ import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; @@ -52,6 +50,7 @@ import org.eclipse.jdt.internal.corext.refactoring.code.flow.InOutFlowAnalyzer; import org.eclipse.jdt.internal.corext.util.Messages; +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; @@ -78,26 +77,17 @@ public String initialize(CompilationUnit root, ASTNode node) { fASTRoot= root; if (node instanceof ReturnStatement) { - fMethodDeclaration= (MethodDeclaration)ASTNodes.getParent(node, ASTNode.METHOD_DECLARATION); + fMethodDeclaration= ASTResolving.findParentMethodDeclaration(node); if (fMethodDeclaration == null) return SearchMessages.MethodExitsFinder_no_return_type_selected; return null; } - Type type= null; - if (node instanceof Type) { - type= (Type)node; - } else if (node instanceof Name) { - Name name= ASTNodes.getTopMostName((Name)node); - if (name.getParent() instanceof Type) { - type= (Type)name.getParent(); - } - } + Type type= ASTNodes.getTopMostType(node); if (type == null) return SearchMessages.MethodExitsFinder_no_return_type_selected; - type= ASTNodes.getTopMostType(type); - if (!(type.getParent() instanceof MethodDeclaration)) + if (type.getLocationInParent() != MethodDeclaration.RETURN_TYPE2_PROPERTY) return SearchMessages.MethodExitsFinder_no_return_type_selected; fMethodDeclaration= (MethodDeclaration)type.getParent(); @@ -203,34 +193,32 @@ public boolean visit(TryStatement node) { } node.getBody().accept(this); - if (node.getAST().apiLevel() >= AST.JLS4) { - List resources= node.resources(); - for (Iterator iterator= resources.iterator(); iterator.hasNext();) { - iterator.next().accept(this); - } + List resources= node.resources(); + for (Iterator iterator= resources.iterator(); iterator.hasNext();) { + iterator.next().accept(this); + } - //check if the method could exit as a result of resource#close() - boolean exitMarked= false; - for (VariableDeclarationExpression variable : resources) { - Type type= variable.getType(); - IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$ - if (methodBinding != null) { - ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes(); - for (int j= 0; j < exceptionTypes.length; j++) { - if (isExitPoint(exceptionTypes[j])) { // a close() throws an uncaught exception - // mark name of resource - for (VariableDeclarationFragment fragment : (List) variable.fragments()) { - SimpleName name= fragment.getName(); - fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fExitDescription)); - } - if (!exitMarked) { - // mark exit position - exitMarked= true; - Block body= node.getBody(); - int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block - fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.MethodExitsFinder_occurrence_exit_impclict_close_description, - BasicElementLabels.getJavaElementName(fMethodDeclaration.getName().toString())))); - } + //check if the method could exit as a result of resource#close() + boolean exitMarked= false; + for (VariableDeclarationExpression variable : resources) { + Type type= variable.getType(); + IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$ + if (methodBinding != null) { + ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes(); + for (int j= 0; j < exceptionTypes.length; j++) { + if (isExitPoint(exceptionTypes[j])) { // a close() throws an uncaught exception + // mark name of resource + for (VariableDeclarationFragment fragment : (List) variable.fragments()) { + SimpleName name= fragment.getName(); + fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fExitDescription)); + } + if (!exitMarked) { + // mark exit position + exitMarked= true; + Block body= node.getBody(); + int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block + fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.MethodExitsFinder_occurrence_exit_impclict_close_description, + BasicElementLabels.getJavaElementName(fMethodDeclaration.getName().toString())))); } } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesFinder.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesFinder.java index 0e2e520a9a..74d07a5cac 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesFinder.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/OccurrencesFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,6 +31,7 @@ import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NodeFinder; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.PostfixExpression; @@ -187,6 +188,9 @@ public boolean visit(ClassInstanceCreation node) { if (name instanceof QualifiedName) name= ((QualifiedName)name).getName(); addUsage(name, node.resolveConstructorBinding()); + } else if (type instanceof NameQualifiedType) { + Name name= ((NameQualifiedType) type).getName(); + addUsage(name, node.resolveConstructorBinding()); } return super.visit(node); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaHeuristicScanner.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaHeuristicScanner.java index f4084a7f84..92beca5736 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaHeuristicScanner.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaHeuristicScanner.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -333,6 +333,8 @@ public int nextToken(int start, int bound) { return TokenRPAREN; case SEMICOLON: return TokenSEMICOLON; + case COLON: + return TokenCOLON; case COMMA: return TokenCOMMA; case QUESTIONMARK: diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java index ccfa462f98..369ed2cff1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java @@ -765,8 +765,14 @@ public int findReferencePosition(int offset, int nextToken) { case Symbols.TokenELSE: danglingElse= true; break; - case Symbols.TokenCASE: case Symbols.TokenDEFAULT: + fScanner.nextToken(offset, lineOffset + line.getLength()); + int next= fScanner.nextToken(fScanner.getPosition(), JavaHeuristicScanner.UNBOUND); + if (next != Symbols.TokenCOLON) { + break; + } + //$FALL-THROUGH$ + case Symbols.TokenCASE: if (isFirstTokenOnLine) matchCase= true; break; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaWordFinder.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaWordFinder.java index a30a993955..ea524c22ad 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaWordFinder.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaWordFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -76,12 +76,36 @@ public static IRegion findWord(IDocument document, int offset) { } if (start >= -1 && end > -1) { - if (start == offset && end == offset) + if (start == offset && end == offset) { + try { + char c= document.getChar(offset); + switch (c) { + case '-': + if (document.getChar(offset + 1) == '>') { + return new Region(offset, 2); + } + break; + case '>': + if (document.getChar(offset - 1) == '-') { + return new Region(offset - 1, 2); + } + break; + case ':': + if (document.getChar(offset + 1) == ':') { + return new Region(offset, 2); + } else if (document.getChar(offset - 1) == ':') { + return new Region(offset - 1, 2); + } + break; + } + } catch (BadLocationException e) { + } return new Region(offset, 0); - else if (start == offset) - return new Region(start, end - start); - else + } else if (start == offset) { + return new Region(start, end - start); //XXX: probably unused... + } else { return new Region(start + 1, end - start - 1); + } } return null; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java index db17f5869c..af80c9d62d 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -49,11 +49,13 @@ import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.InstanceofExpression; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.PrefixExpression; import org.eclipse.jdt.core.dom.PrimitiveType; @@ -229,12 +231,11 @@ private static ITypeBinding getPossibleReferenceBinding(ASTNode node) { return getReducedDimensionBinding(annotMember.getReturnType(), dim); } } - if (creationType != null) { - while ((creationType instanceof ArrayType) && dim > 0) { - creationType= ((ArrayType) creationType).getComponentType(); - dim--; + if (creationType instanceof ArrayType) { + ITypeBinding creationTypeBinding= ((ArrayType) creationType).resolveBinding(); + if (creationTypeBinding != null) { + return Bindings.getComponentType(creationTypeBinding, dim); } - return creationType.resolveBinding(); } break; case ASTNode.CONDITIONAL_EXPRESSION: @@ -270,6 +271,13 @@ private static ITypeBinding getPossibleReferenceBinding(ASTNode node) { if (decl != null && !decl.isConstructor()) { return decl.getReturnType2().resolveBinding(); } + LambdaExpression lambdaExpr= ASTResolving.findEnclosingLambdaExpression(parent); + if (lambdaExpr != null) { + IMethodBinding lambdaMethodBinding= lambdaExpr.resolveMethodBinding(); + if (lambdaMethodBinding != null && lambdaMethodBinding.getReturnType() != null) { + return lambdaMethodBinding.getReturnType(); + } + } break; case ASTNode.CAST_EXPRESSION: return ((CastExpression) parent).getType().resolveBinding(); @@ -346,7 +354,7 @@ public static Type guessTypeForReference(AST ast, ASTNode node) { if (!((ArrayAccess) parent).getIndex().equals(node)) { Type type= guessTypeForReference(ast, parent); if (type != null) { - return ast.newArrayType(type); + return ASTNodeFactory.newArrayType(type); } } return null; @@ -403,7 +411,8 @@ public static ITypeBinding guessBindingForTypeReference(ASTNode node) { if (locationInParent == QualifiedName.QUALIFIER_PROPERTY) { return null; // can't guess type for X.A } - if (locationInParent == SimpleType.NAME_PROPERTY) { + if (locationInParent == SimpleType.NAME_PROPERTY || + locationInParent == NameQualifiedType.NAME_PROPERTY) { node= node.getParent(); } ITypeBinding binding= Bindings.normalizeTypeBinding(getPossibleTypeBinding(node)); @@ -419,11 +428,7 @@ private static ITypeBinding getPossibleTypeBinding(ASTNode node) { ASTNode parent= node.getParent(); switch (parent.getNodeType()) { case ASTNode.ARRAY_TYPE: { - int dim= 1; - while (parent.getParent() instanceof ArrayType) { - parent= parent.getParent(); - dim++; - } + int dim= ((ArrayType) parent).getDimensions(); ITypeBinding parentBinding= getPossibleTypeBinding(parent); if (parentBinding != null && parentBinding.getDimensions() == dim) { return parentBinding.getElementType(); @@ -468,6 +473,16 @@ private static ITypeBinding getPossibleTypeBinding(ASTNode node) { } return parentBinding; } + case ASTNode.NAME_QUALIFIED_TYPE: { + ITypeBinding parentBinding= getPossibleTypeBinding(parent); + if (parentBinding == null || !parentBinding.isMember()) { + return null; + } + if (node.getLocationInParent() == NameQualifiedType.QUALIFIER_PROPERTY) { + return parentBinding.getDeclaringClass(); + } + return parentBinding; + } case ASTNode.VARIABLE_DECLARATION_STATEMENT: return guessVariableType(((VariableDeclarationStatement) parent).fragments()); case ASTNode.FIELD_DECLARATION: @@ -497,9 +512,9 @@ private static ITypeBinding getPossibleTypeBinding(ASTNode node) { if (TagElement.TAG_THROWS.equals(tagElement.getTagName()) || TagElement.TAG_EXCEPTION.equals(tagElement.getTagName())) { ASTNode methNode= tagElement.getParent().getParent(); if (methNode instanceof MethodDeclaration) { - List thrownExceptions= ((MethodDeclaration) methNode).thrownExceptions(); + List thrownExceptions= ((MethodDeclaration) methNode).thrownExceptionTypes(); if (thrownExceptions.size() == 1) { - return thrownExceptions.get(0).resolveTypeBinding(); + return thrownExceptions.get(0).resolveBinding(); } } } @@ -576,6 +591,7 @@ public static void visitAllBindings(ASTNode astRoot, TypeBindingVisitor visitor) try { astRoot.accept(new AllBindingsVisitor(visitor)); } catch (AllBindingsVisitor.VisitCancelledException e) { + // visit cancelled } } @@ -651,11 +667,14 @@ public static CompilationUnit findParentCompilationUnit(ASTNode node) { } /** - * Finds the parent type of a node. + * Finds the ancestor type of node (includes node in the search). * - * @param node the node inside the type to find - * @param treatModifiersOutside if set, modifiers are not part of their type, but of the type's parent - * @return returns either a AbstractTypeDeclaration or an AnonymousTypeDeclaration + * @param node the node to start the search from, can be null + * @param treatModifiersOutside if set, modifiers are not part of their type, but of the type's + * parent + * @return returns the ancestor type of node (AbstractTypeDeclaration or + * AnonymousTypeDeclaration) if any (including node), null + * otherwise */ public static ASTNode findParentType(ASTNode node, boolean treatModifiersOutside) { StructuralPropertyDescriptor lastLocation= null; @@ -675,24 +694,54 @@ public static ASTNode findParentType(ASTNode node, boolean treatModifiersOutside return null; } + /** + * Finds the ancestor type of node (includes node in the search). + * + * @param node the node to start the search from, can be null + * @return returns the ancestor type of node (AbstractTypeDeclaration or + * AnonymousTypeDeclaration) if any (including node), null + * otherwise + */ public static ASTNode findParentType(ASTNode node) { return findParentType(node, false); } /** - * Returns the method binding of the node's parent method declaration or null if - * the node is not inside a method. + * The node's enclosing method declaration or null if + * the node is not inside a method and is not a method declaration itself. * - * @param node the ast node - * @return the method binding of the node's parent method declaration or null if - * the node + * @param node a node + * @return the enclosing method declaration or null */ public static MethodDeclaration findParentMethodDeclaration(ASTNode node) { while (node != null) { - if (node.getNodeType() == ASTNode.METHOD_DECLARATION) { + if (node instanceof MethodDeclaration) { return (MethodDeclaration) node; + } else if (node instanceof BodyDeclaration || node instanceof AnonymousClassDeclaration || node instanceof LambdaExpression) { + return null; + } + node= node.getParent(); + } + return null; + } + + /** + * Returns the lambda expression node which encloses the given node, or + * null if none. + * + * @param node the node + * @return the enclosing lambda expression node for the given node, or + * null if none + * + * @since 3.10 + */ + public static LambdaExpression findEnclosingLambdaExpression(ASTNode node) { + node= node.getParent(); + while (node != null) { + if (node instanceof LambdaExpression) { + return (LambdaExpression) node; } - if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) { + if (node instanceof BodyDeclaration || node instanceof AnonymousClassDeclaration) { return null; } node= node.getParent(); @@ -700,6 +749,19 @@ public static MethodDeclaration findParentMethodDeclaration(ASTNode node) { return null; } + /** + * Returns the closest ancestor of node (including node itself) + * whose type is nodeType, or null if none. + *

    + * Warning: This method does not stop at any boundaries like parentheses, statements, body declarations, etc. + * The resulting node may be in a totally different scope than the given node. + * Consider using one of the other {@link ASTResolving}.find(..) methods instead. + *

    + * @param node the node + * @param nodeType the node type constant from {@link ASTNode} + * @return the closest ancestor of node (including node itself) + * whose type is nodeType, or null if none + */ public static ASTNode findAncestor(ASTNode node, int nodeType) { while ((node != null) && (node.getNodeType() != nodeType)) { node= node.getParent(); @@ -828,6 +890,11 @@ private static int internalGetPossibleTypeKinds(ASTNode node) { return mask & (SimilarElementsRequestor.REF_TYPES); } mask&= SimilarElementsRequestor.REF_TYPES; + } else if (parent instanceof NameQualifiedType) { + if (node.getLocationInParent() == NameQualifiedType.QUALIFIER_PROPERTY) { + return mask & (SimilarElementsRequestor.REF_TYPES); + } + mask&= SimilarElementsRequestor.REF_TYPES; } else if (parent instanceof ParameterizedType) { if (node.getLocationInParent() == ParameterizedType.TYPE_ARGUMENTS_PROPERTY) { return mask & SimilarElementsRequestor.REF_TYPES_AND_VAR; @@ -854,7 +921,7 @@ private static int internalGetPossibleTypeKinds(ASTNode node) { kind= SimilarElementsRequestor.INTERFACES; break; case ASTNode.METHOD_DECLARATION: - if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY) { + if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { kind= SimilarElementsRequestor.CLASSES; } else if (node.getLocationInParent() == MethodDeclaration.RETURN_TYPE2_PROPERTY) { kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE; @@ -1085,15 +1152,23 @@ public static boolean isUseableTypeInContext(ITypeBinding type, IBinding context * Use this method before creating a type for a wildcard. Either to assign a wildcard to a new type or for a type to be assigned. * * @param wildcardType the wildcard type to normalize - * @param isBindingToAssign If true, then a new receiver type is searched (X x= s), else the type of a sender (R r= x) - * @param ast th current AST - * @return Returns the normalized binding or null when only the 'null' binding + * @param isBindingToAssign if true, then the type X for new variable x is returned (X x= s); + * if false, the type of an expression x (R r= x) + * @param ast the current AST + * @return the normalized binding or null when only the 'null' binding + * + * @see Bindings#normalizeForDeclarationUse(ITypeBinding, AST) */ public static ITypeBinding normalizeWildcardType(ITypeBinding wildcardType, boolean isBindingToAssign, AST ast) { ITypeBinding bound= wildcardType.getBound(); if (isBindingToAssign) { if (bound == null || !wildcardType.isUpperbound()) { - return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ + ITypeBinding[] typeBounds= wildcardType.getTypeBounds(); + if (typeBounds.length > 0) { + return typeBounds[0]; + } else { + return wildcardType.getErasure(); + } } } else { if (bound == null || wildcardType.isUpperbound()) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java index f2e2d29b23..bc26d719c0 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -59,6 +59,7 @@ import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.InfixExpression.Operator; import org.eclipse.jdt.core.dom.InstanceofExpression; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; @@ -217,15 +218,28 @@ private static boolean getConvertToIfReturnProposals(IInvocationContext context, if (ifStatement.getElseStatement() != null) { return false; } - MethodDeclaration coveringMetod= ASTResolving.findParentMethodDeclaration(ifStatement); - if (coveringMetod == null) { - return false; - } - // method should return 'void' - Type returnType= coveringMetod.getReturnType2(); - if (!isVoid(returnType)) { - return false; + + // enclosing lambda or method should return 'void' + LambdaExpression enclosingLambda= ASTResolving.findEnclosingLambdaExpression(ifStatement); + if (enclosingLambda != null) { + IMethodBinding lambdaMethodBinding= enclosingLambda.resolveMethodBinding(); + if (lambdaMethodBinding == null) { + return false; + } + if (!(ifStatement.getAST().resolveWellKnownType("void").equals(lambdaMethodBinding.getReturnType()))) { //$NON-NLS-1$ + return false; + } + } else { + MethodDeclaration coveringMethod= ASTResolving.findParentMethodDeclaration(ifStatement); + if (coveringMethod == null) { + return false; + } + Type returnType= coveringMethod.getReturnType2(); + if (!isVoid(returnType)) { + return false; + } } + // should be present in a block if (!(ifStatement.getParent() instanceof Block)) { return false; @@ -242,7 +256,7 @@ private static boolean getConvertToIfReturnProposals(IInvocationContext context, } } // should have no further executable statement - if (!isLastExecutableStatementInMethod(ifStatement)) { + if (!isLastStatementInEnclosingMethodOrLambda(ifStatement)) { return false; } // we could produce quick assist @@ -283,10 +297,10 @@ private static boolean isVoid(Type type) { return type instanceof PrimitiveType && ((PrimitiveType) type).getPrimitiveTypeCode() == PrimitiveType.VOID; } - private static boolean isLastExecutableStatementInMethod(Statement statement) { + private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) { ASTNode currentStructure= statement; ASTNode currentParent= statement.getParent(); - while (!(currentParent instanceof MethodDeclaration)) { + while (!(currentParent instanceof MethodDeclaration || currentParent instanceof LambdaExpression)) { // should not be in a loop if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement || currentParent instanceof WhileStatement || currentParent instanceof DoStatement) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java index 660c0cf0f4..1285960bda 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -257,6 +257,8 @@ private CorrectionMessages() { public static String AssignToVariableAssistProposal_assigntofield_description; public static String AssignToVariableAssistProposal_assignparamtofield_description; public static String QuickAssistProcessor_catchclausetothrows_description; + public static String QuickAssistProcessor_change_lambda_body_to_block; + public static String QuickAssistProcessor_change_lambda_body_to_expression; public static String QuickAssistProcessor_removecatchclause_description; public static String QuickAssistProcessor_removeexception_description; public static String QuickAssistProcessor_unwrap_ifstatement; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties index abf6df07dd..4f0f4c0781 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2013 IBM Corporation and others. +# Copyright (c) 2000, 2014 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -153,12 +153,12 @@ ModifierCorrectionSubProcessor_removeabstract_description=Remove 'abstract' modi ModifierCorrectionSubProcessor_removevolatile_description=Remove 'volatile' modifier ModifierCorrectionSubProcessor_removebody_description=Remove method body ModifierCorrectionSubProcessor_remove_override=Remove '@Override' annotation -ModifierCorrectionSubProcessor_default=default +ModifierCorrectionSubProcessor_default=package ModifierCorrectionSubProcessor_addabstract_description=Make type ''{0}'' abstract SuppressWarningsSubProcessor_suppress_warnings_label=Add @SuppressWarnings ''{0}'' to ''{1}'' ModifierCorrectionSubProcessor_removenative_description=Remove 'native' modifier ModifierCorrectionSubProcessor_removefinal_description=Remove 'final' modifier -ModifierCorrectionSubProcessor_default_visibility_label=(default) +ModifierCorrectionSubProcessor_default_visibility_label=(package) ModifierCorrectionSubProcessor_addmissingbody_description=Add body ModifierCorrectionSubProcessor_setmethodabstract_description=Add 'abstract' modifier GetterSetterCorrectionSubProcessor_additional_info=Starts the 'Encapsulate field' refactoring to create getter and setters @@ -305,6 +305,8 @@ AssignToVariableAssistProposal_assignparamtofield_description=Assign parameter t AssignToVariableAssistProposal_assigntoexistingfield_description=Assign parameter to field ''{0}'' QuickAssistProcessor_catchclausetothrows_description=Replace catch clause with throws +QuickAssistProcessor_change_lambda_body_to_block=Change body expression to block +QuickAssistProcessor_change_lambda_body_to_expression=Change body block to expression QuickAssistProcessor_removecatchclause_description=Remove catch clause QuickAssistProcessor_removeexception_description=Remove exception QuickAssistProcessor_name_extension_from_interface={0}Extension diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java index 3b32c967f2..d2450e3aee 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2013 IBM Corporation and others. + * Copyright (c) 2012, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -15,6 +15,7 @@ /** * Interface defining relevance values for quick fixes/assists. * + * @see org.eclipse.jdt.ui.text.java.IJavaCompletionProposal#getRelevance() * @since 3.9 */ public interface IProposalRelevance { @@ -84,6 +85,8 @@ public interface IProposalRelevance { public static final int INSERT_INFERRED_TYPE_ARGUMENTS= 7; public static final int RETURN_ALLOCATED_OBJECT_MATCH= 7; public static final int CREATE_LOCAL= 7; + public static final int CHANGE_LAMBDA_BODY_TO_BLOCK= 7; + public static final int CHANGE_LAMBDA_BODY_TO_EXPRESSION= 7; public static final int REMOVE_SEMICOLON= 6; public static final int CREATE_METHOD_IN_SUPER= 6; @@ -119,6 +122,8 @@ public interface IProposalRelevance { public static final int EXTRACT_LOCAL_ALL= 6; public static final int CHANGE_TO_ATTRIBUTE_SIMILAR_NAME= 6; public static final int CREATE_FIELD= 6; + public static final int CONVERT_TO_ANONYMOUS_CLASS_CREATION= 6; + public static final int CONVERT_TO_LAMBDA_EXPRESSION= 6; public static final int ADD_ALL_MISSING_TAGS= 5; public static final int QUALIFY_INNER_TYPE_NAME= 5; @@ -208,6 +213,7 @@ public interface IProposalRelevance { public static final int EXTRACT_LOCAL_ERROR= 2; public static final int ASSIGN_TO_FIELD= 2; public static final int RETURN_ALLOCATED_OBJECT= 2; + public static final int REMOVE_BLOCK_FIX= 2; public static final int JOIN_VARIABLE_DECLARATION= 1; public static final int INVERT_EQUALS= 1; @@ -263,7 +269,6 @@ public interface IProposalRelevance { public static final int CONVERT_TO_MESSAGE_FORMAT= 0; public static final int COPY_ANNOTATION_JAR= 0; public static final int ADD_ANNOTATION_BUNDLE= 0; - public static final int REMOVE_BLOCK_FIX= 0; public static final int NO_SUGGESSTIONS_AVAILABLE= 0; public static final int ADD_QUOTE= 0; public static final int NEW_TYPE= 0; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java index 77c70e8ad0..a9d70bcc38 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavadocTagsSubProcessor.java @@ -193,13 +193,13 @@ private void insertMissingJavadocTag(ASTRewrite rewrite, ASTNode missingNode, Bo newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_RETURN); insertTag(tagsRewriter, newTag, null); - } else if (location == MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY) { + } else if (location == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_THROWS); TextElement excNode= ast.newTextElement(); - excNode.setText(ASTNodes.asString(missingNode)); + excNode.setText(ASTNodes.getQualifiedTypeName((Type) missingNode)); newTag.fragments().add(excNode); - List exceptions= ((MethodDeclaration) bodyDecl).thrownExceptions(); + List exceptions= ((MethodDeclaration) bodyDecl).thrownExceptionTypes(); insertTag(tagsRewriter, newTag, getPreviousExceptionNames(exceptions, missingNode)); } else { Assert.isTrue(false, "AddMissingJavadocTagProposal: unexpected node location"); //$NON-NLS-1$ @@ -291,17 +291,17 @@ private void insertAllMissingMethodTags(ASTRewrite rewriter, MethodDeclaration m } } } - List thrownExceptions= methodDecl.thrownExceptions(); + List thrownExceptions= methodDecl.thrownExceptionTypes(); for (int i= thrownExceptions.size() - 1; i >= 0 ; i--) { - Name exception= thrownExceptions.get(i); - ITypeBinding binding= exception.resolveTypeBinding(); + Type exception= thrownExceptions.get(i); + ITypeBinding binding= exception.resolveBinding(); if (binding != null) { String name= binding.getName(); if (findThrowsTag(javadoc, name) == null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_THROWS); TextElement excNode= ast.newTextElement(); - excNode.setText(ASTNodes.asString(exception)); + excNode.setText(ASTNodes.getQualifiedTypeName(exception)); newTag.fragments().add(excNode); insertTabStop(rewriter, newTag.fragments(), "exception" + i); //$NON-NLS-1$ insertTag(tagsRewriter, newTag, getPreviousExceptionNames(thrownExceptions, exception)); @@ -371,7 +371,7 @@ public static void getMissingJavadocTagProposals(IInvocationContext context, IPr } } else if (location == MethodDeclaration.RETURN_TYPE2_PROPERTY) { label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_returntag_description; - } else if (location == MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY) { + } else if (location == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { label= CorrectionMessages.JavadocTagsSubProcessor_addjavadoc_throwstag_description; } else { return; @@ -417,6 +417,7 @@ public static void getUnusedAndUndocumentedParameterOrExceptionProposals(IInvoca } else if (isUnusedParam) { label= CorrectionMessages.JavadocTagsSubProcessor_document_parameter_description; } else { + node= ASTNodes.getNormalizedNode(node); label= CorrectionMessages.JavadocTagsSubProcessor_document_exception_description; } ASTRewriteCorrectionProposal proposal= new AddMissingJavadocTagProposal(label, context.getCompilationUnit(), bodyDecl, node, IProposalRelevance.DOCUMENT_UNUSED_ITEM); @@ -514,11 +515,11 @@ private static Set getPreviousParamNames(List return previousNames; } - private static Set getPreviousExceptionNames(List list, ASTNode missingNode) { + private static Set getPreviousExceptionNames(List list, ASTNode missingNode) { Set previousNames= new HashSet(); for (int i= 0; i < list.size() && missingNode != list.get(i); i++) { - Name curr= list.get(i); - previousNames.add(ASTNodes.getSimpleNameIdentifier(curr)); + Type curr= list.get(i); + previousNames.add(ASTNodes.getTypeName(curr)); } return previousNames; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java index 68eb7d9e76..b2309fd8e1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -79,6 +79,7 @@ import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PrefixExpression; @@ -410,12 +411,12 @@ public static void addUncaughtExceptionProposals(IInvocationContext context, IPr } uncaughtExceptions= unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]); - List exceptions= methodDecl.thrownExceptions(); + List exceptions= methodDecl.thrownExceptionTypes(); int nExistingExceptions= exceptions.size(); ChangeDescription[] desc= new ChangeDescription[nExistingExceptions + uncaughtExceptions.length]; for (int i= 0; i < exceptions.size(); i++) { - Name elem= exceptions.get(i); - if (isSubtype(elem.resolveTypeBinding(), uncaughtExceptions)) { + Type elem= exceptions.get(i); + if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) { desc[i]= new RemoveDescription(); } } @@ -766,13 +767,14 @@ public static void addUnnecessaryInstanceofProposal(IInvocationContext context, public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode == null || !(selectedNode.getParent() instanceof MethodDeclaration)) { + selectedNode= ASTNodes.getNormalizedNode(selectedNode); + if (selectedNode == null || selectedNode.getLocationInParent() != MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { return; } MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent(); IMethodBinding binding= decl.resolveBinding(); if (binding != null) { - List thrownExceptions= decl.thrownExceptions(); + List thrownExceptions= decl.thrownExceptionTypes(); int index= thrownExceptions.indexOf(selectedNode); if (index == -1) { return; @@ -1452,10 +1454,14 @@ private static void addTypeArgumentsFromContext(IInvocationContext context, IPro Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); + } else if (selectedNode instanceof NameQualifiedType) { + node= ((NameQualifiedType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); + } else if (elementType.isNameQualifiedType()) { + node= ((NameQualifiedType) elementType).getName(); } else { return; } @@ -1479,7 +1485,7 @@ private static void addTypeArgumentsFromContext(IInvocationContext context, IPro simpleBinding= simpleBinding.getTypeDeclaration(); if (!simpleBinding.isRecovered()) { - if (binding.isParameterizedType() && node.getParent() instanceof SimpleType && !(node.getParent().getParent() instanceof Type)) { + if (binding.isParameterizedType() && (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType) && !(node.getParent().getParent() instanceof Type)) { proposals.add(UnresolvedElementsSubProcessor.createTypeRefChangeFullProposal(cu, binding, node, IProposalRelevance.TYPE_ARGUMENTS_FROM_CONTEXT)); } } @@ -1599,8 +1605,9 @@ public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext cont method.setExpression(ast.newName(qfn)); method.setName(ast.newSimpleName(methodName[1])); ASTNode parent= selectedNode.getParent(); - // add explicit type arguments if necessary: - if (Invocations.isInvocationWithArguments(parent)) { + ICompilationUnit cu= context.getCompilationUnit(); + // add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works): + if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is18OrHigher(cu.getJavaProject())) { IMethodBinding methodBinding= Invocations.resolveBinding(parent); if (methodBinding != null) { ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); @@ -1609,10 +1616,13 @@ public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext cont ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments(); for (int j= 0; j < typeArguments.length; j++) { ITypeBinding typeArgument= typeArguments[j]; + typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); if (! TypeRules.isJavaLangObject(typeArgument)) { + // add all type arguments if at least one is found to be necessary: List typeArgumentsList= method.typeArguments(); for (int k= 0; k < typeArguments.length; k++) { typeArgument= typeArguments[k]; + typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); typeArgumentsList.add(importRewrite.addImport(typeArgument, ast)); } break; @@ -1626,7 +1636,7 @@ public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext cont String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, BasicElementLabels.getJavaElementName(ASTNodes.asString(method))); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image); + ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image); proposal.setImportRewrite(importRewrite); proposals.add(proposal); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java index a2a7eb12fd..10baf78ea4 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,6 +55,7 @@ import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; @@ -93,7 +94,6 @@ import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.fix.Java50CleanUp; import org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposal; -import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.ModifierChangeCorrectionProposal; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; @@ -127,6 +127,9 @@ public static void addNonAccessibleReferenceProposal(IInvocationContext context, case ASTNode.SIMPLE_TYPE: binding= ((SimpleType) selectedNode).resolveBinding(); break; + case ASTNode.NAME_QUALIFIED_TYPE: + binding= ((NameQualifiedType) selectedNode).resolveBinding(); + break; case ASTNode.METHOD_INVOCATION: binding= ((MethodInvocation) selectedNode).getName().resolveBinding(); break; @@ -193,6 +196,9 @@ public static void addNonAccessibleReferenceProposal(IInvocationContext context, case TO_STATIC: label= Messages.format(CorrectionMessages.ModifierCorrectionSubProcessor_changemodifiertostatic_description, name); includedModifiers= Modifier.STATIC; + if (bindingDecl.getKind() == IBinding.METHOD) { + excludedModifiers= Modifier.DEFAULT | Modifier.ABSTRACT; + } break; case TO_NON_STATIC: if (typeBinding != null && typeBinding.isInterface()) @@ -718,16 +724,13 @@ public static void addMethodRequiresBodyProposals(IInvocationContext context, IP proposals.add(proposal); } - if (modifierNode == null) { - ASTRewrite rewrite= ASTRewrite.create(ast); - - Modifier newModifier= ast.newModifier(Modifier.ModifierKeyword.ABSTRACT_KEYWORD); - rewrite.getListRewrite(decl, MethodDeclaration.MODIFIERS2_PROPERTY).insertLast(newModifier, null); - + IMethodBinding binding= decl.resolveBinding(); + if (modifierNode == null && binding != null) { String label= CorrectionMessages.ModifierCorrectionSubProcessor_setmethodabstract_description; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ABSTRACT_MODIFIER, image); - proposal.addLinkedPosition(rewrite.track(newModifier), true, "modifier"); //$NON-NLS-1$ + int included= Modifier.ABSTRACT; + int excluded= Modifier.STATIC | Modifier.DEFAULT; + ModifierChangeCorrectionProposal proposal= new ModifierChangeCorrectionProposal(label, cu, binding, decl, included, excluded, IProposalRelevance.ADD_ABSTRACT_MODIFIER, image); proposals.add(proposal); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java index fd7d42ae2f..c3a7be2104 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java @@ -76,21 +76,27 @@ import org.eclipse.jdt.core.dom.InfixExpression; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.LabeledStatement; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NumberLiteral; import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PostfixExpression; +import org.eclipse.jdt.core.dom.PrefixExpression; +import org.eclipse.jdt.core.dom.PrefixExpression.Operator; import org.eclipse.jdt.core.dom.PrimitiveType; +import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; +import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.SynchronizedStatement; @@ -114,6 +120,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; import org.eclipse.jdt.internal.corext.dom.Selection; @@ -123,6 +130,7 @@ import org.eclipse.jdt.internal.corext.fix.ControlStatementsFix; import org.eclipse.jdt.internal.corext.fix.ConvertLoopFix; import org.eclipse.jdt.internal.corext.fix.IProposableFix; +import org.eclipse.jdt.internal.corext.fix.LambdaExpressionsFix; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModel; import org.eclipse.jdt.internal.corext.fix.VariableDeclarationFix; import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester; @@ -150,6 +158,8 @@ import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.fix.ControlStatementsCleanUp; import org.eclipse.jdt.internal.ui.fix.ConvertLoopCleanUp; +import org.eclipse.jdt.internal.ui.fix.ExpressionsCleanUp; +import org.eclipse.jdt.internal.ui.fix.LambdaExpressionsCleanUp; import org.eclipse.jdt.internal.ui.fix.VariableDeclarationCleanUp; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.correction.proposals.AssignToVariableAssistProposal; @@ -217,6 +227,10 @@ public boolean hasAssists(IInvocationContext context) throws CoreException { || getInlineLocalProposal(context, coveringNode, null) || getConvertLocalToFieldProposal(context, coveringNode, null) || getConvertAnonymousToNestedProposal(context, coveringNode, null) + || getConvertAnonymousClassCreationsToLambdaProposals(context, coveringNode, null) + || getConvertLambdaToAnonymousClassCreationsProposals(context, coveringNode, null) + || getChangeLambdaBodyToBlockProposal(context, coveringNode, null) + || getChangeLambdaBodyToExpressionProposal(context, coveringNode, null) || getRemoveBlockProposals(context, coveringNode, null) || getMakeVariableDeclarationFinalProposals(context, null) || getMissingCaseStatementProposals(context, coveringNode, null) @@ -261,6 +275,10 @@ public IJavaCompletionProposal[] getAssists(IInvocationContext context, IProblem getInlineLocalProposal(context, coveringNode, resultingCollections); getConvertLocalToFieldProposal(context, coveringNode, resultingCollections); getConvertAnonymousToNestedProposal(context, coveringNode, resultingCollections); + getConvertAnonymousClassCreationsToLambdaProposals(context, coveringNode, resultingCollections); + getConvertLambdaToAnonymousClassCreationsProposals(context, coveringNode, resultingCollections); + getChangeLambdaBodyToBlockProposal(context, coveringNode, resultingCollections); + getChangeLambdaBodyToExpressionProposal(context, coveringNode, resultingCollections); if (!getConvertForLoopProposal(context, coveringNode, resultingCollections)) getConvertIterableLoopProposal(context, coveringNode, resultingCollections); getConvertEnhancedForLoopProposal(context, coveringNode, resultingCollections); @@ -504,13 +522,190 @@ private static boolean getConvertAnonymousToNestedProposal(IInvocationContext co return false; } + private static boolean getConvertAnonymousClassCreationsToLambdaProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) { + while (covering.getLocationInParent() == MethodDeclaration.NAME_PROPERTY + || covering.getLocationInParent() == MethodDeclaration.BODY_PROPERTY + || covering.getLocationInParent() == AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY) { + covering= covering.getParent(); + } + + ClassInstanceCreation cic; + if (covering instanceof ClassInstanceCreation) { + cic= (ClassInstanceCreation) covering; + } else if (covering.getLocationInParent() == ClassInstanceCreation.ANONYMOUS_CLASS_DECLARATION_PROPERTY) { + cic= (ClassInstanceCreation) covering.getParent(); + } else if (covering instanceof Name) { + ASTNode normalized= ASTNodes.getNormalizedNode(covering); + if (normalized.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY) + return false; + cic= (ClassInstanceCreation) normalized.getParent(); + } else { + return false; + } + + IProposableFix fix= LambdaExpressionsFix.createConvertToLambdaFix(cic); + if (fix == null) + return false; + + if (resultingCollections == null) + return true; + + // add correction proposal + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + Map options= new Hashtable(); + options.put(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES, CleanUpOptions.TRUE); + options.put(CleanUpConstants.USE_LAMBDA, CleanUpOptions.TRUE); + FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.CONVERT_TO_LAMBDA_EXPRESSION, image, context); + resultingCollections.add(proposal); + return true; + } + + private static boolean getConvertLambdaToAnonymousClassCreationsProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) { + LambdaExpression lambda; + if (covering instanceof LambdaExpression) { + lambda= (LambdaExpression) covering; + } else if (covering.getLocationInParent() == LambdaExpression.BODY_PROPERTY) { + lambda= (LambdaExpression) covering.getParent(); + } else { + return false; + } + + IProposableFix fix= LambdaExpressionsFix.createConvertToAnonymousClassCreationsFix(lambda); + if (fix == null) + return false; + + if (resultingCollections == null) + return true; + + // add correction proposal + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + Map options= new Hashtable(); + options.put(CleanUpConstants.CONVERT_FUNCTIONAL_INTERFACES, CleanUpOptions.TRUE); + options.put(CleanUpConstants.USE_ANONYMOUS_CLASS_CREATION, CleanUpOptions.TRUE); + FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new LambdaExpressionsCleanUp(options), IProposalRelevance.CONVERT_TO_ANONYMOUS_CLASS_CREATION, image, context); + resultingCollections.add(proposal); + return true; + } + + private static boolean getChangeLambdaBodyToBlockProposal(IInvocationContext context, ASTNode covering, Collection resultingCollections) { + LambdaExpression lambda; + if (covering instanceof LambdaExpression) { + lambda= (LambdaExpression) covering; + } else if (covering.getLocationInParent() == LambdaExpression.BODY_PROPERTY) { + lambda= (LambdaExpression) covering.getParent(); + } else { + return false; + } + + if (!(lambda.getBody() instanceof Expression)) + return false; + if (lambda.resolveMethodBinding() == null) + return false; + + if (resultingCollections == null) + return true; + + AST ast= lambda.getAST(); + ASTRewrite rewrite= ASTRewrite.create(ast); + + Statement statementInBlockBody; + Expression bodyExpr= (Expression) rewrite.createMoveTarget(lambda.getBody()); + if (ast.resolveWellKnownType("void").isEqualTo(lambda.resolveMethodBinding().getReturnType())) { //$NON-NLS-1$ + ExpressionStatement expressionStatement= ast.newExpressionStatement(bodyExpr); + statementInBlockBody= expressionStatement; + } else { + ReturnStatement returnStatement= ast.newReturnStatement(); + returnStatement.setExpression(bodyExpr); + statementInBlockBody= returnStatement; + } + Block blockBody= ast.newBlock(); + blockBody.statements().add(statementInBlockBody); + + rewrite.set(lambda, LambdaExpression.BODY_PROPERTY, blockBody, null); + + // add proposal + String label= CorrectionMessages.QuickAssistProcessor_change_lambda_body_to_block; + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_LAMBDA_BODY_TO_BLOCK, image); + resultingCollections.add(proposal); + return true; + } + + private static boolean getChangeLambdaBodyToExpressionProposal(IInvocationContext context, ASTNode covering, Collection resultingCollections) { + LambdaExpression lambda; + if (covering instanceof LambdaExpression) { + lambda= (LambdaExpression) covering; + } else if (covering.getLocationInParent() == LambdaExpression.BODY_PROPERTY) { + lambda= (LambdaExpression) covering.getParent(); + } else { + return false; + } + + if (!(lambda.getBody() instanceof Block)) + return false; + + Block lambdaBody= (Block) lambda.getBody(); + if (lambdaBody.statements().size() != 1) + return false; + + Expression exprBody; + Statement singleStatement= (Statement) lambdaBody.statements().get(0); + if (singleStatement instanceof ReturnStatement) { + Expression returnExpr= ((ReturnStatement) singleStatement).getExpression(); + if (returnExpr == null) + return false; + exprBody= returnExpr; + } else if (singleStatement instanceof ExpressionStatement) { + Expression expression= ((ExpressionStatement) singleStatement).getExpression(); + if (isValidExpressionBody(expression)) { + exprBody= expression; + } else { + return false; + } + } else { + return false; + } + + if (resultingCollections == null) + return true; + + AST ast= lambda.getAST(); + ASTRewrite rewrite= ASTRewrite.create(ast); + + Expression movedBody= (Expression) rewrite.createMoveTarget(exprBody); + rewrite.set(lambda, LambdaExpression.BODY_PROPERTY, movedBody, null); + + // add proposal + String label= CorrectionMessages.QuickAssistProcessor_change_lambda_body_to_expression; + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_LAMBDA_BODY_TO_EXPRESSION, image); + resultingCollections.add(proposal); + return true; + } + + private static boolean isValidExpressionBody(Expression expression) { + boolean isValidExpressionBody= expression instanceof Assignment + || expression instanceof ClassInstanceCreation + || expression instanceof MethodInvocation + || expression instanceof PostfixExpression + || expression instanceof SuperMethodInvocation; + if (expression instanceof PrefixExpression) { + Operator operator= ((PrefixExpression) expression).getOperator(); + if (operator == Operator.INCREMENT || operator == Operator.DECREMENT) { + isValidExpressionBody= true; + } + } + return isValidExpressionBody; + } + public static boolean getInferDiamondArgumentsProposal(IInvocationContext context, ASTNode node, IProblemLocation[] locations, Collection resultingCollections) { ParameterizedType createdType= null; if (node instanceof Name) { Name name= ASTNodes.getTopMostName((Name) node); - if (name.getLocationInParent() == SimpleType.NAME_PROPERTY) { - SimpleType type= (SimpleType) name.getParent(); + if (name.getLocationInParent() == SimpleType.NAME_PROPERTY || + name.getLocationInParent() == NameQualifiedType.NAME_PROPERTY) { + ASTNode type= name.getParent(); if (type.getLocationInParent() == ParameterizedType.TYPE_PROPERTY) { createdType= (ParameterizedType) type.getParent(); if (createdType.getLocationInParent() != ClassInstanceCreation.TYPE_PROPERTY) { @@ -755,12 +950,12 @@ private static boolean getSplitVariableProposals(IInvocationContext context, AST rewrite.replace(fragment.getParent(), assignment, null); VariableDeclarationFragment newFrag= ast.newVariableDeclarationFragment(); newFrag.setName(ast.newSimpleName(fragment.getName().getIdentifier())); - newFrag.setExtraDimensions(fragment.getExtraDimensions()); + newFrag.extraDimensions().addAll(DimensionRewrite.copyDimensions(fragment.extraDimensions(), rewrite)); VariableDeclarationExpression oldVarDecl= (VariableDeclarationExpression) fragParent; VariableDeclarationStatement newVarDec= ast.newVariableDeclarationStatement(newFrag); - newVarDec.setType((Type) ASTNode.copySubtree(ast, oldVarDecl.getType())); + newVarDec.setType((Type) rewrite.createCopyTarget(oldVarDecl.getType())); newVarDec.modifiers().addAll(ASTNodeFactory.newModifiers(ast, oldVarDecl.getModifiers())); newStatement= newVarDec; } @@ -1187,6 +1382,9 @@ private static boolean getAssignParamToFieldProposals(IInvocationContext context ITypeBinding parentType= Bindings.getBindingOfParentType(node); if (parentType != null) { + if (parentType.isInterface()) { + return false; + } // assign to existing fields CompilationUnit root= context.getASTRoot(); IVariableBinding[] declaredFields= parentType.getDeclaredFields(); @@ -1276,7 +1474,7 @@ public static boolean getCatchClauseToThrowsProposals(IInvocationContext context } Type type= catchClause.getException().getType(); - if (!type.isSimpleType() && !type.isUnionType()) { + if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) { return false; } @@ -1292,12 +1490,14 @@ public static boolean getCatchClauseToThrowsProposals(IInvocationContext context AST ast= bodyDeclaration.getAST(); Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - SimpleType selectedMultiCatchType= null; + Type selectedMultiCatchType= null; if (type.isUnionType() && node instanceof Name) { Name topMostName= ASTNodes.getTopMostName((Name) node); ASTNode parent= topMostName.getParent(); if (parent instanceof SimpleType) { selectedMultiCatchType= (SimpleType) parent; + } else if (parent instanceof NameQualifiedType) { + selectedMultiCatchType= (NameQualifiedType) parent; } } @@ -1317,12 +1517,12 @@ public static boolean getCatchClauseToThrowsProposals(IInvocationContext context UnionType unionType= (UnionType) type; List types= unionType.types(); for (Type elementType : types) { - if (!(elementType instanceof SimpleType)) + if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType)) return false; - addExceptionToThrows(ast, methodDeclaration, rewrite, (SimpleType) elementType); + addExceptionToThrows(ast, methodDeclaration, rewrite, elementType); } } else { - addExceptionToThrows(ast, methodDeclaration, rewrite, (SimpleType) type); + addExceptionToThrows(ast, methodDeclaration, rewrite, type); } String label= CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description; ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS, image); @@ -1358,20 +1558,19 @@ private static void removeException(ASTRewrite rewrite, UnionType unionType, Typ } } - private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, SimpleType type2) { + private static void addExceptionToThrows(AST ast, MethodDeclaration methodDeclaration, ASTRewrite rewrite, Type type2) { ITypeBinding binding= type2.resolveBinding(); - if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptions())) { - Name name= type2.getName(); - Name newName= (Name) ASTNode.copySubtree(ast, name); + if (binding == null || isNotYetThrown(binding, methodDeclaration.thrownExceptionTypes())) { + Type newType= (Type) ASTNode.copySubtree(ast, type2); - ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY); - listRewriter.insertLast(newName, null); + ListRewrite listRewriter= rewrite.getListRewrite(methodDeclaration, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY); + listRewriter.insertLast(newType, null); } } private static void removeCatchBlock(ASTRewrite rewrite, CatchClause catchClause) { TryStatement tryStatement= (TryStatement) catchClause.getParent(); - if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null || (tryStatement.getAST().apiLevel() >= AST.JLS4 && !tryStatement.resources().isEmpty())) { + if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null || !tryStatement.resources().isEmpty()) { rewrite.remove(catchClause, null); } else { Block block= tryStatement.getBody(); @@ -1397,10 +1596,10 @@ private static void removeCatchBlock(ASTRewrite rewrite, CatchClause catchClause } } - private static boolean isNotYetThrown(ITypeBinding binding, List thrownExceptions) { + private static boolean isNotYetThrown(ITypeBinding binding, List thrownExceptions) { for (int i= 0; i < thrownExceptions.size(); i++) { - Name name= thrownExceptions.get(i); - ITypeBinding elem= (ITypeBinding) name.resolveBinding(); + Type name= thrownExceptions.get(i); + ITypeBinding elem= name.resolveBinding(); if (elem != null) { if (Bindings.isSuperType(elem, binding)) { // existing exception is base class of new return false; @@ -1426,12 +1625,12 @@ private static boolean getPickoutTypeFromMulticatchProposals(IInvocationContext return false; } - SimpleType selectedMultiCatchType= null; + Type selectedMultiCatchType= null; if (type.isUnionType() && node instanceof Name) { Name topMostName= ASTNodes.getTopMostName((Name) node); ASTNode parent= topMostName.getParent(); - if (parent instanceof SimpleType) { - selectedMultiCatchType= (SimpleType) parent; + if (parent instanceof SimpleType || parent instanceof NameQualifiedType) { + selectedMultiCatchType= (Type) parent; } } @@ -1499,12 +1698,12 @@ private static boolean getConvertToMultiCatchProposals(IInvocationContext contex } Type type1= catchClause.getException().getType(); - SimpleType selectedMultiCatchType= null; + Type selectedMultiCatchType= null; if (type1.isUnionType() && covering instanceof Name) { Name topMostName= ASTNodes.getTopMostName((Name) covering); ASTNode parent= topMostName.getParent(); - if (parent instanceof SimpleType) { - selectedMultiCatchType= (SimpleType) parent; + if (parent instanceof SimpleType || parent instanceof NameQualifiedType) { + selectedMultiCatchType= (Type) parent; } } if (selectedMultiCatchType != null) @@ -1590,12 +1789,12 @@ private static boolean getUnrollMultiCatchProposals(IInvocationContext context, } Type type1= catchClause.getException().getType(); - SimpleType selectedMultiCatchType= null; + Type selectedMultiCatchType= null; if (type1.isUnionType() && covering instanceof Name) { Name topMostName= ASTNodes.getTopMostName((Name) covering); ASTNode parent= topMostName.getParent(); - if (parent instanceof SimpleType) { - selectedMultiCatchType= (SimpleType) parent; + if (parent instanceof SimpleType || parent instanceof NameQualifiedType) { + selectedMultiCatchType= (Type) parent; } } if (selectedMultiCatchType != null) @@ -1801,7 +2000,7 @@ private static boolean getUnWrapProposals(IInvocationContext context, ASTNode no label= CorrectionMessages.QuickAssistProcessor_unwrap_dostatement; } else if (outer instanceof TryStatement) { TryStatement tryStatement= (TryStatement) outer; - if (tryStatement.catchClauses().isEmpty() && (tryStatement.getAST().apiLevel() >= AST.JLS4 && tryStatement.resources().isEmpty())) { + if (tryStatement.catchClauses().isEmpty() && tryStatement.resources().isEmpty()) { body= tryStatement.getBody(); } label= CorrectionMessages.QuickAssistProcessor_unwrap_trystatement; @@ -2325,7 +2524,7 @@ private static boolean getConvertEnhancedForLoopProposal(IInvocationContext cont // create 'for' body element variable VariableDeclarationFragment elementFragment= ast.newVariableDeclarationFragment(); - elementFragment.setExtraDimensions(parameter.getExtraDimensions()); + elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite)); elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName())); SimpleName elementIterName= ast.newSimpleName(iterName); @@ -2394,7 +2593,9 @@ private static boolean getConvertEnhancedForLoopProposal(IInvocationContext cont VariableDeclarationStatement varDeclaration= ast.newVariableDeclarationStatement(varFragment); Type varType; if (initializerIsArray) { - varType= ast.newArrayType((Type) rewrite.createCopyTarget(parameter.getType()), parameter.getExtraDimensions() + 1); + ArrayType varArrayType= (ArrayType) DimensionRewrite.copyTypeAndAddDimensions(parameter.getType(), parameter.extraDimensions(), rewrite); + varArrayType.dimensions().add(0, ast.newDimension()); + varType= varArrayType; } else { ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(node, imports); @@ -2465,7 +2666,7 @@ private static boolean getConvertEnhancedForLoopProposal(IInvocationContext cont // create 'for' body element variable VariableDeclarationFragment elementFragment= ast.newVariableDeclarationFragment(); - elementFragment.setExtraDimensions(parameter.getExtraDimensions()); + elementFragment.extraDimensions().addAll(DimensionRewrite.copyDimensions(parameter.extraDimensions(), rewrite)); elementFragment.setName((SimpleName) rewrite.createCopyTarget(parameter.getName())); SimpleName elementVarName= ast.newSimpleName(varName); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java index bc2e604fa4..23cf48e5b6 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -66,6 +66,7 @@ public boolean hasCorrections(ICompilationUnit cu, int problemId) { case IProblem.PackageIsNotExpectedPackage: case IProblem.UndefinedType: case IProblem.TypeMismatch: + case IProblem.ReturnTypeMismatch: case IProblem.UnhandledException: case IProblem.UnhandledExceptionOnAutoClose: case IProblem.UnreachableCatch: @@ -78,6 +79,7 @@ public boolean hasCorrections(ICompilationUnit cu, int problemId) { case IProblem.NonExternalizedStringLiteral: case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: + case IProblem.NonStaticOrAlienTypeReceiver: case IProblem.StaticMethodRequested: case IProblem.NonStaticFieldFromStaticInvocation: case IProblem.InstanceMethodDuringConstructorInvocation: @@ -263,6 +265,14 @@ public boolean hasCorrections(ICompilationUnit cu, int problemId) { case IProblem.ConflictingNullAnnotations: case IProblem.ConflictingInheritedNullAnnotations: case IProblem.ParsingErrorInsertToComplete: + case IProblem.ExplicitThisParameterNotBelow18: + case IProblem.DefaultMethodNotBelow18: + case IProblem.StaticInterfaceMethodNotBelow18: + case IProblem.LambdaExpressionNotBelow18: + case IProblem.MethodReferenceNotBelow18: + case IProblem.ConstructorReferenceNotBelow18: + case IProblem.IntersectionCastNotBelow18: + case IProblem.InvalidUsageOfTypeAnnotations: return true; default: return SuppressWarningsSubProcessor.hasSuppressWarningsProposal(cu.getJavaProject(), problemId); @@ -361,6 +371,7 @@ private void process(IInvocationContext context, IProblemLocation problem, Colle UnresolvedElementsSubProcessor.getTypeProposals(context, problem, proposals); break; case IProblem.TypeMismatch: + case IProblem.ReturnTypeMismatch: TypeMismatchSubProcessor.addTypeMismatchProposals(context, problem, proposals); break; case IProblem.IncompatibleTypesInForeach: @@ -405,6 +416,7 @@ private void process(IInvocationContext context, IProblemLocation problem, Colle break; case IProblem.NonStaticAccessToStaticField: case IProblem.NonStaticAccessToStaticMethod: + case IProblem.NonStaticOrAlienTypeReceiver: case IProblem.IndirectAccessToStaticField: case IProblem.IndirectAccessToStaticMethod: LocalCorrectionsSubProcessor.addCorrectAccessToStaticProposals(context, problem, proposals); @@ -615,6 +627,16 @@ private void process(IInvocationContext context, IProblemLocation problem, Colle case IProblem.SwitchOnStringsNotBelow17: ReorgCorrectionsSubProcessor.getNeedHigherComplianceProposals(context, problem, proposals, JavaCore.VERSION_1_7); break; + case IProblem.ExplicitThisParameterNotBelow18: + case IProblem.DefaultMethodNotBelow18: + case IProblem.StaticInterfaceMethodNotBelow18: + case IProblem.LambdaExpressionNotBelow18: + case IProblem.MethodReferenceNotBelow18: + case IProblem.ConstructorReferenceNotBelow18: + case IProblem.IntersectionCastNotBelow18: + case IProblem.InvalidUsageOfTypeAnnotations: + ReorgCorrectionsSubProcessor.getNeedHigherComplianceProposals(context, problem, proposals, JavaCore.VERSION_1_8); + break; case IProblem.NonGenericType: TypeArgumentMismatchSubProcessor.removeMismatchedArguments(context, problem, proposals); break; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java index c10deec0b5..fe07a12a29 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReturnTypeSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,6 +30,7 @@ import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Javadoc; +import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.ReturnStatement; @@ -54,6 +55,7 @@ import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.MissingReturnTypeInLambdaCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposal; import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.BindingLabelProvider; @@ -288,33 +290,40 @@ public static void addMissingReturnStatementProposals(IInvocationContext context if (selectedNode == null) { return; } - BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); - if (decl instanceof MethodDeclaration) { - MethodDeclaration methodDecl= (MethodDeclaration) decl; - Block block= methodDecl.getBody(); - if (block == null) { - return; - } - ReturnStatement existingStatement= (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null; - proposals.add( new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE)); - - Type returnType= methodDecl.getReturnType2(); - if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) { //$NON-NLS-1$ - AST ast= methodDecl.getAST(); - ASTRewrite rewrite= ASTRewrite.create(ast); - rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null); - Javadoc javadoc= methodDecl.getJavadoc(); - if (javadoc != null) { - TagElement tagElement= JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null); - if (tagElement != null) { - rewrite.remove(tagElement, null); - } + ReturnStatement existingStatement= (selectedNode instanceof ReturnStatement) ? (ReturnStatement) selectedNode : null; + // Lambda Expression can be in a MethodDeclaration or a Field Declaration + if (selectedNode instanceof LambdaExpression) { + MissingReturnTypeInLambdaCorrectionProposal proposal= new MissingReturnTypeInLambdaCorrectionProposal(cu, (LambdaExpression) selectedNode, existingStatement, + IProposalRelevance.MISSING_RETURN_TYPE); + proposals.add(proposal); + } else { + BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); + if (decl instanceof MethodDeclaration) { + MethodDeclaration methodDecl= (MethodDeclaration) decl; + Block block= methodDecl.getBody(); + if (block == null) { + return; } + proposals.add(new MissingReturnTypeCorrectionProposal(cu, methodDecl, existingStatement, IProposalRelevance.MISSING_RETURN_TYPE)); + + Type returnType= methodDecl.getReturnType2(); + if (returnType != null && !"void".equals(ASTNodes.asString(returnType))) { //$NON-NLS-1$ + AST ast= methodDecl.getAST(); + ASTRewrite rewrite= ASTRewrite.create(ast); + rewrite.replace(returnType, ast.newPrimitiveType(PrimitiveType.VOID), null); + Javadoc javadoc= methodDecl.getJavadoc(); + if (javadoc != null) { + TagElement tagElement= JavadocTagsSubProcessor.findTag(javadoc, TagElement.TAG_RETURN, null); + if (tagElement != null) { + rewrite.remove(tagElement, null); + } + } - String label= CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_RETURN_TYPE_TO_VOID, image); - proposals.add(proposal); + String label= CorrectionMessages.ReturnTypeSubProcessor_changetovoid_description; + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.CHANGE_RETURN_TYPE_TO_VOID, image); + proposals.add(proposal); + } } } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java index f904ad5b0b..f2cfefbbed 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,6 +39,7 @@ import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; @@ -455,11 +456,17 @@ public static void addTypeMismatchInForEachProposals(IInvocationContext context, SingleVariableDeclaration parameter= forStatement.getParameter(); ICompilationUnit cu= context.getCompilationUnit(); - if (parameter.getName().getLength() == 0 - && parameter.getType() instanceof SimpleType) { - SimpleType type= (SimpleType) parameter.getType(); - if (type.getName() instanceof SimpleName) { - SimpleName simpleName= (SimpleName) type.getName(); + if (parameter.getName().getLength() == 0) { + SimpleName simpleName= null; + if (parameter.getType() instanceof SimpleType) { + SimpleType type= (SimpleType) parameter.getType(); + if (type.getName() instanceof SimpleName) { + simpleName= (SimpleName) type.getName(); + } + } else if (parameter.getType() instanceof NameQualifiedType) { + simpleName= ((NameQualifiedType) parameter.getType()).getName(); + } + if (simpleName != null) { String name= simpleName.getIdentifier(); int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7; String label= Messages.format(CorrectionMessages.TypeMismatchSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name)); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java index 2dcf18c0b8..35c877a2b0 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,7 +31,6 @@ import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.resources.IFile; @@ -83,6 +82,7 @@ import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.EnhancedForStatement; import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionMethodReference; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; @@ -95,6 +95,7 @@ import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; +import org.eclipse.jdt.core.dom.NameQualifiedType; import org.eclipse.jdt.core.dom.NormalAnnotation; import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.QualifiedName; @@ -201,8 +202,14 @@ public static void getVariableProposals(IInvocationContext context, IProblemLoca node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); - if (locationInParent == MethodInvocation.EXPRESSION_PROPERTY) { - typeKind= SimilarElementsRequestor.CLASSES; + if (locationInParent == ExpressionMethodReference.EXPRESSION_PROPERTY) { + typeKind= SimilarElementsRequestor.REF_TYPES; + } else if (locationInParent == MethodInvocation.EXPRESSION_PROPERTY) { + if (JavaModelUtil.is18OrHigher(cu.getJavaProject())) { + typeKind= SimilarElementsRequestor.CLASSES | SimilarElementsRequestor.INTERFACES | SimilarElementsRequestor.ENUMS; + } else { + typeKind= SimilarElementsRequestor.CLASSES; + } } else if (locationInParent == FieldAccess.NAME_PROPERTY) { Expression expression= ((FieldAccess) parent).getExpression(); if (expression != null) { @@ -211,7 +218,7 @@ public static void getVariableProposals(IInvocationContext context, IProblemLoca node= null; } } - } else if (parent instanceof SimpleType) { + } else if (parent instanceof SimpleType || parent instanceof NameQualifiedType) { suggestVariableProposals= false; typeKind= SimilarElementsRequestor.REF_TYPES_AND_VAR; } else if (parent instanceof QualifiedName) { @@ -225,7 +232,7 @@ public static void getVariableProposals(IInvocationContext context, IProblemLoca while (outerParent instanceof QualifiedName) { outerParent= outerParent.getParent(); } - if (outerParent instanceof SimpleType) { + if (outerParent instanceof SimpleType || outerParent instanceof NameQualifiedType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } @@ -249,7 +256,7 @@ public static void getVariableProposals(IInvocationContext context, IProblemLoca typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= node.isSimpleName(); } - if (selectedNode.getParent() instanceof SimpleType) { + if (selectedNode.getParent() instanceof SimpleType || selectedNode.getParent() instanceof NameQualifiedType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariableProposals= false; } @@ -609,10 +616,14 @@ public static void getTypeProposals(IInvocationContext context, IProblemLocation Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); + } else if (selectedNode instanceof NameQualifiedType) { + node= ((NameQualifiedType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); + } else if (elementType.isNameQualifiedType()) { + node= ((NameQualifiedType) elementType).getName(); } else { return; } @@ -641,7 +652,7 @@ public static void getTypeProposals(IInvocationContext context, IProblemLocation } private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection proposals) { - if (selectedNode instanceof SimpleName && selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY) { + if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) { ASTNode type= selectedNode.getParent(); if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) { SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent(); @@ -687,12 +698,13 @@ private static void addNullityAnnotationTypesProposals(ICompilationUnit cu, Name return; if (javaProject.findType(defaultOptions.get(annotationNameOptions[0])) != null) return; - Bundle annotationsBundle= Platform.getBundle("org.eclipse.jdt.annotation"); //$NON-NLS-1$ - if (annotationsBundle == null) + String version= JavaModelUtil.is18OrHigher(javaProject) ? "2" : "[1.1.0,2.0.0)"; //$NON-NLS-1$ //$NON-NLS-2$ + Bundle[] annotationsBundles= JavaPlugin.getDefault().getBundles("org.eclipse.jdt.annotation", version); //$NON-NLS-1$ + if (annotationsBundles == null) return; if (! addAddToBuildPropertiesProposal(cu, node, nullityAnnotation, proposals)) - addCopyAnnotationsJarProposal(cu, node, nullityAnnotation, annotationsBundle, proposals); + addCopyAnnotationsJarProposal(cu, node, nullityAnnotation, annotationsBundles[0], proposals); } private static boolean addAddToBuildPropertiesProposal(final ICompilationUnit cu, final Name name, final String fullyQualifiedName, Collection proposals) throws CoreException { @@ -840,7 +852,9 @@ private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name if (proposal instanceof AddImportCorrectionProposal) proposal.setRelevance(relevance + elements.length + 2); - if (binding.isParameterizedType() && node.getParent() instanceof SimpleType && !(node.getParent().getParent() instanceof Type)) { + if (binding.isParameterizedType() + && (node.getParent() instanceof SimpleType || node.getParent() instanceof NameQualifiedType) + && !(node.getParent().getParent() instanceof Type)) { proposals.add(createTypeRefChangeFullProposal(cu, binding, node, relevance + 5)); } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/AbstractMethodCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/AbstractMethodCorrectionProposal.java index 67858db7aa..7f9adc3ed4 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/AbstractMethodCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/AbstractMethodCorrectionProposal.java @@ -32,7 +32,6 @@ import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; @@ -151,7 +150,7 @@ private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) th } addNewParameters(rewrite, takenNames, decl.parameters()); - addNewExceptions(rewrite, decl.thrownExceptions()); + addNewExceptions(rewrite, decl.thrownExceptionTypes()); Block body= null; if (!fSenderBinding.isInterface()) { @@ -206,7 +205,7 @@ private int findConstructorInsertIndex(List decls) { protected abstract void addNewModifiers(ASTRewrite rewrite, ASTNode targetTypeDecl, List exceptions); protected abstract void addNewTypeParameters(ASTRewrite rewrite, List takenNames, List params) throws CoreException; protected abstract void addNewParameters(ASTRewrite rewrite, List takenNames, List params) throws CoreException; - protected abstract void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException; + protected abstract void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException; protected abstract SimpleName getNewName(ASTRewrite rewrite); protected abstract Type getNewMethodType(ASTRewrite rewrite) throws CoreException; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ChangeMethodSignatureProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ChangeMethodSignatureProposal.java index b43f5fb55a..2d7681bec6 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ChangeMethodSignatureProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ChangeMethodSignatureProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,6 @@ import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TagElement; @@ -46,6 +45,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; @@ -212,7 +212,7 @@ private void modifyParameters(ASTRewrite rewrite, MethodDeclaration methodDecl) Type newType= imports.addImport(newTypeBinding, ast, context); rewrite.replace(decl.getType(), newType, null); - rewrite.set(decl, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(decl, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); IBinding binding= decl.getName().resolveBinding(); if (binding != null) { @@ -364,9 +364,9 @@ private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) ImportRewrite imports= getImportRewrite(); ImportRewriteContext context= new ContextSensitiveImportRewriteContext(methodDecl, imports); - ListRewrite listRewrite= rewrite.getListRewrite(methodDecl, MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY); + ListRewrite listRewrite= rewrite.getListRewrite(methodDecl, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY); - List exceptions= methodDecl.thrownExceptions(); // old exceptions + List exceptions= methodDecl.thrownExceptionTypes(); // old exceptions int k= 0; // index over the old exceptions for (int i= 0; i < fExceptionChanges.length; i++) { @@ -377,7 +377,7 @@ private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) } else if (curr instanceof InsertDescription) { InsertDescription desc= (InsertDescription) curr; String type= imports.addImport(desc.type, context); - ASTNode newNode= ASTNodeFactory.newName(ast, type); + ASTNode newNode= imports.addImport(desc.type, ast, context); listRewrite.insertAt(newNode, i, null); @@ -397,7 +397,7 @@ private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) } } else if (curr instanceof RemoveDescription) { - Name node= exceptions.get(k); + Type node= exceptions.get(k); listRewrite.remove(node, null); k++; @@ -409,10 +409,10 @@ private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) } else if (curr instanceof EditDescription) { EditDescription desc= (EditDescription) curr; - Name oldNode= exceptions.get(k); + Type oldNode= exceptions.get(k); String type= imports.addImport(desc.type, context); - ASTNode newNode= ASTNodeFactory.newName(ast, type); + ASTNode newNode= imports.addImport(desc.type, ast, context); listRewrite.replace(oldNode, newNode, null); String key= getExceptionTypeGroupId(i); @@ -422,14 +422,14 @@ private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) TagElement tagNode= findThrowsTag(methodDecl, oldNode); if (tagNode != null) { - ASTNode newRef= ASTNodeFactory.newName(ast, type); + ASTNode newRef= ASTNodeFactory.newType(ast, type); rewrite.replace((ASTNode) tagNode.fragments().get(0), newRef, null); addLinkedPosition(rewrite.track(newRef), false, key); } } else if (curr instanceof SwapDescription) { - Name decl1= exceptions.get(k); - Name decl2= exceptions.get(((SwapDescription) curr).index); + Type decl1= exceptions.get(k); + Type decl2= exceptions.get(((SwapDescription) curr).index); rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null); rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null); @@ -453,20 +453,20 @@ private void insertTabStop(ASTRewrite rewriter, List fragments, String addLinkedPosition(rewriter.track(textElement), false, linkedName); } - private TagElement findThrowsTag(MethodDeclaration decl, Name exception) { + private TagElement findThrowsTag(MethodDeclaration decl, Type exception) { Javadoc javadoc= decl.getJavadoc(); if (javadoc != null) { - String name= ASTNodes.getSimpleNameIdentifier(exception); + String name= ASTNodes.getTypeName(exception); return JavadocTagsSubProcessor.findThrowsTag(javadoc, name); } return null; } - private TagElement insertThrowsTag(ListRewrite tagRewriter, List exceptions, int currentIndex, TagElement newTagElement) { + private TagElement insertThrowsTag(ListRewrite tagRewriter, List exceptions, int currentIndex, TagElement newTagElement) { HashSet previousNames= new HashSet(); for (int n = 0; n < currentIndex; n++) { - Name curr= exceptions.get(n); - previousNames.add(ASTNodes.getSimpleNameIdentifier(curr)); + Type curr= exceptions.get(n); + previousNames.add(ASTNodes.getTypeName(curr)); } JavadocTagsSubProcessor.insertTag(tagRewriter, newTagElement, previousNames); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java index eb19bbe15e..6550f0c847 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,6 +31,7 @@ import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; +import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; @@ -161,11 +162,11 @@ private MethodDeclaration createNewMethodDeclaration(AST ast, IMethodBinding bin parameters.add(var); } - List thrownExceptions= decl.thrownExceptions(); + List thrownExceptions= decl.thrownExceptionTypes(); ITypeBinding[] excTypes= binding.getExceptionTypes(); for (int i= 0; i < excTypes.length; i++) { - String excTypeName= getImportRewrite().addImport(excTypes[i], importRewriteContext); - thrownExceptions.add(ASTNodeFactory.newName(ast, excTypeName)); + Type excType= getImportRewrite().addImport(excTypes[i], ast, importRewriteContext); + thrownExceptions.add(excType); } if (invocation == null) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeCorrectionProposal.java index daa0f16d67..f2bde06d55 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeCorrectionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -38,10 +38,10 @@ public class MissingReturnTypeCorrectionProposal extends LinkedCorrectionProposal { - private static final String RETURN_EXPRESSION_KEY= "value"; //$NON-NLS-1$ + protected static final String RETURN_EXPRESSION_KEY= "value"; //$NON-NLS-1$ private MethodDeclaration fMethodDecl; - private ReturnStatement fExistingReturn; + protected ReturnStatement fExistingReturn; public MissingReturnTypeCorrectionProposal(ICompilationUnit cu, MethodDeclaration decl, ReturnStatement existingReturn, int relevance) { super("", cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); //$NON-NLS-1$ @@ -63,7 +63,7 @@ public String getName() { */ @Override protected ASTRewrite getRewrite() { - AST ast= fMethodDecl.getAST(); + AST ast= getAST(); ITypeBinding returnBinding= getReturnTypeBinding(); @@ -80,77 +80,62 @@ protected ASTRewrite getRewrite() { } else { ASTRewrite rewrite= ASTRewrite.create(ast); - Block block= fMethodDecl.getBody(); + ASTNode body= getBody(); + // For lambda the body can be a block or an expression. + if (body instanceof Block) { + Block block= (Block) body; + List statements= block.statements(); + int nStatements= statements.size(); + ASTNode lastStatement= null; + if (nStatements > 0) { + lastStatement= statements.get(nStatements - 1); + } - List statements= block.statements(); - int nStatements= statements.size(); - ASTNode lastStatement= null; - if (nStatements > 0) { - lastStatement= statements.get(nStatements - 1); - } + if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) { + Expression expression= ((ExpressionStatement) lastStatement).getExpression(); + ITypeBinding binding= expression.resolveTypeBinding(); + if (binding != null && binding.isAssignmentCompatible(returnBinding)) { + Expression placeHolder= (Expression) rewrite.createMoveTarget(expression); - if (returnBinding != null && lastStatement instanceof ExpressionStatement && lastStatement.getNodeType() != ASTNode.ASSIGNMENT) { - Expression expression= ((ExpressionStatement) lastStatement).getExpression(); - ITypeBinding binding= expression.resolveTypeBinding(); - if (binding != null && binding.isAssignmentCompatible(returnBinding)) { - Expression placeHolder= (Expression) rewrite.createMoveTarget(expression); + ReturnStatement returnStatement= ast.newReturnStatement(); + returnStatement.setExpression(placeHolder); - ReturnStatement returnStatement= ast.newReturnStatement(); - returnStatement.setExpression(placeHolder); + rewrite.replace(lastStatement, returnStatement, null); + return rewrite; + } + } - rewrite.replace(lastStatement, returnStatement, null); - return rewrite; + int offset; + if (lastStatement == null) { + offset= block.getStartPosition() + 1; + } else { + offset= lastStatement.getStartPosition() + lastStatement.getLength(); } - } - int offset; - if (lastStatement == null) { - offset= block.getStartPosition() + 1; - } else { - offset= lastStatement.getStartPosition() + lastStatement.getLength(); - } - ReturnStatement returnStatement= ast.newReturnStatement(); - Expression expression= evaluateReturnExpressions(ast, returnBinding, offset); + ReturnStatement returnStatement= ast.newReturnStatement(); + Expression expression= evaluateReturnExpressions(ast, returnBinding, offset); - returnStatement.setExpression(expression); + returnStatement.setExpression(expression); - rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null); + rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY).insertLast(returnStatement, null); - addLinkedPosition(rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY); + addLinkedPosition(rewrite.track(returnStatement.getExpression()), true, RETURN_EXPRESSION_KEY); + } return rewrite; } } - private ITypeBinding getReturnTypeBinding() { - IMethodBinding methodBinding= fMethodDecl.resolveBinding(); - if (methodBinding != null && methodBinding.getReturnType() != null) { - return methodBinding.getReturnType(); - } - return null; - } - /* * Evaluates possible return expressions. The favourite expression is returned. */ private Expression evaluateReturnExpressions(AST ast, ITypeBinding returnBinding, int returnOffset) { - CompilationUnit root= (CompilationUnit) fMethodDecl.getRoot(); + CompilationUnit root= getCU(); Expression result= null; if (returnBinding != null) { - ScopeAnalyzer analyzer= new ScopeAnalyzer(root); - IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY ); - for (int i= 0; i < bindings.length; i++) { - IVariableBinding curr= (IVariableBinding) bindings[i]; - ITypeBinding type= curr.getType(); - if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr)) { - if (result == null) { - result= ast.newSimpleName(curr.getName()); - } - addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null); - } - } + result= computeProposals(ast, returnBinding, returnOffset, root, result); } - Expression defaultExpression= ASTNodeFactory.newDefaultExpression(ast, fMethodDecl.getReturnType2(), fMethodDecl.getExtraDimensions()); + Expression defaultExpression= createDefaultExpression(ast); addLinkedPositionProposal(RETURN_EXPRESSION_KEY, ASTNodes.asString(defaultExpression), null); if (result == null) { return defaultExpression; @@ -158,15 +143,60 @@ private Expression evaluateReturnExpressions(AST ast, ITypeBinding returnBinding return result; } - private boolean testModifier(IVariableBinding curr) { + protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) { + ScopeAnalyzer analyzer= new ScopeAnalyzer(root); + IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); + for (int i= 0; i < bindings.length; i++) { + IVariableBinding curr= (IVariableBinding) bindings[i]; + ITypeBinding type= curr.getType(); + if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr)) { + if (result == null) { + result= ast.newSimpleName(curr.getName()); + } + addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null); + } + } + return result; + } + + protected boolean testModifier(IVariableBinding curr) { int modifiers= curr.getModifiers(); int staticFinal= Modifier.STATIC | Modifier.FINAL; if ((modifiers & staticFinal) == staticFinal) { return false; } - if (Modifier.isStatic(modifiers) && !Modifier.isStatic(fMethodDecl.getModifiers())) { + if (Modifier.isStatic(modifiers) && !Modifier.isStatic(getModifiers())) { return false; } return true; } + + protected Expression createDefaultExpression(AST ast) { + return ASTNodeFactory.newDefaultExpression(ast, fMethodDecl.getReturnType2(), fMethodDecl.getExtraDimensions()); + } + + protected CompilationUnit getCU() { + return (CompilationUnit) fMethodDecl.getRoot(); + } + + + protected ASTNode getBody() { + return fMethodDecl.getBody(); + } + + protected AST getAST() { + return fMethodDecl.getAST(); + } + + protected ITypeBinding getReturnTypeBinding() { + IMethodBinding methodBinding= fMethodDecl.resolveBinding(); + if (methodBinding != null && methodBinding.getReturnType() != null) { + return methodBinding.getReturnType(); + } + return null; + } + + protected int getModifiers() { + return fMethodDecl.getModifiers(); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeInLambdaCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeInLambdaCorrectionProposal.java new file mode 100644 index 0000000000..964840fed8 --- /dev/null +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingReturnTypeInLambdaCorrectionProposal.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * Copyright (c) 2013, 2014 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package org.eclipse.jdt.internal.ui.text.correction.proposals; + +import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.ReturnStatement; +import org.eclipse.jdt.core.dom.VariableDeclarationFragment; + +import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; + +import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; + +public class MissingReturnTypeInLambdaCorrectionProposal extends MissingReturnTypeCorrectionProposal { + + private final LambdaExpression lambdaExpression; + + public MissingReturnTypeInLambdaCorrectionProposal(ICompilationUnit cu, LambdaExpression lambda, ReturnStatement existingReturn, int relevance) { + super(cu, null, existingReturn, relevance); + lambdaExpression= lambda; + fExistingReturn= existingReturn; + } + + @Override + protected AST getAST() { + return lambdaExpression.getAST(); + } + + @Override + public ITypeBinding getReturnTypeBinding() { + IMethodBinding methodBinding= lambdaExpression.resolveMethodBinding(); + if (methodBinding != null && methodBinding.getReturnType() != null) { + return methodBinding.getReturnType(); + } + return null; + } + + + @Override + protected CompilationUnit getCU() { + return (CompilationUnit) lambdaExpression.getRoot(); + } + + @Override + protected Expression createDefaultExpression(AST ast) { + return ASTNodeFactory.newDefaultExpression(ast, getReturnTypeBinding()); + } + + @Override + protected ASTNode getBody() { + return lambdaExpression.getBody(); + } + + @Override + protected int getModifiers() { + return 0; + } + + @Override + protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) { + ScopeAnalyzer analyzer= new ScopeAnalyzer(root); + IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); + + org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0); + ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT); + IVariableBinding varDeclFragBinding= null; + if (varDeclFrag != null) + varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding(); + for (int i= 0; i < bindings.length; i++) { + IVariableBinding curr= (IVariableBinding) bindings[i]; + ITypeBinding type= curr.getType(); + // Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised. + if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) { + if (result == null) { + result= ast.newSimpleName(curr.getName()); + } + addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName(), null); + } + } + return result; + } +} diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java index bcef4e72fb..6e6c670788 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -12,24 +12,36 @@ import org.eclipse.swt.graphics.Image; +import org.eclipse.core.runtime.CoreException; + import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.Modifier; +import org.eclipse.jdt.core.dom.ReturnStatement; +import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; import org.eclipse.jdt.internal.corext.dom.VariableDeclarationRewrite; import org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup; import org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroup.PositionInformation; +import org.eclipse.jdt.ui.CodeGeneration; + import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; public class ModifierChangeCorrectionProposal extends LinkedCorrectionProposal { @@ -48,7 +60,7 @@ public ModifierChangeCorrectionProposal(String label, ICompilationUnit targetCU, } @Override - protected ASTRewrite getRewrite() { + protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode boundNode= astRoot.findDeclaringNode(fBinding); ASTNode declNode= null; @@ -83,6 +95,34 @@ protected ASTRewrite getRewrite() { // can't separate } declNode= parent; + } else if (declNode.getNodeType() == ASTNode.METHOD_DECLARATION) { + MethodDeclaration methodDecl= (MethodDeclaration) declNode; + if (!methodDecl.isConstructor()) { + IMethodBinding methodBinding= methodDecl.resolveBinding(); + if (methodDecl.getBody() == null && methodBinding != null && Modifier.isAbstract(methodBinding.getModifiers()) && Modifier.isStatic(fIncludedModifiers)) { + // add body + ICompilationUnit unit= getCompilationUnit(); + String delimiter= unit.findRecommendedLineSeparator(); + String bodyStatement= ""; //$NON-NLS-1$ + + Block body= ast.newBlock(); + rewrite.set(methodDecl, MethodDeclaration.BODY_PROPERTY, body, null); + Type returnType= methodDecl.getReturnType2(); + if (returnType != null) { + Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, methodDecl.getExtraDimensions()); + if (expression != null) { + ReturnStatement returnStatement= ast.newReturnStatement(); + returnStatement.setExpression(expression); + bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, delimiter, unit.getJavaProject().getOptions(true)); + } + } + String placeHolder= CodeGeneration.getMethodBodyContent(unit, methodBinding.getDeclaringClass().getName(), methodBinding.getName(), false, bodyStatement, delimiter); + if (placeHolder != null) { + ReturnStatement todoNode= (ReturnStatement) rewrite.createStringPlaceholder(placeHolder, ASTNode.RETURN_STATEMENT); + body.statements().add(todoNode); + } + } + } } ModifierRewrite listRewrite= ModifierRewrite.create(rewrite, declNode); PositionInformation trackedDeclNode= listRewrite.setModifiers(fIncludedModifiers, fExcludedModifiers, null); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewCUUsingWizardProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewCUUsingWizardProposal.java index f899f41199..5caa80be1b 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewCUUsingWizardProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewCUUsingWizardProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -354,7 +354,7 @@ private ITypeBinding getPossibleSuperTypeBinding(ASTNode node) { ASTNode parent= node.getParent(); switch (parent.getNodeType()) { case ASTNode.METHOD_DECLARATION: - if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTIONS_PROPERTY) { + if (node.getLocationInParent() == MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY) { return ast.resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$ } break; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java index e04108bd23..df99572484 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -24,7 +24,6 @@ import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; @@ -33,7 +32,6 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; -import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; @@ -135,16 +133,15 @@ protected Type getNewMethodType(ASTRewrite rewrite) throws CoreException { * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewExceptions(org.eclipse.jdt.core.dom.rewrite.ASTRewrite, java.util.List) */ @Override - protected void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException { + protected void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException { AST ast= rewrite.getAST(); ImportRewrite importRewrite= getImportRewrite(); ITypeBinding[] bindings= fMethod.getExceptionTypes(); for (int i= 0; i < bindings.length; i++) { - String typeName= importRewrite.addImport(bindings[i]); - Name newNode= ASTNodeFactory.newName(ast, typeName); - exceptions.add(newNode); + Type newType= importRewrite.addImport(bindings[i], ast); + exceptions.add(newType); - addLinkedPosition(rewrite.track(newNode), false, "exc_type_" + i); //$NON-NLS-1$ + addLinkedPosition(rewrite.track(newType), false, "exc_type_" + i); //$NON-NLS-1$ } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewMethodCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewMethodCorrectionProposal.java index 324f9a9948..cb901c6a0f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewMethodCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewMethodCorrectionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -277,7 +277,7 @@ private String evaluateParameterName(List takenNames, Expression argNode * @see org.eclipse.jdt.internal.ui.text.correction.proposals.AbstractMethodCorrectionProposal#addNewExceptions(org.eclipse.jdt.core.dom.rewrite.ASTRewrite, java.util.List) */ @Override - protected void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException { + protected void addNewExceptions(ASTRewrite rewrite, List exceptions) throws CoreException { } /* (non-Javadoc) diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewVariableCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewVariableCorrectionProposal.java index 46f4d0f423..479fac4d3b 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewVariableCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewVariableCorrectionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -225,7 +225,6 @@ private ASTRewrite doAddLocal(CompilationUnit cu) { ASTRewrite rewrite= ASTRewrite.create(ast); ImportRewrite imports= createImportRewrite((CompilationUnit) decl.getRoot()); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); SimpleName[] names= getAllReferences(body); ASTNode dominant= getDominantNode(names); @@ -236,6 +235,7 @@ private ASTRewrite doAddLocal(CompilationUnit cu) { } SimpleName node= names[0]; + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(node, imports); if (isAssigned(dominantStatement, node)) { // x = 1; -> int x = 1; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/TypeChangeCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/TypeChangeCorrectionProposal.java index cfab9a9af2..6e7a6da73f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/TypeChangeCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/TypeChangeCorrectionProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -46,6 +46,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.DimensionRewrite; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.JavaElementLabels; @@ -121,7 +122,7 @@ protected ASTRewrite getRewrite() throws CoreException { MethodDeclaration methodDecl= (MethodDeclaration) declNode; Type origReturnType= methodDecl.getReturnType2(); rewrite.set(methodDecl, MethodDeclaration.RETURN_TYPE2_PROPERTY, type, null); - rewrite.set(methodDecl, MethodDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(methodDecl, MethodDeclaration.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); // add javadoc tag Javadoc javadoc= methodDecl.getJavadoc(); if (javadoc != null && origReturnType != null && origReturnType.isPrimitiveType() @@ -161,7 +162,7 @@ protected ASTRewrite getRewrite() throws CoreException { } } else { rewrite.set(fieldDecl, FieldDeclaration.TYPE_PROPERTY, type, null); - rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); } } else if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent; @@ -178,18 +179,18 @@ protected ASTRewrite getRewrite() throws CoreException { } } else { rewrite.set(varDecl, VariableDeclarationStatement.TYPE_PROPERTY, type, null); - rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); } } else if (parent instanceof VariableDeclarationExpression) { VariableDeclarationExpression varDecl= (VariableDeclarationExpression) parent; rewrite.set(varDecl, VariableDeclarationExpression.TYPE_PROPERTY, type, null); - rewrite.set(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(declNode, VariableDeclarationFragment.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); } } else if (declNode instanceof SingleVariableDeclaration) { SingleVariableDeclaration variableDeclaration= (SingleVariableDeclaration) declNode; rewrite.set(variableDeclaration, SingleVariableDeclaration.TYPE_PROPERTY, type, null); - rewrite.set(variableDeclaration, SingleVariableDeclaration.EXTRA_DIMENSIONS_PROPERTY, new Integer(0), null); + DimensionRewrite.removeAllChildren(declNode, SingleVariableDeclaration.EXTRA_DIMENSIONS2_PROPERTY, rewrite, null); } // set up linked mode diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavadocHover.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavadocHover.java index b0e49f9c82..51d45c3dc8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavadocHover.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavadocHover.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -84,12 +84,7 @@ import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.NodeFinder; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; @@ -1039,15 +1034,11 @@ private static String getAnnotations(IJavaElement element, ITypeRoot editorInput private static IBinding resolveBinding(ASTNode node) { if (node instanceof SimpleName) { - // workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method) SimpleName simpleName= (SimpleName) node; - StructuralPropertyDescriptor loc= simpleName.getLocationInParent(); - while (loc == QualifiedType.NAME_PROPERTY || loc == QualifiedName.NAME_PROPERTY|| loc == SimpleType.NAME_PROPERTY || loc == ParameterizedType.TYPE_PROPERTY) { - node= node.getParent(); - loc= node.getLocationInParent(); - } - if (loc == ClassInstanceCreation.TYPE_PROPERTY) { - ClassInstanceCreation cic= (ClassInstanceCreation) node.getParent(); + // workaround for https://bugs.eclipse.org/62605 (constructor name resolves to type, not method) + ASTNode normalized= ASTNodes.getNormalizedNode(simpleName); + if (normalized.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { + ClassInstanceCreation cic= (ClassInstanceCreation) normalized.getParent(); IMethodBinding constructorBinding= cic.resolveConstructorBinding(); if (constructorBinding == null) return null; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.java index 47d4f3212b..c35f09a4b1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.java @@ -34,6 +34,8 @@ private JavaDocMessages() { public static String JavaDoc2HTMLTextReader_since_section; public static String JavaDoc2HTMLTextReader_specified_by_section; public static String JavaDoc2HTMLTextReader_version_section; + public static String JavadocContentAccess2_getproperty_message; + public static String JavadocContentAccess2_setproperty_message; static { NLS.initializeMessages(BUNDLE_NAME, JavaDocMessages.class); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.properties index e957e8e5d9..ddad125af8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocMessages.properties @@ -20,3 +20,5 @@ JavaDoc2HTMLTextReader_see_section=See Also: JavaDoc2HTMLTextReader_since_section=Since: JavaDoc2HTMLTextReader_specified_by_section=Specified by: JavaDoc2HTMLTextReader_version_section=Version: +JavadocContentAccess2_getproperty_message=

    Gets the value of the property {0}.

    Property Description:
    {1}
    +JavadocContentAccess2_setproperty_message=

    Sets the value of the property {0}.

    Property Description:
    {1}
    diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavadocContentAccess2.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavadocContentAccess2.java index 48c1ae94ce..b0f69b2b56 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavadocContentAccess2.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavadocContentAccess2.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 IBM Corporation and others. + * Copyright (c) 2008, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -91,6 +91,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; +import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.corext.util.MethodOverrideTester; import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache; @@ -600,18 +601,58 @@ private static String getHTMLContentFromSource(IMember member) throws JavaModelE ISourceRange javadocRange= member.getJavadocRange(); if (javadocRange == null) { if (canInheritJavadoc(member)) { - // Try to use the inheritDoc algorithm. If it finds nothing (in source), return null. + // Try to use the inheritDoc algorithm. String inheritedJavadoc= javadoc2HTML(member, "/***/"); //$NON-NLS-1$ - return inheritedJavadoc != null && inheritedJavadoc.length() > 0 ? inheritedJavadoc : null; - } else { - return null; + if (inheritedJavadoc != null && inheritedJavadoc.length() > 0) { + return inheritedJavadoc; + } } + return getJavaFxPropertyDoc(member); } String rawJavadoc= buf.getText(javadocRange.getOffset(), javadocRange.getLength()); return javadoc2HTML(member, rawJavadoc); } + + private static String getJavaFxPropertyDoc(IMember member) throws JavaModelException { + // XXX: should not do this by default (but we don't have settings for Javadoc, see https://bugs.eclipse.org/424283 ) + if (member instanceof IMethod) { + String name= member.getElementName(); + boolean isGetter= name.startsWith("get"); //$NON-NLS-1$ + boolean isSetter= name.startsWith("set"); //$NON-NLS-1$ + boolean isProperty= name.endsWith("Property"); //$NON-NLS-1$ + if (isGetter || isSetter || isProperty) { + String propertyName= null; + if (isGetter || isSetter) { + propertyName= firstToLower(name.substring(3)); + } else { + propertyName= name.substring(0, name.length() - 8); + } + IType type= member.getDeclaringType(); + IField field= type.getField(propertyName); + if (field.exists()) { + String content= getHTMLContentFromSource(field); + if (content != null) { + if (isGetter) { + content= Messages.format(JavaDocMessages.JavadocContentAccess2_getproperty_message, new Object[] { propertyName, content }); + } else if (isSetter) { + content= Messages.format(JavaDocMessages.JavadocContentAccess2_setproperty_message, new Object[] { propertyName, content }); + } + } + return content; + } + } + } + return null; + } + + private static String firstToLower(String propertyName) { + char[] c = propertyName.toCharArray(); + c[0] = Character.toLowerCase(c[0]); + return String.valueOf(c); + } + private static Javadoc getJavadocNode(IJavaElement element, String rawJavadoc) { //FIXME: take from SharedASTProvider if available //Caveat: Javadoc nodes are not available when Javadoc processing has been disabled! diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SWTUtil.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SWTUtil.java index 7ecd76813e..bf6bf08b67 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SWTUtil.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SWTUtil.java @@ -26,6 +26,7 @@ import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; +import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import org.eclipse.core.runtime.Assert; @@ -151,5 +152,18 @@ public static GridLayout newLayoutNoMargins(int columns) { return layout; } + /** + * Fixes https://bugs.eclipse.org/71765 by setting the background + * color to {@code SWT.COLOR_WIDGET_BACKGROUND}. + *

    + * Should be applied to all SWT.READ_ONLY Texts in dialogs (or at least those which don't have an SWT.BORDER). + * Search regex: {@code new Text\([^,]+,[^\)]+SWT\.READ_ONLY} + * + * @param textField the text field + */ + public static void fixReadonlyTextBackground(Text textField) { + textField.setBackground(textField.getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + } + } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/BindingLabelProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/BindingLabelProvider.java index bc312f65a2..4316d3b0fc 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/BindingLabelProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/BindingLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -61,6 +61,11 @@ private static int getAdornmentFlags(IBinding binding) { adornments|= JavaElementImageDescriptor.SYNCHRONIZED; if (Modifier.isNative(modifiers)) adornments|= JavaElementImageDescriptor.NATIVE; + ITypeBinding type= ((IMethodBinding) binding).getDeclaringClass(); + if (type.isInterface() && !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers)) + adornments|= JavaElementImageDescriptor.DEFAULT_METHOD; + if (((IMethodBinding) binding).getDefaultValue() != null) + adornments|= JavaElementImageDescriptor.ANNOTATION_DEFAULT; } if (binding instanceof IVariableBinding && ((IVariableBinding) binding).isField()) { if (Modifier.isTransient(modifiers)) diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java index 82b66babca..65c26b3530 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -39,6 +39,7 @@ import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.ui.JavaElementImageDescriptor; @@ -361,7 +362,7 @@ private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { IMember member= (IMember)element; int modifiers= member.getFlags(); - if (Flags.isAbstract(modifiers) && confirmAbstract(member)) + if (confirmAbstract(member) && JdtFlags.isAbstract(member)) flags|= JavaElementImageDescriptor.ABSTRACT; if (Flags.isFinal(modifiers) || isInterfaceOrAnnotationField(member) || isEnumConstant(member, modifiers)) flags|= JavaElementImageDescriptor.FINAL; @@ -379,6 +380,10 @@ private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { flags|= JavaElementImageDescriptor.SYNCHRONIZED; if (Flags.isNative(modifiers)) flags|= JavaElementImageDescriptor.NATIVE; + if (Flags.isDefaultMethod(modifiers)) + flags|= JavaElementImageDescriptor.DEFAULT_METHOD; + if (Flags.isAnnnotationDefault(modifiers)) + flags|= JavaElementImageDescriptor.ANNOTATION_DEFAULT; } if (member.getElementType() == IJavaElement.TYPE) { @@ -405,11 +410,11 @@ private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { private static boolean confirmAbstract(IMember element) throws JavaModelException { - // never show the abstract symbol on interfaces or members in interfaces + // never show the abstract symbol on interfaces if (element.getElementType() == IJavaElement.TYPE) { return ! JavaModelUtil.isInterfaceOrAnnotation((IType) element); } - return ! JavaModelUtil.isInterfaceOrAnnotation(element.getDeclaringType()); + return true; } private static boolean isInterfaceOrAnnotationField(IMember element) throws JavaModelException { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabelComposer.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabelComposer.java index fa293a261d..934cbf6815 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabelComposer.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabelComposer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -40,10 +40,12 @@ import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeParameter; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.SourceRange; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; @@ -966,40 +968,62 @@ public void appendTypeLabel(IType type, long flags) { fBuffer.append('.'); } } + IJavaElement parent= type.getParent(); if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) { IType declaringType= type.getDeclaringType(); if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS)); fBuffer.append('.'); } - int parentType= type.getParent().getElementType(); + int parentType= parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local - appendElementLabel(type.getParent(), 0); + appendElementLabel(parent, 0); fBuffer.append('.'); } } String typeName= getElementName(type); - if (typeName.length() == 0) { // anonymous + + if (isLambdaType(type)) { + typeName= "() -> {...}"; //$NON-NLS-1$ try { - if (type.getParent() instanceof IField && type.isEnum()) { - typeName= '{' + JavaElementLabels.ELLIPSIS_STRING + '}'; - } else { - String supertypeName; - String[] superInterfaceSignatures= type.getSuperInterfaceTypeSignatures(); - if (superInterfaceSignatures.length > 0) { - supertypeName= getSimpleTypeName(type, superInterfaceSignatures[0]); - } else { - supertypeName= getSimpleTypeName(type, type.getSuperclassTypeSignature()); - } - typeName= Messages.format(JavaUIMessages.JavaElementLabels_anonym_type , supertypeName); + String[] superInterfaceSignatures= type.getSuperInterfaceTypeSignatures(); + if (superInterfaceSignatures.length > 0) { + typeName= typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]); } } catch (JavaModelException e) { //ignore - typeName= JavaUIMessages.JavaElementLabels_anonym; + } + + } else { + boolean isAnonymous; + try { + isAnonymous= type.isAnonymous(); + } catch (JavaModelException e1) { + isAnonymous= typeName.length() == 0; + } + if (isAnonymous) { + try { + if (parent instanceof IField && type.isEnum()) { + typeName= '{' + JavaElementLabels.ELLIPSIS_STRING + '}'; + } else { + String supertypeName; + String[] superInterfaceSignatures= type.getSuperInterfaceTypeSignatures(); + if (superInterfaceSignatures.length > 0) { + supertypeName= getSimpleTypeName(type, superInterfaceSignatures[0]); + } else { + supertypeName= getSimpleTypeName(type, type.getSuperclassTypeSignature()); + } + typeName= Messages.format(JavaUIMessages.JavaElementLabels_anonym_type , supertypeName); + } + } catch (JavaModelException e) { + //ignore + typeName= JavaUIMessages.JavaElementLabels_anonym; + } } } fBuffer.append(typeName); + if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) { if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) { BindingKey key= new BindingKey(type.getKey()); @@ -1033,12 +1057,32 @@ public void appendTypeLabel(IType type, long flags) { int offset= fBuffer.length(); fBuffer.append(JavaElementLabels.CONCAT_STRING); IType declaringType= type.getDeclaringType(); + if (declaringType == null && type.isBinary() && type.getElementName().length() == 0) { + // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type + String tqn= type.getTypeQualifiedName(); + int lastDollar= tqn.lastIndexOf('$'); + if (lastDollar != 1) { + String declaringTypeCF= tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$ + declaringType= type.getPackageFragment().getClassFile(declaringTypeCF).getType(); + try { + ISourceRange typeSourceRange= type.getSourceRange(); + if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) { + IJavaElement realParent= declaringType.getTypeRoot().getElementAt(typeSourceRange.getOffset() - 1); + if (realParent != null) { + parent= realParent; + } + } + } catch (JavaModelException e) { + // ignore + } + } + } if (declaringType != null) { appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS)); - int parentType= type.getParent().getElementType(); + int parentType= parent.getElementType(); if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD || parentType == IJavaElement.INITIALIZER) { // anonymous or local fBuffer.append('.'); - appendElementLabel(type.getParent(), 0); + appendElementLabel(parent, 0); } } else { appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS); @@ -1049,6 +1093,16 @@ public void appendTypeLabel(IType type, long flags) { } } + private static boolean isLambdaType(IType type) { + // TODO: use IType#isLambda() from bug 430195 + try { + IMethod[] methods= type.getMethods(); + return methods.length == 1 && methods[0].isLambdaMethod(); + } catch (JavaModelException e) { + return false; + } + } + /** * Returns the string for rendering the {@link IJavaElement#getElementName() element name} of * the given element. diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLinks.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLinks.java index 0f94af9f04..7050d65cb5 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLinks.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLinks.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2013 IBM Corporation and others. + * Copyright (c) 2008, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,12 +41,14 @@ import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache; import org.eclipse.jdt.ui.JavaElementLabels; import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.JavaUIMessages; /** @@ -173,9 +175,22 @@ protected String getLT() { @Override protected String getSimpleTypeName(IJavaElement enclosingElement, String typeSig) { String typeName= super.getSimpleTypeName(enclosingElement, typeSig); + + String title= ""; //$NON-NLS-1$ + String qualifiedName= Signature.toString(Signature.getTypeErasure(typeSig)); + int qualifierLength= qualifiedName.length() - typeName.length() - 1; + if (qualifierLength > 0) { + if (qualifiedName.endsWith(typeName)) { + title= qualifiedName.substring(0, qualifierLength); + title= Messages.format(JavaUIMessages.JavaElementLinks_title, title); + } else { + title= qualifiedName; // Not expected. Just show the whole qualifiedName. + } + } + try { - String uri= createURI(JAVADOC_SCHEME, enclosingElement, typeName, null, null); - return createHeaderLink(uri, typeName); + String uri= createURI(JAVADOC_SCHEME, enclosingElement, qualifiedName, null, null); + return createHeaderLink(uri, typeName, title); } catch (URISyntaxException e) { JavaPlugin.log(e); return typeName; @@ -638,7 +653,23 @@ public static String createLink(String uri, String label) { * @since 3.6 */ public static String createHeaderLink(String uri, String label) { - return "" + label + ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ + return createHeaderLink(uri, label, ""); //$NON-NLS-1$ + } + + /** + * Creates a link with the given URI, label and title text. + * + * @param uri the URI + * @param label the label + * @param title the title to be displayed while hovering over the link (can be empty) + * @return the HTML link + * @since 3.10 + */ + private static String createHeaderLink(String uri, String label, String title) { + if (title.length() > 0) { + title= " title='" + title + "'"; //$NON-NLS-1$ //$NON-NLS-2$ + } + return "" + label + ""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } /** diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties index aaf428525c..6a2715ec9f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2012 IBM Corporation and others. +# Copyright (c) 2000, 2013 IBM Corporation and others. # All rights reserved. This program and the accompanying materials # are made available under the terms of the Eclipse Public License v1.0 # which accompanies this distribution, and is available at @@ -112,7 +112,7 @@ NewTypeWizardPage_modifiers_acc_label=Modifiers: NewTypeWizardPage_modifiers_public=&public NewTypeWizardPage_modifiers_private=pri&vate NewTypeWizardPage_modifiers_protected=pro&tected -NewTypeWizardPage_modifiers_default=defa&ult +NewTypeWizardPage_modifiers_default=pa&ckage NewTypeWizardPage_modifiers_abstract=abs&tract NewTypeWizardPage_modifiers_final=fina&l NewTypeWizardPage_modifiers_static=stati&c @@ -163,7 +163,7 @@ NewClassWizardPage_description=Create a new Java class. NewClassWizardPage_methods_label=Which method stubs would you like to create? NewClassWizardPage_methods_main=public static &void main(String[] args) -NewClassWizardPage_methods_constructors=&Constructors from superclass +NewClassWizardPage_methods_constructors=Constr&uctors from superclass NewClassWizardPage_methods_inherited=In&herited abstract methods diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementImageDescriptor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementImageDescriptor.java index cdfd28a3a8..9cffc480f8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementImageDescriptor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementImageDescriptor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -103,6 +103,20 @@ public class JavaElementImageDescriptor extends CompositeImageDescriptor { */ public final static int IGNORE_OPTIONAL_PROBLEMS= 0x8000; + /** + * Flag to render the 'default' method adornment. + * + * @since 3.10 + */ + public final static int DEFAULT_METHOD= 0x10000; + + /** + * Flag to render the 'default' annotation adornment. + * + * @since 3.10 + */ + public final static int ANNOTATION_DEFAULT= 0x20000; + private ImageDescriptor fBaseImage; private int fFlags; private Point fSize; @@ -275,6 +289,12 @@ private void drawTopRight() { if ((fFlags & NATIVE) != 0) { addTopRightImage(JavaPluginImages.DESC_OVR_NATIVE, pos); } + if ((fFlags & DEFAULT_METHOD) != 0) { + addTopRightImage(JavaPluginImages.DESC_OVR_ANNOTATION_DEFAULT_METHOD, pos); + } + if ((fFlags & ANNOTATION_DEFAULT) != 0) { + addTopRightImage(JavaPluginImages.DESC_OVR_ANNOTATION_DEFAULT_METHOD, pos); + } } private void drawBottomRight() { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/SharedASTProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/SharedASTProvider.java index 6ac4a42cfb..c3f7aac2ba 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/SharedASTProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/SharedASTProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -31,7 +31,7 @@ *

    Clients can make the following assumptions about the AST: *

    *
  • the AST has a {@link ITypeRoot} as source: {@link CompilationUnit#getTypeRoot()} is not null.
  • - *
  • the {@link AST#apiLevel() AST API level} is {@link AST#JLS4 API level 4} or higher
  • + *
  • the {@link AST#apiLevel() AST API level} is {@link AST#JLS8 API level 8} or higher
  • *
  • the AST has bindings resolved ({@link AST#hasResolvedBindings()})
  • *
  • {@link AST#hasStatementsRecovery() statement} and {@link AST#hasBindingsRecovery() bindings} * recovery are enabled diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/CompletionProposalLabelProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/CompletionProposalLabelProvider.java index 09c8ef560f..1ffbae89a2 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/CompletionProposalLabelProvider.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/CompletionProposalLabelProvider.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2012 IBM Corporation and others. + * Copyright (c) 2005, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -724,15 +724,21 @@ private ImageDescriptor decorateImageDescriptor(ImageDescriptor descriptor, Comp if (deprecated) adornments |= JavaElementImageDescriptor.DEPRECATED; - if (kind == CompletionProposal.FIELD_REF || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE + if (kind == CompletionProposal.FIELD_REF || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE || kind == CompletionProposal.METHOD_REF || kind == CompletionProposal.CONSTRUCTOR_INVOCATION) if (Flags.isStatic(flags)) adornments |= JavaElementImageDescriptor.STATIC; - if (kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE || kind == CompletionProposal.METHOD_REF + if (kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE || kind == CompletionProposal.METHOD_REF || kind == CompletionProposal.CONSTRUCTOR_INVOCATION) if (Flags.isSynchronized(flags)) adornments |= JavaElementImageDescriptor.SYNCHRONIZED; + if (kind == CompletionProposal.METHOD_DECLARATION || kind == CompletionProposal.METHOD_NAME_REFERENCE || kind == CompletionProposal.METHOD_REF) + if (Flags.isDefaultMethod(flags)) + adornments|= JavaElementImageDescriptor.DEFAULT_METHOD; + if (kind == CompletionProposal.ANNOTATION_ATTRIBUTE_REF) + if (Flags.isAnnnotationDefault(flags)) + adornments|= JavaElementImageDescriptor.ANNOTATION_DEFAULT; if (kind == CompletionProposal.TYPE_REF && Flags.isAbstract(flags) && !Flags.isInterface(flags)) adornments |= JavaElementImageDescriptor.ABSTRACT; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/IInvocationContext.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/IInvocationContext.java index cea4250727..8f0e4a359a 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/IInvocationContext.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/IInvocationContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * Copyright (c) 2000, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -28,17 +28,17 @@ public interface IInvocationContext { /** - * @return Returns the current compilation unit. + * @return the current compilation unit */ ICompilationUnit getCompilationUnit(); /** - * @return Returns the offset of the current selection + * @return the offset of the current selection */ int getSelectionOffset(); /** - * @return Returns the length of the current selection + * @return the length of the current selection */ int getSelectionLength(); @@ -47,21 +47,30 @@ public interface IInvocationContext { * offset (see {@link org.eclipse.jdt.core.dom.ASTParser#setFocalPosition(int)}). * The returned AST is shared and therefore protected and cannot be modified. * The client must check the AST API level and do nothing if they are given an AST - * they can't handle. (see {@link org.eclipse.jdt.core.dom.AST#apiLevel()}). - * @return Returns the root of the AST corresponding to the current compilation unit. + * they can't handle. + * + * @see org.eclipse.jdt.core.dom.AST#apiLevel() + * @return the root of the AST corresponding to the current compilation unit */ CompilationUnit getASTRoot(); /** - * Convenience method to evaluate the AST node covering the current selection. - * @return Returns the node that covers the location of the problem + * If the AST contains nodes whose range is equal to the selection, returns the innermost of those nodes. + * Otherwise, returns the first node in a preorder traversal of the AST, where the complete node range is covered by the selection. + * + * @return the covered node, or null if the selection is empty or too short to cover an entire node */ - ASTNode getCoveringNode(); - + ASTNode getCoveredNode(); + /** - * Convenience method to evaluate the AST node that is covered by the current selection. - * @return Returns the node that is covered by the location of the problem + * Returns the innermost node that fully contains the selection. A node also contains the zero-length selection on either end. + *

    + * If more than one node covers the selection, the returned node is the last covering node found in a preorder traversal of the AST. + * This implies that for a zero-length selection between two adjacent sibling nodes, the node on the right is returned. + *

    + * + * @return the covering node */ - ASTNode getCoveredNode(); + ASTNode getCoveringNode(); } diff --git a/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/resource/ResourceRefactoringUndoTests.java b/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/resource/ResourceRefactoringUndoTests.java index e1ad620f33..90f9e72e17 100644 --- a/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/resource/ResourceRefactoringUndoTests.java +++ b/org.eclipse.ltk.core.refactoring.tests/src/org/eclipse/ltk/core/refactoring/tests/resource/ResourceRefactoringUndoTests.java @@ -179,25 +179,30 @@ public void testFolderRenameUndoRedoLTK() throws ExecutionException, CoreExcepti } public void testProjectRenameUndoRedoLTK() throws ExecutionException, CoreException { - RefactoringContribution renameContribution= RefactoringCore.getRefactoringContribution(RenameResourceDescriptor.ID); - RenameResourceDescriptor desc= (RenameResourceDescriptor) renameContribution.createDescriptor(); - desc.setResourcePath(fProject.getProject().getFullPath()); - desc.setNewName(TEST_NEWPROJECT_NAME); - PerformRefactoringOperation op= new PerformRefactoringOperation(desc.createRefactoringContext(new RefactoringStatus()), CheckConditionsOperation.ALL_CONDITIONS); - - ProjectSnapshot snap= new ProjectSnapshot(fProject.getProject()); - execute(op); - IProject renamedProject= getWorkspaceRoot().getProject(TEST_NEWPROJECT_NAME); - assertTrue("Project rename failed", renamedProject.exists()); - snap.name= TEST_NEWPROJECT_NAME; - assertTrue("Project CONTENT was altered on rename", snap.isValid()); - undo(); - snap.name= SimpleTestProject.TEST_PROJECT_NAME; - assertTrue("Project CONTENT was altered on undo rename", snap.isValid()); - assertFalse("Undo rename failed", renamedProject.exists()); - redo(); - snap.name= TEST_NEWPROJECT_NAME; - assertTrue("Project CONTENT was altered on redo rename", snap.isValid()); + IProject renamedProject= null; + try { + RefactoringContribution renameContribution= RefactoringCore.getRefactoringContribution(RenameResourceDescriptor.ID); + RenameResourceDescriptor desc= (RenameResourceDescriptor) renameContribution.createDescriptor(); + desc.setResourcePath(fProject.getProject().getFullPath()); + desc.setNewName(TEST_NEWPROJECT_NAME); + PerformRefactoringOperation op= new PerformRefactoringOperation(desc.createRefactoringContext(new RefactoringStatus()), CheckConditionsOperation.ALL_CONDITIONS); + + ProjectSnapshot snap= new ProjectSnapshot(fProject.getProject()); + execute(op); + renamedProject= getWorkspaceRoot().getProject(TEST_NEWPROJECT_NAME); + assertTrue("Project rename failed", renamedProject.exists()); + snap.name= TEST_NEWPROJECT_NAME; + assertTrue("Project CONTENT was altered on rename", snap.isValid()); + undo(); + snap.name= SimpleTestProject.TEST_PROJECT_NAME; + assertTrue("Project CONTENT was altered on undo rename", snap.isValid()); + assertFalse("Undo rename failed", renamedProject.exists()); + redo(); + snap.name= TEST_NEWPROJECT_NAME; + assertTrue("Project CONTENT was altered on redo rename", snap.isValid()); + } finally { + renamedProject.delete(true, true, null); + } } public void testFileDeleteUndoRedoLTK() throws ExecutionException, CoreException { diff --git a/org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/history/RefactoringHistoryControl.java b/org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/history/RefactoringHistoryControl.java index 3b6b94659e..e97c31ec93 100644 --- a/org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/history/RefactoringHistoryControl.java +++ b/org.eclipse.ltk.ui.refactoring/src/org/eclipse/ltk/internal/ui/refactoring/history/RefactoringHistoryControl.java @@ -413,6 +413,7 @@ protected Composite createDetailPane(final Composite parent) { createDetailLabel(composite); createSelectionLabel(composite); fDetailField= new Text(composite, SWT.BORDER | SWT.FLAT | SWT.MULTI | SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL); + fDetailField.setBackground(getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); fDetailField.setText(fControlConfiguration.getCommentCaption()); final GridData data= new GridData(GridData.FILL_HORIZONTAL | GridData.FILL_VERTICAL); data.horizontalSpan= getDetailColumns(); diff --git a/tests-pom/pom.xml b/tests-pom/pom.xml index 58d957b7ac..8d1ab0dc42 100644 --- a/tests-pom/pom.xml +++ b/tests-pom/pom.xml @@ -1,6 +1,6 @@