diff --git a/org.eclipse.jdt.ls.core/META-INF/MANIFEST.MF b/org.eclipse.jdt.ls.core/META-INF/MANIFEST.MF index 021f41b8ae..979274986b 100644 --- a/org.eclipse.jdt.ls.core/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ls.core/META-INF/MANIFEST.MF @@ -40,9 +40,7 @@ Export-Package: org.eclipse.jdt.ls.core.contentassist;x-friends:="org.eclipse.jd org.eclipse.jdt.ls.core.internal.corext.refactoring;x-internal:=true, org.eclipse.jdt.ls.core.internal.corext.refactoring.code;x-internal:=true, org.eclipse.jdt.ls.core.internal.corext.refactoring.rename;x-internal:=true, - org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg;x-internal:=true, org.eclipse.jdt.ls.core.internal.corext.template.java;x-friends:="org.eclipse.jdt.ls.tests", - org.eclipse.jdt.ls.core.internal.corext.util;x-internal:=true, org.eclipse.jdt.ls.core.internal.corrections;x-internal:=true, org.eclipse.jdt.ls.core.internal.corrections.proposals;x-internal:=true, org.eclipse.jdt.ls.core.internal.decompiler;x-friends:="org.eclipse.jdt.ls.tests", diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/RefactoringAvailabilityTester.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/RefactoringAvailabilityTester.java deleted file mode 100644 index 63c51d39c8..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/RefactoringAvailabilityTester.java +++ /dev/null @@ -1,1517 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2005, 2018 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTester - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring; - -import java.util.ArrayList; -import java.util.List; - -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaModel; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.ILocalVariable; -import org.eclipse.jdt.core.IMember; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IModuleDescription; -import org.eclipse.jdt.core.IPackageDeclaration; -import org.eclipse.jdt.core.IPackageFragment; -import org.eclipse.jdt.core.IPackageFragmentRoot; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeParameter; -import org.eclipse.jdt.core.ITypeRoot; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.SourceRange; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.NodeFinder; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.internal.corext.refactoring.Checks; -import org.eclipse.jdt.internal.corext.refactoring.rename.MethodChecks; -import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; -import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; -import org.eclipse.jdt.internal.corext.util.JdtFlags; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgUtils; - -/** - * Helper class to detect whether a certain refactoring can be enabled on a - * selection. - *

- * This class has been introduced to decouple actions from the refactoring code, - * in order not to eagerly load refactoring classes during action - * initialization. - *

- * - * @since 3.1 - */ -public final class RefactoringAvailabilityTester { - - public static IType getDeclaringType(IJavaElement element) { - if (element == null) { - return null; - } - if (!(element instanceof IType)) { - element = element.getAncestor(IJavaElement.TYPE); - } - return (IType) element; - } - - public static IJavaElement[] getJavaElements(final Object[] elements) { - List result = new ArrayList<>(); - for (int index = 0; index < elements.length; index++) { - if (elements[index] instanceof IJavaElement) { - result.add((IJavaElement) elements[index]); - } - } - return result.toArray(new IJavaElement[result.size()]); - } - - public static IMember[] getPullUpMembers(final IType type) throws JavaModelException { - final List list = new ArrayList<>(3); - if (type.exists()) { - IMember[] members = type.getFields(); - for (int index = 0; index < members.length; index++) { - if (isPullUpAvailable(members[index])) { - list.add(members[index]); - } - } - members = type.getMethods(); - for (int index = 0; index < members.length; index++) { - if (isPullUpAvailable(members[index])) { - list.add(members[index]); - } - } - members = type.getTypes(); - for (int index = 0; index < members.length; index++) { - if (isPullUpAvailable(members[index])) { - list.add(members[index]); - } - } - } - return list.toArray(new IMember[list.size()]); - } - - public static IMember[] getPushDownMembers(final IType type) throws JavaModelException { - final List list = new ArrayList<>(3); - if (type.exists()) { - IMember[] members = type.getFields(); - for (int index = 0; index < members.length; index++) { - if (isPushDownAvailable(members[index])) { - list.add(members[index]); - } - } - members = type.getMethods(); - for (int index = 0; index < members.length; index++) { - if (isPushDownAvailable(members[index])) { - list.add(members[index]); - } - } - } - return list.toArray(new IMember[list.size()]); - } - - public static IResource[] getResources(final Object[] elements) { - List result = new ArrayList<>(); - for (int index = 0; index < elements.length; index++) { - if (elements[index] instanceof IResource) { - result.add((IResource) elements[index]); - } - } - return result.toArray(new IResource[result.size()]); - } - - // public static IType getSingleSelectedType(IStructuredSelection selection) throws JavaModelException { - // Object first= selection.getFirstElement(); - // if (first instanceof IType) { - // return (IType) first; - // } - // if (first instanceof ICompilationUnit) { - // final ICompilationUnit unit= (ICompilationUnit) first; - // if (unit.exists()) { - // return JavaElementUtil.getMainType(unit); - // } - // } - // return null; - // } - - public static IType getTopLevelType(final IMember[] members) { - if (members != null && members.length == 1 && Checks.isTopLevelType(members[0])) { - return (IType) members[0]; - } - return null; - } - - public static boolean isChangeSignatureAvailable(final IMethod method) throws JavaModelException { - return (method != null) && Checks.isAvailable(method) && !Flags.isAnnotation(method.getDeclaringType().getFlags()); - } - - // public static boolean isChangeSignatureAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof IMethod) { - // final IMethod method= (IMethod) selection.getFirstElement(); - // return isChangeSignatureAvailable(method); - // } - // } - // return false; - // } - - // public static boolean isChangeSignatureAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length == 1 && (elements[0] instanceof IMethod)) { - // return isChangeSignatureAvailable((IMethod) elements[0]); - // } - // final IJavaElement element= selection.resolveEnclosingElement(); - // return (element instanceof IMethod) && isChangeSignatureAvailable((IMethod) element); - // } - - public static boolean isCommonDeclaringType(final IMember[] members) { - if (members.length == 0) { - return false; - } - final IType type = members[0].getDeclaringType(); - if (type == null) { - return false; - } - for (int index = 0; index < members.length; index++) { - if (!type.equals(members[index].getDeclaringType())) { - return false; - } - } - return true; - } - - // public static boolean isConvertAnonymousAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof IType) { - // return isConvertAnonymousAvailable((IType) selection.getFirstElement()); - // } - // } - // return false; - // } - - public static boolean isConvertAnonymousAvailable(final IType type) throws JavaModelException { - if (Checks.isAvailable(type)) { - final IJavaElement element = type.getParent(); - if (element instanceof IField && JdtFlags.isEnum((IMember) element)) { - return false; - } - return type.isAnonymous(); - } - return false; - } - - // public static boolean isConvertAnonymousAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IType type= RefactoringActions.getEnclosingType(selection); - // if (type != null) { - // return RefactoringAvailabilityTester.isConvertAnonymousAvailable(type); - // } - // return false; - // } - - // public static boolean isCopyAvailable(final IResource[] resources, final IJavaElement[] elements) throws JavaModelException { - // return ReorgPolicyFactory.createCopyPolicy(resources, elements).canEnable(); - // } - - public static boolean isDelegateCreationAvailable(final IField field) throws JavaModelException { - return field.exists() && (Flags.isStatic(field.getFlags()) && Flags.isFinal(field.getFlags()) /* - * && - * hasInitializer(field) - */); - } - - public static boolean isDeleteAvailable(final IJavaElement element) { - if (!element.exists()) { - return false; - } - if (element instanceof IJavaModel || element instanceof IJavaProject) { - return false; - } - if (element.getParent() != null && element.getParent().isReadOnly()) { - return false; - } - if (element instanceof IPackageFragmentRoot) { - IPackageFragmentRoot root = (IPackageFragmentRoot) element; - if (root.isExternal() || Checks.isClasspathDelete(root)) { - return false; - } - - if (root.getResource().equals(root.getJavaProject().getProject())) { - return false; - } - } - if (element instanceof IPackageFragment && ((IPackageFragment) element).isDefaultPackage()) { - return false; - } - if (element.getResource() == null && !RefactoringAvailabilityTester.isWorkingCopyElement(element)) { - return false; - } - if (element instanceof IMember && ((IMember) element).isBinary()) { - return false; - } - return true; - } - - public static boolean isDeleteAvailable(final IResource resource) { - if (!resource.exists() || resource.isPhantom()) { - return false; - } - if (resource.getType() == IResource.ROOT || resource.getType() == IResource.PROJECT) { - return false; - } - return true; - } - - // public static boolean isDeleteAvailable(final IStructuredSelection selection) { - // if (!selection.isEmpty()) { - // return isDeleteAvailable(selection.toArray()); - // } - // return false; - // } - - public static boolean isDeleteAvailable(final Object[] objects) { - if (objects.length != 0) { - // if (ReorgUtils.containsOnlyWorkingSets(Arrays.asList(objects))) { - // return true; - // } - final IResource[] resources = RefactoringAvailabilityTester.getResources(objects); - final IJavaElement[] elements = RefactoringAvailabilityTester.getJavaElements(objects); - - if (objects.length != resources.length + elements.length) { - return false; - } - for (int index = 0; index < resources.length; index++) { - if (!isDeleteAvailable(resources[index])) { - return false; - } - } - for (int index = 0; index < elements.length; index++) { - if (!isDeleteAvailable(elements[index])) { - return false; - } - } - return true; - } - return false; - } - - // public static boolean isExternalizeStringsAvailable(final IStructuredSelection selection) throws JavaModelException { - // for (Iterator iter= selection.iterator(); iter.hasNext();) { - // Object element= iter.next(); - // if (element instanceof IJavaElement) { - // IJavaElement javaElement= (IJavaElement)element; - // if (javaElement.exists() && !javaElement.isReadOnly()) { - // int elementType= javaElement.getElementType(); - // if (elementType == IJavaElement.PACKAGE_FRAGMENT) { - // return true; - // } else if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT) { - // IPackageFragmentRoot root= (IPackageFragmentRoot)javaElement; - // if (!root.isExternal() && !ReorgUtils.isClassFolder(root)) { - // return true; - // } - // } else if (elementType == IJavaElement.JAVA_PROJECT) { - // return true; - // } else if (elementType == IJavaElement.COMPILATION_UNIT) { - // ICompilationUnit cu= (ICompilationUnit)javaElement; - // if (cu.exists()) { - // return true; - // } - // } else if (elementType == IJavaElement.TYPE) { - // IJavaElement parent= ((IType) element).getParent(); - // if (parent instanceof ICompilationUnit && parent.exists()) { - // return true; - // } - // } - // } - // } else if (element instanceof IWorkingSet) { - // IWorkingSet workingSet= (IWorkingSet) element; - // return IWorkingSetIDs.JAVA.equals(workingSet.getId()); - // } - // } - // return false; - // } - - // public static boolean isExtractConstantAvailable(final JavaTextSelection selection) { - // return (selection.resolveInClassInitializer() || selection.resolveInMethodBody() || selection.resolveInVariableInitializer() || selection.resolveInAnnotation()) - // && Checks.isExtractableExpression(selection.resolveSelectedNodes(), selection.resolveCoveringNode()); - // } - - // public static boolean isExtractInterfaceAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // Object first= selection.getFirstElement(); - // if (first instanceof IType) { - // return isExtractInterfaceAvailable((IType) first); - // } else if (first instanceof ICompilationUnit) { - // ICompilationUnit unit= (ICompilationUnit) first; - // if (!unit.exists() || unit.isReadOnly()) { - // return false; - // } - // - // return true; - // } - // } - // return false; - // } - - public static boolean isExtractInterfaceAvailable(final IType type) throws JavaModelException { - return Checks.isAvailable(type) && !type.isBinary() && !type.isReadOnly() && !type.isAnnotation() && !type.isAnonymous() && !type.isLambda(); - } - - // public static boolean isExtractInterfaceAvailable(final JavaTextSelection selection) throws JavaModelException { - // return isExtractInterfaceAvailable(RefactoringActions.getEnclosingOrPrimaryType(selection)); - // } - - public static boolean isExtractMethodAvailable(final ASTNode[] nodes) { - if (nodes != null && nodes.length != 0) { - if (nodes.length == 1) { - return nodes[0] instanceof Statement || Checks.isExtractableExpression(nodes[0]); - } else { - for (int index = 0; index < nodes.length; index++) { - if (!(nodes[index] instanceof Statement)) { - return false; - } - } - return true; - } - } - return false; - } - - // public static boolean isExtractMethodAvailable(final JavaTextSelection selection) { - // return (selection.resolveInMethodBody() || selection.resolveInClassInitializer() || selection.resolveInVariableInitializer()) - // && !selection.resolveInAnnotation() - // && RefactoringAvailabilityTester.isExtractMethodAvailable(selection.resolveSelectedNodes()); - // } - - public static boolean isExtractSupertypeAvailable(IMember member) throws JavaModelException { - if (!member.exists()) { - return false; - } - final int type = member.getElementType(); - if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE) { - return false; - } - if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) { - return false; - } - if (!Checks.isAvailable(member)) { - return false; - } - if (member instanceof IMethod) { - final IMethod method = (IMethod) member; - if (method.isConstructor()) { - return false; - } - if (JdtFlags.isNative(method)) { - return false; - } - member = method.getDeclaringType(); - } else if (member instanceof IField) { - member = member.getDeclaringType(); - } - if (member instanceof IType) { - if (JdtFlags.isEnum(member) || JdtFlags.isAnnotation(member)) { - return false; - } - if (member.getDeclaringType() != null && !JdtFlags.isStatic(member)) { - return false; - } - if (((IType) member).isAnonymous()) { - return false; // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=253727 - } - if (((IType) member).isLambda()) { - return false; - } - } - return true; - } - - public static boolean isExtractSupertypeAvailable(final IMember[] members) throws JavaModelException { - if (members != null && members.length != 0) { - final IType type = getTopLevelType(members); - if (type != null && !type.isClass()) { - return false; - } - for (int index = 0; index < members.length; index++) { - if (!isExtractSupertypeAvailable(members[index])) { - return false; - } - } - return members.length == 1 || isCommonDeclaringType(members); - } - return false; - } - - // public static boolean isExtractSupertypeAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (!selection.isEmpty()) { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof ICompilationUnit) - // { - // return true; // Do not force opening - // } - // final IType type= getSingleSelectedType(selection); - // if (type != null) { - // return Checks.isAvailable(type) && isExtractSupertypeAvailable(new IType[] { type}); - // } - // } - // for (final Iterator iterator= selection.iterator(); iterator.hasNext();) { - // if (!(iterator.next() instanceof IMember)) { - // return false; - // } - // } - // final Set members= new HashSet<>(); - // @SuppressWarnings("unchecked") - // List selectionList= (List) (List) Arrays.asList(selection.toArray()); - // members.addAll(selectionList); - // return isExtractSupertypeAvailable(members.toArray(new IMember[members.size()])); - // } - // return false; - // } - - // public static boolean isExtractSupertypeAvailable(final JavaTextSelection selection) throws JavaModelException { - // IJavaElement element= selection.resolveEnclosingElement(); - // if (!(element instanceof IMember)) { - // return false; - // } - // return isExtractSupertypeAvailable(new IMember[] { (IMember) element}); - // } - - // public static boolean isExtractTempAvailable(final JavaTextSelection selection) { - // final ASTNode[] nodes= selection.resolveSelectedNodes(); - // return (selection.resolveInMethodBody() || selection.resolveInClassInitializer()) - // && !selection.resolveInAnnotation() - // && (Checks.isExtractableExpression(nodes, selection.resolveCoveringNode()) || (nodes != null && nodes.length == 1 && nodes[0] instanceof ExpressionStatement)); - // } - - public static boolean isGeneralizeTypeAvailable(final IJavaElement element) throws JavaModelException { - if (element != null && element.exists()) { - String type = null; - if (element instanceof IMethod) { - type = ((IMethod) element).getReturnType(); - } else if (element instanceof IField) { - final IField field = (IField) element; - if (JdtFlags.isEnum(field)) { - return false; - } - type = field.getTypeSignature(); - } else if (element instanceof ILocalVariable) { - return true; - } else if (element instanceof IType) { - final IType clazz = (IType) element; - if (JdtFlags.isEnum(clazz)) { - return false; - } - return true; - } - if (type == null || PrimitiveType.toCode(Signature.toString(type)) != null) { - return false; - } - return true; - } - return false; - } - - // public static boolean isGeneralizeTypeAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // final Object element= selection.getFirstElement(); - // if (element instanceof IMethod) { - // final IMethod method= (IMethod) element; - // if (!method.exists()) { - // return false; - // } - // final String type= method.getReturnType(); - // if (PrimitiveType.toCode(Signature.toString(type)) == null) { - // return Checks.isAvailable(method); - // } - // } else if (element instanceof IField) { - // final IField field= (IField) element; - // if (!field.exists()) { - // return false; - // } - // if (!JdtFlags.isEnum(field)) { - // return Checks.isAvailable(field); - // } - // } - // } - // return false; - // } - - // public static boolean isGeneralizeTypeAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // return isGeneralizeTypeAvailable(elements[0]); - // } - - public static boolean isInferTypeArgumentsAvailable(final IJavaElement element) throws JavaModelException { - if (!Checks.isAvailable(element)) { - return false; - } else if (element instanceof IJavaProject) { - IJavaProject project = (IJavaProject) element; - IClasspathEntry[] classpathEntries = project.getRawClasspath(); - for (int i = 0; i < classpathEntries.length; i++) { - if (classpathEntries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) { - return true; - } - } - return false; - } else if (element instanceof IPackageFragmentRoot) { - return ((IPackageFragmentRoot) element).getKind() == IPackageFragmentRoot.K_SOURCE; - } else if (element instanceof IPackageFragment) { - return ((IPackageFragment) element).getKind() == IPackageFragmentRoot.K_SOURCE; - } else if (element instanceof ICompilationUnit) { - return true; - } else if (element.getAncestor(IJavaElement.COMPILATION_UNIT) != null) { - return true; - } else { - return false; - } - } - - public static boolean isInferTypeArgumentsAvailable(final IJavaElement[] elements) throws JavaModelException { - if (elements.length == 0) { - return false; - } - - for (int i = 0; i < elements.length; i++) { - if (!(isInferTypeArgumentsAvailable(elements[i]))) { - return false; - } - } - return true; - } - - // public static boolean isInferTypeArgumentsAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.isEmpty()) { - // return false; - // } - // - // for (Iterator iter= selection.iterator(); iter.hasNext();) { - // Object element= iter.next(); - // if (!(element instanceof IJavaElement)) { - // return false; - // } - // if (element instanceof ICompilationUnit) { - // ICompilationUnit unit= (ICompilationUnit) element; - // if (!unit.exists() || unit.isReadOnly()) { - // return false; - // } - // - // return true; - // } - // if (!isInferTypeArgumentsAvailable((IJavaElement) element)) { - // return false; - // } - // } - // return true; - // } - - public static boolean isInlineConstantAvailable(final IField field) throws JavaModelException { - return Checks.isAvailable(field) && JdtFlags.isStatic(field) && JdtFlags.isFinal(field) && !JdtFlags.isEnum(field); - } - - // public static boolean isInlineConstantAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.isEmpty() || selection.size() != 1) { - // return false; - // } - // final Object first= selection.getFirstElement(); - // return (first instanceof IField) && isInlineConstantAvailable(((IField) first)); - // } - // - // public static boolean isInlineConstantAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // return (elements[0] instanceof IField) && isInlineConstantAvailable(((IField) elements[0])); - // } - - public static boolean isInlineMethodAvailable(IMethod method) throws JavaModelException { - if (method == null) { - return false; - } - if (!method.exists()) { - return false; - } - if (!method.isStructureKnown()) { - return false; - } - if (!method.isBinary()) { - return true; - } - if (method.isConstructor()) { - return false; - } - return SourceRange.isAvailable(method.getNameRange()); - } - - // public static boolean isInlineMethodAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.isEmpty() || selection.size() != 1) { - // return false; - // } - // final Object first= selection.getFirstElement(); - // return (first instanceof IMethod) && isInlineMethodAvailable(((IMethod) first)); - // } - // - // public static boolean isInlineMethodAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // IJavaElement enclosingElement= selection.resolveEnclosingElement(); - // if (!(enclosingElement instanceof IMember)) { - // return false; - // } - // ITypeRoot typeRoot= ((IMember)enclosingElement).getTypeRoot(); - // CompilationUnit compilationUnit= selection.resolvePartialAstAtOffset(); - // if (compilationUnit == null) { - // return false; - // } - // return getInlineableMethodNode(typeRoot, compilationUnit, selection.getOffset(), selection.getLength()) != null; - // } - // IJavaElement element= elements[0]; - // if (!(element instanceof IMethod)) { - // return false; - // } - // IMethod method= (IMethod) element; - // if (!isInlineMethodAvailable((method))) { - // return false; - // } - // - // // in binary class, only activate for method declarations - // IJavaElement enclosingElement= selection.resolveEnclosingElement(); - // if (enclosingElement == null || enclosingElement.getAncestor(IJavaElement.CLASS_FILE) == null) { - // return true; - // } - // if (!(enclosingElement instanceof IMethod)) { - // return false; - // } - // IMethod enclosingMethod= (IMethod) enclosingElement; - // if (enclosingMethod.isConstructor()) { - // return false; - // } - // int nameOffset= enclosingMethod.getNameRange().getOffset(); - // int nameLength= enclosingMethod.getNameRange().getLength(); - // return (nameOffset <= selection.getOffset()) && (selection.getOffset() + selection.getLength() <= nameOffset + nameLength); - // } - - public static ASTNode getInlineableMethodNode(ITypeRoot typeRoot, CompilationUnit root, int offset, int length) { - ASTNode node = null; - try { - node = getInlineableMethodNode(NodeFinder.perform(root, offset, length, typeRoot), typeRoot); - } catch (JavaModelException e) { - // Do nothing - } - if (node != null) { - return node; - } - return getInlineableMethodNode(NodeFinder.perform(root, offset, length), typeRoot); - } - - private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) { - if (node == null) { - return null; - } - switch (node.getNodeType()) { - case ASTNode.SIMPLE_NAME: - StructuralPropertyDescriptor locationInParent = node.getLocationInParent(); - if (locationInParent == MethodDeclaration.NAME_PROPERTY) { - return node.getParent(); - } else if (locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY) { - return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary - } - return null; - case ASTNode.EXPRESSION_STATEMENT: - node = ((ExpressionStatement) node).getExpression(); - } - switch (node.getNodeType()) { - case ASTNode.METHOD_DECLARATION: - return node; - case ASTNode.METHOD_INVOCATION: - case ASTNode.SUPER_METHOD_INVOCATION: - case ASTNode.CONSTRUCTOR_INVOCATION: - return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary - } - return null; - } - - public static boolean isInlineTempAvailable(final ILocalVariable variable) throws JavaModelException { - return Checks.isAvailable(variable); - } - - // public static boolean isInlineTempAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // return (elements[0] instanceof ILocalVariable) && isInlineTempAvailable((ILocalVariable) elements[0]); - // } - - public static boolean isIntroduceFactoryAvailable(final IMethod method) throws JavaModelException { - return Checks.isAvailable(method) && method.isConstructor(); - } - - // public static boolean isIntroduceFactoryAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1 && selection.getFirstElement() instanceof IMethod) { - // return isIntroduceFactoryAvailable((IMethod) selection.getFirstElement()); - // } - // return false; - // } - // - // public static boolean isIntroduceFactoryAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length == 1 && elements[0] instanceof IMethod) { - // return isIntroduceFactoryAvailable((IMethod) elements[0]); - // } - // - // // there's no IMethod for the default constructor - // if (!Checks.isAvailable(selection.resolveEnclosingElement())) { - // return false; - // } - // ASTNode node= selection.resolveCoveringNode(); - // if (node == null) { - // ASTNode[] selectedNodes= selection.resolveSelectedNodes(); - // if (selectedNodes != null && selectedNodes.length == 1) { - // node= selectedNodes[0]; - // if (node == null) { - // return false; - // } - // } else { - // return false; - // } - // } - // - // if (node.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { - // return true; - // } - // - // node= ASTNodes.getNormalizedNode(node); - // if (node.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { - // return true; - // } - // - // return false; - // } - - public static boolean isIntroduceIndirectionAvailable(IMethod method) throws JavaModelException { - if (method == null) { - return false; - } - if (!method.exists()) { - return false; - } - if (!method.isStructureKnown()) { - return false; - } - if (method.isConstructor()) { - return false; - } - if (method.getDeclaringType().isAnnotation()) { - return false; - } - if (JavaModelUtil.isPolymorphicSignature(method)) { - return false; - } - - return true; - } - - // public static boolean isIntroduceIndirectionAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.isEmpty() || selection.size() != 1) { - // return false; - // } - // final Object first= selection.getFirstElement(); - // return (first instanceof IMethod) && isIntroduceIndirectionAvailable(((IMethod) first)); - // } - // - // public static boolean isIntroduceIndirectionAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length == 1) { - // return (elements[0] instanceof IMethod) && isIntroduceIndirectionAvailable(((IMethod) elements[0])); - // } - // ASTNode[] selectedNodes= selection.resolveSelectedNodes(); - // if (selectedNodes == null || selectedNodes.length != 1) { - // return false; - // } - // switch (selectedNodes[0].getNodeType()) { - // case ASTNode.METHOD_DECLARATION: - // case ASTNode.METHOD_INVOCATION: - // case ASTNode.SUPER_METHOD_INVOCATION: - // return true; - // default: - // return false; - // } - // } - - public static boolean isIntroduceParameterAvailable(final ASTNode[] selectedNodes, ASTNode coveringNode) { - return Checks.isExtractableExpression(selectedNodes, coveringNode); - } - - // public static boolean isIntroduceParameterAvailable(final JavaTextSelection selection) { - // return selection.resolveInMethodBody() - // && !selection.resolveInAnnotation() - // && isIntroduceParameterAvailable(selection.resolveSelectedNodes(), selection.resolveCoveringNode()); - // } - - public static boolean isMoveAvailable(final IResource[] resources, final IJavaElement[] elements) throws JavaModelException { - if (elements != null) { - for (int index = 0; index < elements.length; index++) { - IJavaElement element = elements[index]; - if (element == null || !element.exists()) { - return false; - } - if ((element instanceof IType) && ((IType) element).isLocal()) { - return false; - } - if ((element instanceof IPackageDeclaration)) { - return false; - } - if (element instanceof IField && JdtFlags.isEnum((IMember) element)) { - return false; - } - } - } - return ReorgPolicyFactory.createMovePolicy(resources, elements).canEnable(); - } - // - // public static boolean isMoveAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement element= selection.resolveEnclosingElement(); - // if (element == null) { - // return false; - // } - // return isMoveAvailable(new IResource[0], new IJavaElement[] { element}); - // } - // - // public static boolean isMoveInnerAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // Object first= selection.getFirstElement(); - // if (first instanceof IType) { - // return isMoveInnerAvailable((IType) first); - // } - // } - // return false; - // } - - public static boolean isMoveInnerAvailable(final IType type) throws JavaModelException { - return Checks.isAvailable(type) && !Checks.isAnonymous(type) && !JavaElementUtil.isMainType(type) && !Checks.isInsideLocalType(type); - } - // - // public static boolean isMoveInnerAvailable(final JavaTextSelection selection) throws JavaModelException { - // IType type= RefactoringAvailabilityTester.getDeclaringType(selection.resolveEnclosingElement()); - // if (type == null) { - // return false; - // } - // return isMoveInnerAvailable(type); - // } - - public static boolean isMoveMethodAvailable(final IMethod method) throws JavaModelException { - return method.exists() && !method.isConstructor() && !method.isBinary() && !method.isReadOnly() && !JdtFlags.isStatic(method) && (JdtFlags.isDefaultMethod(method) || !method.getDeclaringType().isInterface()); - } - - // public static boolean isMoveMethodAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // final Object first= selection.getFirstElement(); - // return first instanceof IMethod && isMoveMethodAvailable((IMethod) first); - // } - // return false; - // } - // - // public static boolean isMoveMethodAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement method= selection.resolveEnclosingElement(); - // if (!(method instanceof IMethod)) { - // return false; - // } - // return isMoveMethodAvailable((IMethod) method); - // } - - public static boolean isMoveStaticAvailable(final IMember member) throws JavaModelException { - if (!member.exists()) { - return false; - } - final int type = member.getElementType(); - if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE) { - return false; - } - if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) { - return false; - } - final IType declaring = member.getDeclaringType(); - if (declaring == null) { - return false; - } - if (!Checks.isAvailable(member)) { - return false; - } - if (type == IJavaElement.METHOD && declaring.isInterface()) { - boolean is1d8OrHigher = JavaModelUtil.is1d8OrHigher(member.getJavaProject()); - if (!is1d8OrHigher || !Flags.isStatic(member.getFlags())) { - return false; - } - } - if (type == IJavaElement.METHOD && !JdtFlags.isStatic(member)) { - return false; - } - if (type == IJavaElement.METHOD && ((IMethod) member).isConstructor()) { - return false; - } - if (type == IJavaElement.TYPE && !JdtFlags.isStatic(member)) { - return false; - } - if (!declaring.isInterface() && !JdtFlags.isStatic(member)) { - return false; - } - return true; - } - - public static boolean isMoveStaticAvailable(final IMember[] members) throws JavaModelException { - for (int index = 0; index < members.length; index++) { - if (!isMoveStaticAvailable(members[index])) { - return false; - } - } - return true; - } - - // public static boolean isMoveStaticAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement element= selection.resolveEnclosingElement(); - // if (!(element instanceof IMember)) { - // return false; - // } - // return RefactoringAvailabilityTester.isMoveStaticMembersAvailable(new IMember[] { (IMember) element}); - // } - - public static boolean isMoveStaticMembersAvailable(final IMember[] members) throws JavaModelException { - if (members == null) { - return false; - } - if (members.length == 0) { - return false; - } - if (!isMoveStaticAvailable(members)) { - return false; - } - if (!isCommonDeclaringType(members)) { - return false; - } - return true; - } - - public static boolean isPromoteTempAvailable(final ILocalVariable variable) throws JavaModelException { - return Checks.isAvailable(variable); - } - - // public static boolean isPromoteTempAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // return (elements[0] instanceof ILocalVariable) && isPromoteTempAvailable((ILocalVariable) elements[0]); - // } - - public static boolean isPullUpAvailable(IMember member) throws JavaModelException { - if (!member.exists()) { - return false; - } - final int type = member.getElementType(); - if (type != IJavaElement.METHOD && type != IJavaElement.FIELD && type != IJavaElement.TYPE) { - return false; - } - if (JdtFlags.isEnum(member) && type != IJavaElement.TYPE) { - return false; - } - if (!Checks.isAvailable(member)) { - return false; - } - if (member instanceof IType) { - if (!JdtFlags.isStatic(member) && !JdtFlags.isEnum(member) && !JdtFlags.isAnnotation(member)) { - return false; - } - } - if (member instanceof IMethod) { - final IMethod method = (IMethod) member; - if (method.isConstructor()) { - return false; - } - if (JdtFlags.isNative(method)) { - return false; - } - final IType declaring = method.getDeclaringType(); - if (declaring != null && declaring.isAnnotation()) { - return false; - } - } - return true; - } - - public static boolean isPullUpAvailable(final IMember[] members) throws JavaModelException { - if (members != null && members.length != 0) { - final IType type = getTopLevelType(members); - if (type != null && getPullUpMembers(type).length != 0) { - return true; - } - for (int index = 0; index < members.length; index++) { - if (!isPullUpAvailable(members[index])) { - return false; - } - } - return isCommonDeclaringType(members); - } - return false; - } - - // public static boolean isPullUpAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (!selection.isEmpty()) { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof ICompilationUnit) - // { - // return true; // Do not force opening - // } - // final IType type= getSingleSelectedType(selection); - // if (type != null) { - // return Checks.isAvailable(type) && isPullUpAvailable(new IType[] { type}); - // } - // } - // for (final Iterator iterator= selection.iterator(); iterator.hasNext();) { - // if (!(iterator.next() instanceof IMember)) { - // return false; - // } - // } - // final Set members= new HashSet<>(); - // @SuppressWarnings("unchecked") - // List selectionList= (List) (List) Arrays.asList(selection.toArray()); - // members.addAll(selectionList); - // return isPullUpAvailable(members.toArray(new IMember[members.size()])); - // } - // return false; - // } - // - // public static boolean isPullUpAvailable(final JavaTextSelection selection) throws JavaModelException { - // IJavaElement element= selection.resolveEnclosingElement(); - // if (!(element instanceof IMember)) { - // return false; - // } - // return isPullUpAvailable(new IMember[] { (IMember) element}); - // } - - public static boolean isPushDownAvailable(final IMember member) throws JavaModelException { - if (!member.exists()) { - return false; - } - final int type = member.getElementType(); - if (type != IJavaElement.METHOD && type != IJavaElement.FIELD) { - return false; - } - if (JdtFlags.isEnum(member)) { - return false; - } - if (!Checks.isAvailable(member)) { - return false; - } - if (JdtFlags.isStatic(member)) { - return false; - } - if (type == IJavaElement.METHOD) { - final IMethod method = (IMethod) member; - if (method.isConstructor()) { - return false; - } - if (JdtFlags.isNative(method)) { - return false; - } - final IType declaring = method.getDeclaringType(); - if (declaring != null && declaring.isAnnotation()) { - return false; - } - } - return true; - } - - public static boolean isPushDownAvailable(final IMember[] members) throws JavaModelException { - if (members != null && members.length != 0) { - final IType type = getTopLevelType(members); - if (type != null && RefactoringAvailabilityTester.getPushDownMembers(type).length != 0) { - return true; - } - if (type != null && JdtFlags.isEnum(type)) { - return false; - } - for (int index = 0; index < members.length; index++) { - if (!isPushDownAvailable(members[index])) { - return false; - } - } - return isCommonDeclaringType(members); - } - return false; - } - - // public static boolean isPushDownAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (!selection.isEmpty()) { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof ICompilationUnit) - // { - // return true; // Do not force opening - // } - // final IType type= getSingleSelectedType(selection); - // if (type != null) { - // return isPushDownAvailable(new IType[] { type}); - // } - // } - // for (final Iterator iterator= selection.iterator(); iterator.hasNext();) { - // if (!(iterator.next() instanceof IMember)) { - // return false; - // } - // } - // final Set members= new HashSet<>(); - // @SuppressWarnings("unchecked") - // List selectionList= (List) (List) Arrays.asList(selection.toArray()); - // members.addAll(selectionList); - // return isPushDownAvailable(members.toArray(new IMember[members.size()])); - // } - // return false; - // } - // - // public static boolean isPushDownAvailable(final JavaTextSelection selection) throws JavaModelException { - // IJavaElement element= selection.resolveEnclosingElement(); - // if (!(element instanceof IMember)) { - // return false; - // } - // return isPullUpAvailable(new IMember[] { (IMember) element}); - // } - - public static boolean isRenameAvailable(final ICompilationUnit unit) { - if (unit == null) { - return false; - } - if (!unit.exists()) { - return false; - } - if (!JavaModelUtil.isPrimary(unit)) { - return false; - } - if (unit.isReadOnly()) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IJavaProject project) throws JavaModelException { - if (project == null) { - return false; - } - if (!Checks.isAvailable(project)) { - return false; - } - if (!project.isConsistent()) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IModuleDescription module) throws JavaModelException { - return Checks.isAvailable(module); - } - - public static boolean isRenameAvailable(final ILocalVariable variable) throws JavaModelException { - return Checks.isAvailable(variable); - } - - public static boolean isRenameAvailable(final IMethod method) throws CoreException { - if (method == null) { - return false; - } - if (!Checks.isAvailable(method)) { - return false; - } - if (method.isConstructor()) { - return false; - } - if (isRenameProhibited(method)) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IPackageFragment fragment) throws JavaModelException { - if (fragment == null) { - return false; - } - if (!Checks.isAvailable(fragment)) { - return false; - } - if (fragment.isDefaultPackage()) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IPackageFragmentRoot root) throws JavaModelException { - if (root == null) { - return false; - } - if (!Checks.isAvailable(root)) { - return false; - } - if (root.isArchive()) { - return false; - } - if (root.isExternal()) { - return false; - } - if (!root.isConsistent()) { - return false; - } - if (root.getResource() instanceof IProject) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IResource resource) { - if (resource == null) { - return false; - } - if (!resource.exists()) { - return false; - } - if (!resource.isAccessible()) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final IType type) throws JavaModelException { - if (type == null) { - return false; - } - if (type.isAnonymous()) { - return false; - } - if (type.isLambda()) { - return false; - } - if (!Checks.isAvailable(type)) { - return false; - } - if (isRenameProhibited(type)) { - return false; - } - return true; - } - - public static boolean isRenameAvailable(final ITypeParameter parameter) throws JavaModelException { - return Checks.isAvailable(parameter); - } - - public static boolean isRenameEnumConstAvailable(final IField field) throws JavaModelException { - return Checks.isAvailable(field) && field.getDeclaringType().isEnum(); - } - - public static boolean isRenameFieldAvailable(final IField field) throws JavaModelException { - return Checks.isAvailable(field) && !JdtFlags.isEnum(field); - } - - public static boolean isRenameModuleAvailable(final IModuleDescription module) throws JavaModelException { - return Checks.isAvailable(module); - } - - public static boolean isRenameNonVirtualMethodAvailable(final IMethod method) throws JavaModelException, CoreException { - return isRenameAvailable(method) && !MethodChecks.isVirtual(method); - } - - public static boolean isRenameProhibited(final IMethod method) throws CoreException { - if (method.getElementName().equals("toString") //$NON-NLS-1$ - && (method.getNumberOfParameters() == 0) && (method.getReturnType().equals("Ljava.lang.String;") //$NON-NLS-1$ - || method.getReturnType().equals("QString;") //$NON-NLS-1$ - || method.getReturnType().equals("Qjava.lang.String;"))) { - return true; - } else { - return false; - } - } - - public static boolean isRenameProhibited(final IType type) { - return type.getPackageFragment().getElementName().equals("java.lang"); //$NON-NLS-1$ - } - - public static boolean isRenameVirtualMethodAvailable(final IMethod method) throws CoreException { - return isRenameAvailable(method) && MethodChecks.isVirtual(method); - } - - public static boolean isRenameElementAvailable(IJavaElement element) throws CoreException { - return isRenameElementAvailable(element, false); - } - - public static boolean isRenameElementAvailable(IJavaElement element, boolean isTextSelection) throws CoreException { - if (element != null) { - switch (element.getElementType()) { - case IJavaElement.JAVA_PROJECT: - return isRenameAvailable((IJavaProject) element); - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - return isRenameAvailable((IPackageFragmentRoot) element); - case IJavaElement.PACKAGE_FRAGMENT: - return isRenameAvailable((IPackageFragment) element); - case IJavaElement.COMPILATION_UNIT: - return isRenameAvailable((ICompilationUnit) element); - case IJavaElement.TYPE: - return isRenameAvailable((IType) element); - case IJavaElement.METHOD: - final IMethod method = (IMethod) element; - if (method.isConstructor()) { - return isRenameAvailable(method.getDeclaringType()); - } else { - return isRenameAvailable(method); - } - case IJavaElement.FIELD: - final IField field = (IField) element; - if (Flags.isEnum(field.getFlags())) { - return isRenameEnumConstAvailable(field); - } else { - return isRenameFieldAvailable(field); - } - case IJavaElement.TYPE_PARAMETER: - return isRenameAvailable((ITypeParameter) element); - case IJavaElement.LOCAL_VARIABLE: - return isRenameAvailable((ILocalVariable) element); - case IJavaElement.JAVA_MODULE: { - return isRenameAvailable((IModuleDescription) element); - } - default: - break; - } - } - return false; - } - - public static boolean isReplaceInvocationsAvailable(IMethod method) throws JavaModelException { - if (method == null) { - return false; - } - if (!method.exists()) { - return false; - } - if (method.isConstructor()) { - return false; - } - return true; - } - - // public static boolean isReplaceInvocationsAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.isEmpty() || selection.size() != 1) { - // return false; - // } - // final Object first= selection.getFirstElement(); - // return (first instanceof IMethod) && isReplaceInvocationsAvailable(((IMethod) first)); - // } - // - // public static boolean isReplaceInvocationsAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // IJavaElement element= elements[0]; - // return (element instanceof IMethod) && isReplaceInvocationsAvailable(((IMethod) element)); - // } - - public static boolean isSelfEncapsulateAvailable(IField field) throws JavaModelException { - return Checks.isAvailable(field) && !JdtFlags.isEnum(field) && !field.getDeclaringType().isInterface(); - } - - // public static boolean isSelfEncapsulateAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // if (selection.getFirstElement() instanceof IField) { - // final IField field= (IField) selection.getFirstElement(); - // return isSelfEncapsulateAvailable(field); - // } - // } - // return false; - // } - // - // public static boolean isSelfEncapsulateAvailable(final JavaTextSelection selection) throws JavaModelException { - // final IJavaElement[] elements= selection.resolveElementAtOffset(); - // if (elements.length != 1) { - // return false; - // } - // return (elements[0] instanceof IField) && isSelfEncapsulateAvailable((IField) elements[0]); - // } - // - // public static boolean isUseSuperTypeAvailable(final IStructuredSelection selection) throws JavaModelException { - // if (selection.size() == 1) { - // final Object first= selection.getFirstElement(); - // if (first instanceof IType) { - // return isUseSuperTypeAvailable((IType) first); - // } else if (first instanceof ICompilationUnit) { - // ICompilationUnit unit= (ICompilationUnit) first; - // if (!unit.exists() || unit.isReadOnly()) { - // return false; - // } - // - // return true; - // } - // } - // return false; - // } - - public static boolean isUseSuperTypeAvailable(final IType type) throws JavaModelException { - return type != null && type.exists() && !type.isAnnotation() && !type.isAnonymous() && !type.isLambda(); - } - - // public static boolean isUseSuperTypeAvailable(final JavaTextSelection selection) throws JavaModelException { - // return isUseSuperTypeAvailable(RefactoringActions.getEnclosingOrPrimaryType(selection)); - // } - - public static boolean isWorkingCopyElement(final IJavaElement element) { - if (element instanceof ICompilationUnit) { - return ((ICompilationUnit) element).isWorkingCopy(); - } - if (ReorgUtils.isInsideCompilationUnit(element)) { - return ReorgUtils.getCompilationUnit(element).isWorkingCopy(); - } - return false; - } - - private RefactoringAvailabilityTester() { - // Not for instantiation - } - - // public static boolean isIntroduceParameterObjectAvailable(IStructuredSelection selection) throws JavaModelException{ - // return isChangeSignatureAvailable(selection); //TODO test selected element for more than 1 parameter? - // } - // - // public static boolean isIntroduceParameterObjectAvailable(JavaTextSelection selection) throws JavaModelException{ - // return isChangeSignatureAvailable(selection); //TODO test selected element for more than 1 parameter? - // } - - public static boolean isExtractClassAvailable(IType type) throws JavaModelException { - if (type == null) { - return false; - } - if (!type.exists()) { - return false; - } - return ReorgUtils.isInsideCompilationUnit(type) && type.isClass() && !type.isAnonymous() && !type.isLambda(); - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExceptionAnalyzer.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExceptionAnalyzer.java deleted file mode 100644 index 653700c850..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExceptionAnalyzer.java +++ /dev/null @@ -1,72 +0,0 @@ -/******************************************************************************* - * 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 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.code.ExceptionAnalyzer - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring.code; - -import java.util.List; - -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.IMethodBinding; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.internal.corext.refactoring.util.AbstractExceptionAnalyzer; - -/* package */ class ExceptionAnalyzer extends AbstractExceptionAnalyzer { - - public static ITypeBinding[] perform(ASTNode[] statements) { - ExceptionAnalyzer analyzer = new ExceptionAnalyzer(); - for (int i = 0; i < statements.length; i++) { - statements[i].accept(analyzer); - } - List exceptions = analyzer.getCurrentExceptions(); - return exceptions.toArray(new ITypeBinding[exceptions.size()]); - } - - @Override - public boolean visit(ThrowStatement node) { - ITypeBinding exception = node.getExpression().resolveTypeBinding(); - if (exception == null) { - return true; - } - - addException(exception, node.getAST()); - return true; - } - - @Override - public boolean visit(MethodInvocation node) { - return handleExceptions((IMethodBinding) node.getName().resolveBinding(), node); - } - - @Override - public boolean visit(SuperMethodInvocation node) { - return handleExceptions((IMethodBinding) node.getName().resolveBinding(), node); - } - - @Override - public boolean visit(ClassInstanceCreation node) { - return handleExceptions(node.resolveConstructorBinding(), node); - } - - private boolean handleExceptions(IMethodBinding binding, ASTNode node) { - if (binding == null) { - return true; - } - addExceptions(binding.getExceptionTypes(), node.getAST()); - return true; - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExtractTempRefactoring.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExtractTempRefactoring.java deleted file mode 100644 index 86cc3921b4..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/code/ExtractTempRefactoring.java +++ /dev/null @@ -1,1175 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2017 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring - * - * Contributors: - * IBM Corporation - initial API and implementation - * Nikolay Metchev - [extract local] Extract to local variable not replacing multiple occurrences in same statement - https://bugs.eclipse.org/406347 - * Nicolaj Hoess - [extract local] puts declaration at wrong position - https://bugs.eclipse.org/65875 - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring.code; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.StringTokenizer; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.SubProgressMonitor; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.NamingConventions; -import org.eclipse.jdt.core.SourceRange; -import org.eclipse.jdt.core.compiler.IProblem; -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.Annotation; -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.CatchClause; -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.ConstructorInvocation; -import org.eclipse.jdt.core.dom.DoStatement; -import org.eclipse.jdt.core.dom.EnhancedForStatement; -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.ForStatement; -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.IfStatement; -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.Modifier.ModifierKeyword; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.NullLiteral; -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.QualifiedName; -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.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.TryStatement; -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.WhileStatement; -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.core.dom.rewrite.ImportRewrite.TypeLocation; -import org.eclipse.jdt.core.dom.rewrite.ListRewrite; -import org.eclipse.jdt.core.refactoring.CompilationUnitChange; -import org.eclipse.jdt.core.refactoring.IJavaRefactorings; -import org.eclipse.jdt.core.refactoring.descriptors.ExtractLocalDescriptor; -import org.eclipse.jdt.internal.core.manipulation.BindingLabelProviderCore; -import org.eclipse.jdt.internal.core.manipulation.JavaElementLabelsCore; -import org.eclipse.jdt.internal.core.manipulation.StubUtility; -import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; -import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; -import org.eclipse.jdt.internal.core.refactoring.descriptors.RefactoringSignatureDescriptorFactory; -import org.eclipse.jdt.internal.corext.SourceRangeFactory; -import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; -import org.eclipse.jdt.internal.corext.dom.ASTNodes; -import org.eclipse.jdt.internal.corext.dom.Bindings; -import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; -import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; -import org.eclipse.jdt.internal.corext.dom.fragments.ASTFragmentFactory; -import org.eclipse.jdt.internal.corext.dom.fragments.IASTFragment; -import org.eclipse.jdt.internal.corext.dom.fragments.IExpressionFragment; -import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; -import org.eclipse.jdt.internal.corext.fix.LinkedProposalPositionGroupCore; -import org.eclipse.jdt.internal.corext.refactoring.Checks; -import org.eclipse.jdt.internal.corext.refactoring.JDTRefactoringDescriptorComment; -import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringArguments; -import org.eclipse.jdt.internal.corext.refactoring.JavaRefactoringDescriptorUtil; -import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; -import org.eclipse.jdt.internal.corext.refactoring.base.JavaStringStatusContext; -import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusCodes; -import org.eclipse.jdt.internal.corext.refactoring.code.CodeRefactoringUtil; -import org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil; -import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.refactoring.util.JavaStatusContext; -import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer; -import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; -import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; -import org.eclipse.jdt.ls.core.internal.IConstants; -import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; -import org.eclipse.jdt.ls.core.internal.Messages; -import org.eclipse.ltk.core.refactoring.Change; -import org.eclipse.ltk.core.refactoring.Refactoring; -import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor; -import org.eclipse.ltk.core.refactoring.RefactoringDescriptor; -import org.eclipse.ltk.core.refactoring.RefactoringStatus; -import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry; -import org.eclipse.text.edits.TextEditGroup; - -/** - * Extract Local Variable (from selected expression inside method or - * initializer). - */ -public class ExtractTempRefactoring extends Refactoring { - - private static final String ATTRIBUTE_REPLACE = "replace"; //$NON-NLS-1$ - private static final String ATTRIBUTE_FINAL = "final"; //$NON-NLS-1$ - - private static final class ForStatementChecker extends ASTVisitor { - - private final Collection fForInitializerVariables; - - private boolean fReferringToForVariable = false; - - public ForStatementChecker(Collection forInitializerVariables) { - Assert.isNotNull(forInitializerVariables); - fForInitializerVariables = forInitializerVariables; - } - - public boolean isReferringToForVariable() { - return fReferringToForVariable; - } - - @Override - public boolean visit(SimpleName node) { - IBinding binding = node.resolveBinding(); - if (binding != null && fForInitializerVariables.contains(binding)) { - fReferringToForVariable = true; - } - return false; - } - } - - private static boolean allArraysEqual(ASTNode[][] arrays, int position) { - Object element = arrays[0][position]; - for (int i = 0; i < arrays.length; i++) { - Object[] array = arrays[i]; - if (!element.equals(array[position])) { - return false; - } - } - return true; - } - - private static boolean canReplace(IASTFragment fragment) { - ASTNode node = fragment.getAssociatedNode(); - ASTNode parent = node.getParent(); - if (parent instanceof VariableDeclarationFragment) { - VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent; - if (node.equals(vdf.getName())) { - return false; - } - } - if (isMethodParameter(node)) { - return false; - } - if (isThrowableInCatchBlock(node)) { - return false; - } - if (parent instanceof ExpressionStatement) { - return false; - } - if (parent instanceof LambdaExpression) { - return false; - } - if (isLeftValue(node)) { - return false; - } - if (isReferringToLocalVariableFromFor((Expression) node)) { - return false; - } - if (isUsedInForInitializerOrUpdater((Expression) node)) { - return false; - } - if (parent instanceof SwitchCase) { - return false; - } - return true; - } - - private static ASTNode[] getArrayPrefix(ASTNode[] array, int prefixLength) { - Assert.isTrue(prefixLength <= array.length); - Assert.isTrue(prefixLength >= 0); - ASTNode[] prefix = new ASTNode[prefixLength]; - for (int i = 0; i < prefix.length; i++) { - prefix[i] = array[i]; - } - return prefix; - } - - // return List - private static List getForInitializedVariables(VariableDeclarationExpression variableDeclarations) { - List forInitializerVariables = new ArrayList<>(1); - for (Iterator iter = variableDeclarations.fragments().iterator(); iter.hasNext();) { - VariableDeclarationFragment fragment = iter.next(); - IVariableBinding binding = fragment.resolveBinding(); - if (binding != null) { - forInitializerVariables.add(binding); - } - } - return forInitializerVariables; - } - - private static ASTNode[] getLongestArrayPrefix(ASTNode[][] arrays) { - int length = -1; - if (arrays.length == 0) { - return new ASTNode[0]; - } - int minArrayLength = arrays[0].length; - for (int i = 1; i < arrays.length; i++) { - minArrayLength = Math.min(minArrayLength, arrays[i].length); - } - - for (int i = 0; i < minArrayLength; i++) { - if (!allArraysEqual(arrays, i)) { - break; - } - length++; - } - if (length == -1) { - return new ASTNode[0]; - } - return getArrayPrefix(arrays[0], length + 1); - } - - private static ASTNode[] getParents(ASTNode node) { - ASTNode current = node; - List parents = new ArrayList<>(); - do { - parents.add(current.getParent()); - current = current.getParent(); - } while (current.getParent() != null); - Collections.reverse(parents); - return parents.toArray(new ASTNode[parents.size()]); - } - - private static boolean isLeftValue(ASTNode node) { - ASTNode parent = node.getParent(); - if (parent instanceof Assignment) { - Assignment assignment = (Assignment) parent; - if (assignment.getLeftHandSide() == node) { - return true; - } - } - if (parent instanceof PostfixExpression) { - return true; - } - if (parent instanceof PrefixExpression) { - PrefixExpression.Operator op = ((PrefixExpression) parent).getOperator(); - if (op.equals(PrefixExpression.Operator.DECREMENT)) { - return true; - } - if (op.equals(PrefixExpression.Operator.INCREMENT)) { - return true; - } - return false; - } - return false; - } - - private static boolean isMethodParameter(ASTNode node) { - return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof MethodDeclaration); - } - - private static boolean isReferringToLocalVariableFromFor(Expression expression) { - ASTNode current = expression; - ASTNode parent = current.getParent(); - while (parent != null && !(parent instanceof BodyDeclaration)) { - if (parent instanceof ForStatement) { - ForStatement forStmt = (ForStatement) parent; - if (forStmt.initializers().contains(current) || forStmt.updaters().contains(current) || forStmt.getExpression() == current) { - List initializers = forStmt.initializers(); - if (initializers.size() == 1 && initializers.get(0) instanceof VariableDeclarationExpression) { - List forInitializerVariables = getForInitializedVariables((VariableDeclarationExpression) initializers.get(0)); - ForStatementChecker checker = new ForStatementChecker(forInitializerVariables); - expression.accept(checker); - if (checker.isReferringToForVariable()) { - return true; - } - } - } - } - current = parent; - parent = current.getParent(); - } - return false; - } - - private static boolean isThrowableInCatchBlock(ASTNode node) { - return (node instanceof SimpleName) && (node.getParent() instanceof SingleVariableDeclaration) && (node.getParent().getParent() instanceof CatchClause); - } - - private static boolean isUsedInForInitializerOrUpdater(Expression expression) { - ASTNode parent = expression.getParent(); - if (parent instanceof ForStatement) { - ForStatement forStmt = (ForStatement) parent; - return forStmt.initializers().contains(expression) || forStmt.updaters().contains(expression); - } - return false; - } - - private static IASTFragment[] retainOnlyReplacableMatches(IASTFragment[] allMatches) { - List result = new ArrayList<>(allMatches.length); - for (int i = 0; i < allMatches.length; i++) { - if (canReplace(allMatches[i])) { - result.add(allMatches[i]); - } - } - return result.toArray(new IASTFragment[result.size()]); - } - - private CompilationUnit fCompilationUnitNode; - - private CompilationUnitRewrite fCURewrite; - - private ICompilationUnit fCu; - - private boolean fDeclareFinal; - - private String[] fExcludedVariableNames; - - private boolean fReplaceAllOccurrences; - - // caches: - private IExpressionFragment fSelectedExpression; - - private int fSelectionLength; - - private int fSelectionStart; - - private String fTempName; - private String[] fGuessedTempNames; - - private boolean fCheckResultForCompileProblems; - - private CompilationUnitChange fChange; - - private LinkedProposalModelCore fLinkedProposalModel; - - private Map fFormatterOptions; - - private static final String KEY_NAME = "name"; //$NON-NLS-1$ - private static final String KEY_TYPE = "type"; //$NON-NLS-1$ - - /** - * Creates a new extract temp refactoring - * - * @param unit - * the compilation unit, or null if invoked by scripting - * @param selectionStart - * start of selection - * @param selectionLength - * length of selection - */ - public ExtractTempRefactoring(ICompilationUnit unit, int selectionStart, int selectionLength) { - this(unit, selectionStart, selectionLength, null); - } - - public ExtractTempRefactoring(ICompilationUnit unit, int selectionStart, int selectionLength, Map formatterOptions) { - Assert.isTrue(selectionStart >= 0); - Assert.isTrue(selectionLength >= 0); - fSelectionStart = selectionStart; - fSelectionLength = selectionLength; - fCu = unit; - fCompilationUnitNode = null; - - fReplaceAllOccurrences = true; // default - fDeclareFinal = false; // default - fTempName = ""; //$NON-NLS-1$ - - fLinkedProposalModel = null; - fCheckResultForCompileProblems = true; - fFormatterOptions = formatterOptions; - } - - public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength) { - this(astRoot, selectionStart, selectionLength, null); - } - - public ExtractTempRefactoring(CompilationUnit astRoot, int selectionStart, int selectionLength, Map formatterOptions) { - Assert.isTrue(selectionStart >= 0); - Assert.isTrue(selectionLength >= 0); - Assert.isTrue(astRoot.getTypeRoot() instanceof ICompilationUnit); - - fSelectionStart = selectionStart; - fSelectionLength = selectionLength; - fCu = (ICompilationUnit) astRoot.getTypeRoot(); - fCompilationUnitNode = astRoot; - - fReplaceAllOccurrences = true; // default - fDeclareFinal = false; // default - fTempName = ""; //$NON-NLS-1$ - - fLinkedProposalModel = null; - fCheckResultForCompileProblems = true; - fFormatterOptions = formatterOptions; - } - - public ExtractTempRefactoring(JavaRefactoringArguments arguments, RefactoringStatus status) { - this((ICompilationUnit) null, 0, 0); - RefactoringStatus initializeStatus = initialize(arguments); - status.merge(initializeStatus); - } - - public void setCheckResultForCompileProblems(boolean checkResultForCompileProblems) { - fCheckResultForCompileProblems = checkResultForCompileProblems; - } - - public void setLinkedProposalModel(LinkedProposalModelCore linkedProposalModel) { - fLinkedProposalModel = linkedProposalModel; - } - - private void addReplaceExpressionWithTemp() throws JavaModelException { - IASTFragment[] fragmentsToReplace = retainOnlyReplacableMatches(getMatchingFragments()); - //TODO: should not have to prune duplicates here... - ASTRewrite rewrite = fCURewrite.getASTRewrite(); - HashSet seen = new HashSet<>(); - for (int i = 0; i < fragmentsToReplace.length; i++) { - IASTFragment fragment = fragmentsToReplace[i]; - if (!seen.add(fragment)) { - continue; - } - SimpleName tempName = fCURewrite.getAST().newSimpleName(fTempName); - TextEditGroup description = fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_replace); - - fragment.replace(rewrite, tempName, description); - if (fLinkedProposalModel != null) { - fLinkedProposalModel.getPositionGroup(KEY_NAME, true).addPosition(rewrite.track(tempName), false); - } - } - } - - private RefactoringStatus checkExpression() throws JavaModelException { - Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); - if (selectedExpression != null) { - final ASTNode parent = selectedExpression.getParent(); - if (selectedExpression instanceof NullLiteral) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals); - } else if (selectedExpression instanceof ArrayInitializer) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer); - } else if (selectedExpression instanceof Assignment) { - if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression)) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment); - } else { - return null; - } - } else if (selectedExpression instanceof SimpleName) { - if ((((SimpleName) selectedExpression)).isDeclaration()) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations); - } - if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression); - } - } else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources); - } - } - - return null; - } - - // !! Same as in ExtractConstantRefactoring - private RefactoringStatus checkExpressionFragmentIsRValue() throws JavaModelException { - switch (Checks.checkExpressionIsRValue(getSelectedExpression().getAssociatedExpression())) { - case Checks.NOT_RVALUE_MISC: - return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_select_expression, null, IConstants.PLUGIN_ID, RefactoringStatusCodes.EXPRESSION_NOT_RVALUE, - null); - case Checks.NOT_RVALUE_VOID: - return RefactoringStatus.createStatus(RefactoringStatus.FATAL, RefactoringCoreMessages.ExtractTempRefactoring_no_void, null, IConstants.PLUGIN_ID, RefactoringStatusCodes.EXPRESSION_NOT_RVALUE_VOID, null); - case Checks.IS_RVALUE_GUESSED: - case Checks.IS_RVALUE: - return new RefactoringStatus(); - default: - Assert.isTrue(false); - return null; - } - } - - private ITypeBinding guessBindingForReference(Expression expression) { - ITypeBinding binding = expression.resolveTypeBinding(); - if (binding == null) { - binding = ASTResolving.guessBindingForReference(expression); - } - return binding; - } - - @Override - public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException { - try { - pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 4); - - fCURewrite = new CompilationUnitRewrite(fCu, fCompilationUnitNode); - fCURewrite.setFormattingOptions(fFormatterOptions); - fCURewrite.getASTRewrite().setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); - - doCreateChange(new SubProgressMonitor(pm, 2)); - - fChange = fCURewrite.createChange(RefactoringCoreMessages.ExtractTempRefactoring_change_name, true, new SubProgressMonitor(pm, 1)); - - RefactoringStatus result = new RefactoringStatus(); - if (Arrays.asList(getExcludedVariableNames()).contains(fTempName)) { - result.addWarning(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_another_variable, BasicElementLabels.getJavaElementName(fTempName))); - } - - result.merge(checkMatchingFragments()); - - fChange.setKeepPreviewEdits(true); - - if (fCheckResultForCompileProblems) { - checkNewSource(new SubProgressMonitor(pm, 1), result); - } - - return result; - } finally { - pm.done(); - } - } - - private final ExtractLocalDescriptor createRefactoringDescriptor() { - final Map arguments = new HashMap<>(); - String project = null; - IJavaProject javaProject = fCu.getJavaProject(); - if (javaProject != null) { - project = javaProject.getElementName(); - } - final String description = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(fTempName)); - final String expression = ASTNodes.asString(fSelectedExpression.getAssociatedExpression()); - final String header = Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_descriptor_description, new String[] { BasicElementLabels.getJavaElementName(fTempName), BasicElementLabels.getJavaCodeString(expression) }); - final JDTRefactoringDescriptorComment comment = new JDTRefactoringDescriptorComment(project, this, header); - comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_name_pattern, BasicElementLabels.getJavaElementName(fTempName))); - final BodyDeclaration decl = ASTNodes.getParent(fSelectedExpression.getAssociatedExpression(), BodyDeclaration.class); - if (decl instanceof MethodDeclaration) { - final IMethodBinding method = ((MethodDeclaration) decl).resolveBinding(); - final String label = method != null ? BindingLabelProviderCore.getBindingLabel(method, JavaElementLabelsCore.ALL_FULLY_QUALIFIED) : BasicElementLabels.getJavaElementName('{' + JavaElementLabelsCore.ELLIPSIS_STRING + '}'); - comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_destination_pattern, label)); - } - comment.addSetting(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_expression_pattern, BasicElementLabels.getJavaCodeString(expression))); - if (fReplaceAllOccurrences) { - comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_replace_occurrences); - } - if (fDeclareFinal) { - comment.addSetting(RefactoringCoreMessages.ExtractTempRefactoring_declare_final); - } - final ExtractLocalDescriptor descriptor = RefactoringSignatureDescriptorFactory.createExtractLocalDescriptor(project, description, comment.asString(), arguments, RefactoringDescriptor.NONE); - arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fCu)); - arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME, fTempName); - arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$ - arguments.put(ATTRIBUTE_REPLACE, Boolean.valueOf(fReplaceAllOccurrences).toString()); - arguments.put(ATTRIBUTE_FINAL, Boolean.valueOf(fDeclareFinal).toString()); - return descriptor; - } - - private void doCreateChange(IProgressMonitor pm) throws CoreException { - try { - pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 1); - try { - createTempDeclaration(); - } catch (CoreException exception) { - JavaLanguageServerPlugin.logException("Problem with extract temp filed ", exception); - } - addReplaceExpressionWithTemp(); - } finally { - pm.done(); - } - } - - private void checkNewSource(SubProgressMonitor monitor, RefactoringStatus result) throws CoreException { - String newCuSource = fChange.getPreviewContent(new NullProgressMonitor()); - CompilationUnit newCUNode = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL).parse(newCuSource, fCu, true, true, monitor); - IProblem[] newProblems = RefactoringAnalyzeUtil.getIntroducedCompileProblems(newCUNode, fCompilationUnitNode); - for (int i = 0; i < newProblems.length; i++) { - IProblem problem = newProblems[i]; - if (problem.isError()) { - result.addEntry(new RefactoringStatusEntry((problem.isError() ? RefactoringStatus.ERROR : RefactoringStatus.WARNING), problem.getMessage(), new JavaStringStatusContext(newCuSource, SourceRangeFactory.create(problem)))); - } - } - } - - @Override - public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException { - try { - pm.beginTask("", 6); //$NON-NLS-1$ - - RefactoringStatus result = Checks.validateModifiesFiles(ResourceUtil.getFiles(new ICompilationUnit[] { fCu }), getValidationContext(), pm); - if (result.hasFatalError()) { - return result; - } - - if (fCompilationUnitNode == null) { - fCompilationUnitNode = RefactoringASTParser.parseWithASTProvider(fCu, true, new SubProgressMonitor(pm, 3)); - } else { - pm.worked(3); - } - - result.merge(checkSelection(new SubProgressMonitor(pm, 3))); - if (!result.hasFatalError() && isLiteralNodeSelected()) { - fReplaceAllOccurrences = false; - } - return result; - - } finally { - pm.done(); - } - } - - private RefactoringStatus checkMatchingFragments() throws JavaModelException { - RefactoringStatus result = new RefactoringStatus(); - IASTFragment[] matchingFragments = getMatchingFragments(); - for (int i = 0; i < matchingFragments.length; i++) { - ASTNode node = matchingFragments[i].getAssociatedNode(); - if (isLeftValue(node) && !isReferringToLocalVariableFromFor((Expression) node)) { - String msg = RefactoringCoreMessages.ExtractTempRefactoring_assigned_to; - result.addWarning(msg, JavaStatusContext.create(fCu, node)); - } - } - return result; - } - - private RefactoringStatus checkSelection(IProgressMonitor pm) throws JavaModelException { - try { - pm.beginTask("", 8); //$NON-NLS-1$ - - IExpressionFragment selectedExpression = getSelectedExpression(); - - if (selectedExpression == null) { - String message = RefactoringCoreMessages.ExtractTempRefactoring_select_expression; - return CodeRefactoringUtil.checkMethodSyntaxErrors(fSelectionStart, fSelectionLength, fCompilationUnitNode, message); - } - pm.worked(1); - - if (isUsedInExplicitConstructorCall()) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_explicit_constructor); - } - pm.worked(1); - - ASTNode associatedNode = selectedExpression.getAssociatedNode(); - if (getEnclosingBodyNode() == null || ASTNodes.getParent(associatedNode, Annotation.class) != null) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_expr_in_method_or_initializer); - } - pm.worked(1); - - if (associatedNode instanceof Name && associatedNode.getParent() instanceof ClassInstanceCreation && associatedNode.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_name_in_new); - } - pm.worked(1); - - RefactoringStatus result = new RefactoringStatus(); - result.merge(checkExpression()); - if (result.hasFatalError()) { - return result; - } - pm.worked(1); - - result.merge(checkExpressionFragmentIsRValue()); - if (result.hasFatalError()) { - return result; - } - pm.worked(1); - - if (isUsedInForInitializerOrUpdater(getSelectedExpression().getAssociatedExpression())) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_for_initializer_updater); - } - pm.worked(1); - - if (isReferringToLocalVariableFromFor(getSelectedExpression().getAssociatedExpression())) { - return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_refers_to_for_variable); - } - pm.worked(1); - - return result; - } finally { - pm.done(); - } - } - - public RefactoringStatus checkTempName(String newName) { - RefactoringStatus status = Checks.checkTempName(newName, fCu); - if (Arrays.asList(getExcludedVariableNames()).contains(newName)) { - status.addWarning(Messages.format(RefactoringCoreMessages.ExtractTempRefactoring_another_variable, BasicElementLabels.getJavaElementName(newName))); - } - return status; - } - - private void createAndInsertTempDeclaration() throws CoreException { - Expression initializer = getSelectedExpression().createCopyTarget(fCURewrite.getASTRewrite(), true); - VariableDeclarationStatement vds = createTempDeclaration(initializer); - - boolean insertAtSelection; - if (!fReplaceAllOccurrences) { - insertAtSelection = true; - } else { - IASTFragment[] replacableMatches = retainOnlyReplacableMatches(getMatchingFragments()); - insertAtSelection = replacableMatches.length == 0 || replacableMatches.length == 1 && replacableMatches[0].getAssociatedNode().equals(getSelectedExpression().getAssociatedExpression()); - } - if (insertAtSelection) { - insertAt(getSelectedExpression().getAssociatedNode(), vds); - return; - } - - ASTNode[] firstReplaceNodeParents = getParents(getFirstReplacedExpression().getAssociatedNode()); - ASTNode[] commonPath = findDeepestCommonSuperNodePathForReplacedNodes(); - Assert.isTrue(commonPath.length <= firstReplaceNodeParents.length); - - ASTNode deepestCommonParent = firstReplaceNodeParents[commonPath.length - 1]; - if (deepestCommonParent instanceof Block) { - insertAt(firstReplaceNodeParents[commonPath.length], vds); - } else { - insertAt(deepestCommonParent, vds); - } - } - - private VariableDeclarationStatement createTempDeclaration(Expression initializer) throws CoreException { - AST ast = fCURewrite.getAST(); - - VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment(); - vdf.setName(ast.newSimpleName(fTempName)); - vdf.setInitializer(initializer); - - VariableDeclarationStatement vds = ast.newVariableDeclarationStatement(vdf); - if (fDeclareFinal) { - vds.modifiers().add(ast.newModifier(ModifierKeyword.FINAL_KEYWORD)); - } - vds.setType(createTempType()); - - if (fLinkedProposalModel != null) { - ASTRewrite rewrite = fCURewrite.getASTRewrite(); - LinkedProposalPositionGroupCore nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true); - nameGroup.addPosition(rewrite.track(vdf.getName()), true); - - String[] nameSuggestions = guessTempNames(); - if (nameSuggestions.length > 0 && !nameSuggestions[0].equals(fTempName)) { - nameGroup.addProposal(fTempName, nameSuggestions.length + 1); - } - for (int i = 0; i < nameSuggestions.length; i++) { - nameGroup.addProposal(nameSuggestions[i], nameSuggestions.length - i); - } - } - return vds; - } - - private void insertAt(ASTNode target, Statement declaration) { - ASTRewrite rewrite = fCURewrite.getASTRewrite(); - TextEditGroup groupDescription = fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable); - - ASTNode parent = target.getParent(); - StructuralPropertyDescriptor locationInParent = target.getLocationInParent(); - while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) { - if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY || locationInParent == ForStatement.BODY_PROPERTY || locationInParent == EnhancedForStatement.BODY_PROPERTY - || locationInParent == DoStatement.BODY_PROPERTY || locationInParent == WhileStatement.BODY_PROPERTY) { - // create intermediate block if target was the body property of a control statement: - Block replacement = rewrite.getAST().newBlock(); - ListRewrite replacementRewrite = rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY); - replacementRewrite.insertFirst(declaration, null); - replacementRewrite.insertLast(rewrite.createMoveTarget(target), null); - rewrite.replace(target, replacement, groupDescription); - return; - } else if (locationInParent == LambdaExpression.BODY_PROPERTY && ((LambdaExpression) parent).getBody() instanceof Expression) { - Block replacement = rewrite.getAST().newBlock(); - ListRewrite replacementRewrite = rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY); - replacementRewrite.insertFirst(declaration, null); - ASTNode moveTarget = rewrite.createMoveTarget(target); - AST ast = rewrite.getAST(); - if (Bindings.isVoidType(((LambdaExpression) parent).resolveMethodBinding().getReturnType())) { - ExpressionStatement expressionStatement = ast.newExpressionStatement((Expression) moveTarget); - moveTarget = expressionStatement; - } else { - ReturnStatement returnStatement = ast.newReturnStatement(); - returnStatement.setExpression((Expression) moveTarget); - moveTarget = returnStatement; - } - replacementRewrite.insertLast(moveTarget, null); - rewrite.replace(target, replacement, groupDescription); - return; - } - target = parent; - parent = parent.getParent(); - locationInParent = target.getLocationInParent(); - } - ListRewrite listRewrite = rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) locationInParent); - listRewrite.insertBefore(declaration, target, groupDescription); - } - - @Override - public Change createChange(IProgressMonitor pm) throws CoreException { - try { - pm.beginTask(RefactoringCoreMessages.ExtractTempRefactoring_checking_preconditions, 1); - - ExtractLocalDescriptor descriptor = createRefactoringDescriptor(); - fChange.setDescriptor(new RefactoringChangeDescriptor(descriptor)); - return fChange; - } finally { - pm.done(); - } - } - - private void createTempDeclaration() throws CoreException { - if (shouldReplaceSelectedExpressionWithTempDeclaration()) { - replaceSelectedExpressionWithTempDeclaration(); - } else { - createAndInsertTempDeclaration(); - } - } - - public boolean declareFinal() { - return fDeclareFinal; - } - - private ASTNode[] findDeepestCommonSuperNodePathForReplacedNodes() throws JavaModelException { - ASTNode[] matchNodes = getMatchNodes(); - - ASTNode[][] matchingNodesParents = new ASTNode[matchNodes.length][]; - for (int i = 0; i < matchNodes.length; i++) { - matchingNodesParents[i] = getParents(matchNodes[i]); - } - List l = Arrays.asList(getLongestArrayPrefix(matchingNodesParents)); - return l.toArray(new ASTNode[l.size()]); - } - - private ASTNode getEnclosingBodyNode() throws JavaModelException { - ASTNode node = getSelectedExpression().getAssociatedNode(); - - // expression must be in a method, lambda or initializer body - // make sure it is not in method or parameter annotation - StructuralPropertyDescriptor location = null; - while (node != null && !(node instanceof BodyDeclaration)) { - location = node.getLocationInParent(); - node = node.getParent(); - if (node instanceof LambdaExpression) { - break; - } - } - if (location == MethodDeclaration.BODY_PROPERTY || location == Initializer.BODY_PROPERTY || (location == LambdaExpression.BODY_PROPERTY && ((LambdaExpression) node).resolveMethodBinding() != null)) { - return (ASTNode) node.getStructuralProperty(location); - } - return null; - } - - private String[] getExcludedVariableNames() { - if (fExcludedVariableNames == null) { - try { - IBinding[] bindings = new ScopeAnalyzer(fCompilationUnitNode).getDeclarationsInScope(getSelectedExpression().getStartPosition(), ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); - fExcludedVariableNames = new String[bindings.length]; - for (int i = 0; i < bindings.length; i++) { - fExcludedVariableNames[i] = bindings[i].getName(); - } - } catch (JavaModelException e) { - fExcludedVariableNames = new String[0]; - } - } - return fExcludedVariableNames; - } - - private IExpressionFragment getFirstReplacedExpression() throws JavaModelException { - if (!fReplaceAllOccurrences) { - return getSelectedExpression(); - } - IASTFragment[] nodesToReplace = retainOnlyReplacableMatches(getMatchingFragments()); - if (nodesToReplace.length == 0) { - return getSelectedExpression(); - } - Comparator comparator = new Comparator<>() { - - @Override - public int compare(IASTFragment o1, IASTFragment o2) { - return o1.getStartPosition() - o2.getStartPosition(); - } - }; - Arrays.sort(nodesToReplace, comparator); - return (IExpressionFragment) nodesToReplace[0]; - } - - private IASTFragment[] getMatchingFragments() throws JavaModelException { - if (fReplaceAllOccurrences) { - IASTFragment[] allMatches = ASTFragmentFactory.createFragmentForFullSubtree(getEnclosingBodyNode()).getSubFragmentsMatching(getSelectedExpression()); - return allMatches; - } else { - return new IASTFragment[] { getSelectedExpression() }; - } - } - - private ASTNode[] getMatchNodes() throws JavaModelException { - IASTFragment[] matches = retainOnlyReplacableMatches(getMatchingFragments()); - ASTNode[] result = new ASTNode[matches.length]; - for (int i = 0; i < matches.length; i++) { - result[i] = matches[i].getAssociatedNode(); - } - return result; - } - - @Override - public String getName() { - return RefactoringCoreMessages.ExtractTempRefactoring_name; - } - - private IExpressionFragment getSelectedExpression() throws JavaModelException { - if (fSelectedExpression != null) { - return fSelectedExpression; - } - IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu); - - if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) { - fSelectedExpression = (IExpressionFragment) selectedFragment; - } else if (selectedFragment != null) { - if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) { - ExpressionStatement exprStatement = (ExpressionStatement) selectedFragment.getAssociatedNode(); - Expression expression = exprStatement.getExpression(); - fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression); - } else if (selectedFragment.getAssociatedNode() instanceof Assignment) { - Assignment assignment = (Assignment) selectedFragment.getAssociatedNode(); - fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment); - } - } - - if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) { - fSelectedExpression = null; - } - - return fSelectedExpression; - } - - private Type createTempType() throws CoreException { - Expression expression = getSelectedExpression().getAssociatedExpression(); - - Type resultingType = null; - ITypeBinding typeBinding = expression.resolveTypeBinding(); - - ASTRewrite rewrite = fCURewrite.getASTRewrite(); - AST ast = rewrite.getAST(); - - if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) { - resultingType = (Type) rewrite.createCopyTarget(((ClassInstanceCreation) expression).getType()); - } else if (expression instanceof CastExpression) { - resultingType = (Type) rewrite.createCopyTarget(((CastExpression) expression).getType()); - } else { - if (typeBinding == null) { - typeBinding = ASTResolving.guessBindingForReference(expression); - } - if (typeBinding != null) { - typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast); - ImportRewrite importRewrite = fCURewrite.getImportRewrite(); - ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite); - resultingType = importRewrite.addImport(typeBinding, ast, context, TypeLocation.LOCAL_VARIABLE); - } else { - resultingType = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ - } - } - if (fLinkedProposalModel != null) { - LinkedProposalPositionGroupCore typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true); - typeGroup.addPosition(rewrite.track(resultingType), false); - if (typeBinding != null) { - ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding); - for (int i = 0; i < relaxingTypes.length; i++) { - typeGroup.addProposal(relaxingTypes[i], fCURewrite.getCu(), relaxingTypes.length - i); - } - } - } - return resultingType; - } - - public String guessTempName() { - String[] proposals = guessTempNames(); - if (proposals.length == 0) { - return fTempName; - } else { - return proposals[0]; - } - } - - /** - * @return proposed variable names (may be empty, but not null). The first - * proposal should be used as "best guess" (if it exists). - */ - public String[] guessTempNames() { - if (fGuessedTempNames == null) { - try { - Expression expression = getSelectedExpression().getAssociatedExpression(); - if (expression != null) { - ITypeBinding binding = guessBindingForReference(expression); - fGuessedTempNames = StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, fCu.getJavaProject(), binding, expression, Arrays.asList(getExcludedVariableNames())); - } - } catch (JavaModelException e) { - } - if (fGuessedTempNames == null) { - fGuessedTempNames = new String[0]; - } - } - return fGuessedTempNames; - } - - private boolean isLiteralNodeSelected() throws JavaModelException { - IExpressionFragment fragment = getSelectedExpression(); - if (fragment == null) { - return false; - } - Expression expression = fragment.getAssociatedExpression(); - if (expression == null) { - return false; - } - switch (expression.getNodeType()) { - case ASTNode.BOOLEAN_LITERAL: - case ASTNode.CHARACTER_LITERAL: - case ASTNode.NULL_LITERAL: - case ASTNode.NUMBER_LITERAL: - return true; - - default: - return false; - } - } - - private boolean isUsedInExplicitConstructorCall() throws JavaModelException { - Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); - if (ASTNodes.getParent(selectedExpression, ConstructorInvocation.class) != null) { - return true; - } - if (ASTNodes.getParent(selectedExpression, SuperConstructorInvocation.class) != null) { - return true; - } - return false; - } - - public boolean replaceAllOccurrences() { - return fReplaceAllOccurrences; - } - - private void replaceSelectedExpressionWithTempDeclaration() throws CoreException { - ASTRewrite rewrite = fCURewrite.getASTRewrite(); - Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected - - Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression); - VariableDeclarationStatement tempDeclaration = createTempDeclaration(initializer); - ASTNode replacement; - - ASTNode parent = selectedExpression.getParent(); - boolean isParentLambda = parent instanceof LambdaExpression; - AST ast = rewrite.getAST(); - if (isParentLambda) { - Block blockBody = ast.newBlock(); - blockBody.statements().add(tempDeclaration); - if (!Bindings.isVoidType(((LambdaExpression) parent).resolveMethodBinding().getReturnType())) { - List fragments = tempDeclaration.fragments(); - SimpleName varName = fragments.get(0).getName(); - ReturnStatement returnStatement = ast.newReturnStatement(); - returnStatement.setExpression(ast.newSimpleName(varName.getIdentifier())); - blockBody.statements().add(returnStatement); - } - replacement = blockBody; - } else if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) { - Block block = ast.newBlock(); - block.statements().add(tempDeclaration); - replacement = block; - } else { - replacement = tempDeclaration; - } - ASTNode replacee = isParentLambda || !ASTNodes.hasSemicolon((ExpressionStatement) parent, fCu) ? selectedExpression : parent; - rewrite.replace(replacee, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable)); - } - - public void setDeclareFinal(boolean declareFinal) { - fDeclareFinal = declareFinal; - } - - public void setReplaceAllOccurrences(boolean replaceAllOccurrences) { - fReplaceAllOccurrences = replaceAllOccurrences; - } - - public void setTempName(String newName) { - fTempName = newName; - } - - private boolean shouldReplaceSelectedExpressionWithTempDeclaration() throws JavaModelException { - IExpressionFragment selectedFragment = getSelectedExpression(); - IExpressionFragment firstExpression = getFirstReplacedExpression(); - if (firstExpression.getStartPosition() < selectedFragment.getStartPosition()) { - return false; - } - ASTNode associatedNode = selectedFragment.getAssociatedNode(); - return (associatedNode.getParent() instanceof ExpressionStatement || associatedNode.getParent() instanceof LambdaExpression) && selectedFragment.matches(ASTFragmentFactory.createFragmentForFullSubtree(associatedNode)); - } - - private RefactoringStatus initialize(JavaRefactoringArguments arguments) { - final String selection = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION); - if (selection != null) { - int offset = -1; - int length = -1; - final StringTokenizer tokenizer = new StringTokenizer(selection); - if (tokenizer.hasMoreTokens()) { - offset = Integer.valueOf(tokenizer.nextToken()).intValue(); - } - if (tokenizer.hasMoreTokens()) { - length = Integer.valueOf(tokenizer.nextToken()).intValue(); - } - if (offset >= 0 && length >= 0) { - fSelectionStart = offset; - fSelectionLength = length; - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_illegal_argument, new Object[] { selection, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION })); - } - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION)); - } - final String handle = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT); - if (handle != null) { - final IJavaElement element = JavaRefactoringDescriptorUtil.handleToElement(arguments.getProject(), handle, false); - if (element == null || !element.exists() || element.getElementType() != IJavaElement.COMPILATION_UNIT) { - return JavaRefactoringDescriptorUtil.createInputFatalStatus(element, getName(), IJavaRefactorings.EXTRACT_LOCAL_VARIABLE); - } else { - fCu = (ICompilationUnit) element; - } - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT)); - } - final String name = arguments.getAttribute(JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME); - if (name != null && !"".equals(name)) { - fTempName = name; - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, JavaRefactoringDescriptorUtil.ATTRIBUTE_NAME)); - } - final String replace = arguments.getAttribute(ATTRIBUTE_REPLACE); - if (replace != null) { - fReplaceAllOccurrences = Boolean.valueOf(replace).booleanValue(); - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_REPLACE)); - } - final String declareFinal = arguments.getAttribute(ATTRIBUTE_FINAL); - if (declareFinal != null) { - fDeclareFinal = Boolean.valueOf(declareFinal).booleanValue(); - } else { - return RefactoringStatus.createFatalErrorStatus(Messages.format(RefactoringCoreMessages.InitializableRefactoring_argument_not_exist, ATTRIBUTE_FINAL)); - } - return new RefactoringStatus(); - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties deleted file mode 100644 index ab54c8ab04..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/nls/changes/NLSChangesMessages.properties +++ /dev/null @@ -1,17 +0,0 @@ -############################################################################### -# Copyright (c) 2000, 2009 IBM Corporation and others. -# -# This program and the accompanying materials -# are made available under the terms of the Eclipse Public License 2.0 -# which accompanies this distribution, and is available at -# https://www.eclipse.org/legal/epl-2.0/ -# -# SPDX-License-Identifier: EPL-2.0 -# -# Contributors: -# IBM Corporation - initial API and implementation -############################################################################### -createFile_creating_resource=Creating file... -createFile_Create_file=Create file {0} -CreateFileChange_error_exists=File ''{0}'' already exists -CreateFileChange_error_unknownLocation=The location for file ''{0}'' is unknown diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java deleted file mode 100644 index 42d2a27b73..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/rename/RefactoringHandleTransplanter.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringHandleTransplanter - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring.rename; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IInitializer; -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.Signature; - - -/** - * Helper class to transplant a IJavaElement handle from a certain state of the - * Java Model into another. - * - * The changes to the workspace include one type rename, a number of field - * renames, and a number of method renames including signature changes. - * - * The returned handle exists in the target model state. - * - * @since 3.2 - * - */ -public class RefactoringHandleTransplanter { - - private final IType fOldType; - private final IType fNewType; - private final Map fRefactoredSimilarElements; - - /** - * @param oldType old type - * @param newType renamed type - * @param refactoredSimilarElements map from similar element (IJavaElement) to new name (String), or null - */ - public RefactoringHandleTransplanter(IType oldType, IType newType, Map refactoredSimilarElements) { - fOldType= oldType; - fNewType= newType; - if (refactoredSimilarElements == null) { - fRefactoredSimilarElements= Collections.emptyMap(); - } else { - fRefactoredSimilarElements= refactoredSimilarElements; - } - } - - /** - * Converts the handle. Handle need not exist, but must be a source - * reference. - * - * @param handle - * @return the new handle - */ - public IMember transplantHandle(IMember handle) { - - /* - * Create a list of handles from top-level type to the handle - */ - final LinkedList oldElements= new LinkedList<>(); - addElements(handle, oldElements); - - /* - * Step through the elements and re-locate them in the new parents. - */ - final IMember[] newElements= convertElements(oldElements.toArray(new IMember[0])); - - return newElements[newElements.length - 1]; - } - - private void addElements(IMember element, LinkedList chain) { - chain.addFirst(element); - IJavaElement parent= element.getParent(); - if (parent instanceof IMember) { - addElements((IMember) parent, chain); - } - } - - private IMember[] convertElements(IMember[] oldElements) { - - final IMember[] newElements= new IMember[oldElements.length]; - final IMember first= oldElements[0]; - - Assert.isTrue(first instanceof IType); - - if (first.equals(fOldType)) { - // We renamed a top level type. - newElements[0]= fNewType; - } else { - newElements[0]= first; - } - - /* - * Note that we only need to translate the information necessary to - * create new handles. For example, the return type of a method is not - * relevant; neither is information about generic specifics in types. - */ - - for (int i= 1; i < oldElements.length; i++) { - final IJavaElement newParent= newElements[i - 1]; - final IJavaElement currentElement= oldElements[i]; - switch (newParent.getElementType()) { - case IJavaElement.TYPE: { - switch (currentElement.getElementType()) { - case IJavaElement.TYPE: { - final String newName= resolveTypeName((IType) currentElement); - newElements[i]= ((IType) newParent).getType(newName); - break; - } - case IJavaElement.METHOD: { - final String newName= resolveElementName(currentElement); - final String[] newParameterTypes= resolveParameterTypes((IMethod) currentElement); - newElements[i]= ((IType) newParent).getMethod(newName, newParameterTypes); - break; - } - case IJavaElement.INITIALIZER: { - final IInitializer initializer= (IInitializer) currentElement; - newElements[i]= ((IType) newParent).getInitializer(initializer.getOccurrenceCount()); - break; - } - case IJavaElement.FIELD: { - final String newName= resolveElementName(currentElement); - newElements[i]= ((IType) newParent).getField(newName); - break; - } - } - break; - } - case IJavaElement.METHOD: { - switch (currentElement.getElementType()) { - case IJavaElement.TYPE: { - newElements[i]= resolveTypeInMember((IMethod) newParent, (IType) currentElement); - break; - } - } - break; - } - case IJavaElement.INITIALIZER: { - switch (currentElement.getElementType()) { - case IJavaElement.TYPE: { - newElements[i]= resolveTypeInMember((IInitializer) newParent, (IType) currentElement); - break; - } - } - break; - } - case IJavaElement.FIELD: { - switch (currentElement.getElementType()) { - case IJavaElement.TYPE: { - // anonymous type in field declaration - newElements[i]= resolveTypeInMember((IField) newParent, (IType) currentElement); - break; - } - } - break; - } - } - } - return newElements; - } - - private String[] resolveParameterTypes(IMethod method) { - final String[] oldParameterTypes= method.getParameterTypes(); - final String[] newparams= new String[oldParameterTypes.length]; - - final String[] possibleOldSigs= new String[4]; - possibleOldSigs[0]= Signature.createTypeSignature(fOldType.getElementName(), false); - possibleOldSigs[1]= Signature.createTypeSignature(fOldType.getElementName(), true); - possibleOldSigs[2]= Signature.createTypeSignature(fOldType.getFullyQualifiedName(), false); - possibleOldSigs[3]= Signature.createTypeSignature(fOldType.getFullyQualifiedName(), true); - - final String[] possibleNewSigs= new String[4]; - possibleNewSigs[0]= Signature.createTypeSignature(fNewType.getElementName(), false); - possibleNewSigs[1]= Signature.createTypeSignature(fNewType.getElementName(), true); - possibleNewSigs[2]= Signature.createTypeSignature(fNewType.getFullyQualifiedName(), false); - possibleNewSigs[3]= Signature.createTypeSignature(fNewType.getFullyQualifiedName(), true); - - // Textually replace all occurrences - // This handles stuff like Map - for (int i= 0; i < oldParameterTypes.length; i++) { - newparams[i]= oldParameterTypes[i]; - for (int j= 0; j < possibleOldSigs.length; j++) { - newparams[i]= replaceAll(newparams[i], possibleOldSigs[j], possibleNewSigs[j]); - } - } - return newparams; - } - - private String resolveElementName(IJavaElement element) { - final String newName= fRefactoredSimilarElements.get(element); - if (newName != null) { - return newName; - } else { - return element.getElementName(); - } - } - - private IMember resolveTypeInMember(final IMember newParent, IType oldChild) { - // Local type or anonymous type. Only local types can be renamed. - String newName= ""; //$NON-NLS-1$ - if (oldChild.getElementName().length() != 0) { - newName= resolveTypeName(oldChild); - } - return newParent.getType(newName, oldChild.getOccurrenceCount()); - } - - private String resolveTypeName(IType type) { - return type.equals(fOldType) ? fNewType.getElementName() : type.getElementName(); - } - - private static String replaceAll(final String source, final String replaceFrom, final String replaceTo) { - final StringBuilder buf= new StringBuilder(source.length()); - int currentIndex= 0; - int matchIndex; - while ((matchIndex= source.indexOf(replaceFrom, currentIndex)) != -1) { - buf.append(source.substring(currentIndex, matchIndex)); - buf.append(replaceTo); - currentIndex= matchIndex + replaceFrom.length(); - } - buf.append(source.substring(currentIndex)); - return buf.toString(); - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/reorg/ReorgUtils.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/reorg/ReorgUtils.java deleted file mode 100644 index 53403d8b82..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/reorg/ReorgUtils.java +++ /dev/null @@ -1,676 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Stream; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; -import org.eclipse.core.resources.IProject; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.IAdaptable; -import org.eclipse.jdt.core.IClassFile; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJarEntryResource; -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.ISourceRange; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.SourceRange; -import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; -import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; -import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; -import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; -import org.eclipse.jdt.ls.core.internal.Messages; -import org.eclipse.jdt.internal.core.manipulation.JavaElementLabelsCore; - - -public class ReorgUtils { - - //workaround for bug 18311 - private static final ISourceRange fgUnknownRange= new SourceRange(-1, 0); - - private ReorgUtils() { - } - - public static boolean isArchiveOrExternalMember(IJavaElement[] elements) { - for (int i= 0; i < elements.length; i++) { - IJavaElement element= elements[i]; - IPackageFragmentRoot root= (IPackageFragmentRoot)element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - if (root != null && (root.isArchive() || root.isExternal())) { - return true; - } - } - return false; - } - - public static boolean containsOnlyProjects(List elements){ - if (elements.isEmpty()) { - return false; - } - for(Iterator iter= elements.iterator(); iter.hasNext(); ) { - if (! isProject(iter.next())) { - return false; - } - } - return true; - } - - public static boolean isProject(Object element){ - return (element instanceof IJavaProject) || (element instanceof IProject); - } - - // /** - // * Checks whether the given list contains only working sets. - // * - // * @param elements the list with elements to check - // * @return true if the list contains only working sets, false - // * otherwise - // * @since 3.5 - // */ - // public static boolean containsOnlyWorkingSets (List elements){ - // if (elements.isEmpty()) { - // return false; - // } - // for (Iterator iter= elements.iterator(); iter.hasNext();) { - // if (!isWorkingSet(iter.next())) { - // return false; - // } - // } - // return true; - // } - - // /** - // * Checks whether the given object is a working set. - // * - // * @param element the element to test - // * @return true if the element is a working set, false otherwise - // * @since 3.5 - // * - // */ - // - // public static boolean isWorkingSet(Object element){ - // return (element instanceof IWorkingSet); - // } - - public static boolean isInsideCompilationUnit(IJavaElement element) { - return !(element instanceof ICompilationUnit) && - hasAncestorOfType(element, IJavaElement.COMPILATION_UNIT); - } - - public static boolean isInsideClassFile(IJavaElement element) { - return !(element instanceof IClassFile) && - hasAncestorOfType(element, IJavaElement.CLASS_FILE); - } - - public static boolean hasAncestorOfType(IJavaElement element, int type){ - return element.getAncestor(type) != null; - } - - /* - * May be null. - */ - public static ICompilationUnit getCompilationUnit(IJavaElement javaElement){ - if (javaElement instanceof ICompilationUnit) { - return (ICompilationUnit) javaElement; - } - return (ICompilationUnit) javaElement.getAncestor(IJavaElement.COMPILATION_UNIT); - } - - /* - * some of the returned elements may be null. - */ - public static ICompilationUnit[] getCompilationUnits(IJavaElement[] javaElements){ - ICompilationUnit[] result= new ICompilationUnit[javaElements.length]; - for (int i= 0; i < javaElements.length; i++) { - result[i]= getCompilationUnit(javaElements[i]); - } - return result; - } - - public static IResource getResource(IJavaElement element){ - if (element instanceof ICompilationUnit) { - return ((ICompilationUnit)element).getPrimary().getResource(); - } else { - return element.getResource(); - } - } - - public static IResource[] getResources(IJavaElement[] elements) { - IResource[] result= new IResource[elements.length]; - for (int i= 0; i < elements.length; i++) { - result[i]= ReorgUtils.getResource(elements[i]); - } - return result; - } - - public static String getName(IResource resource) { - String resourceLabel= BasicElementLabels.getResourceName(resource); - switch (resource.getType()){ - case IResource.FILE: - return Messages.format(RefactoringCoreMessages.ReorgUtils_0, resourceLabel); - case IResource.FOLDER: - return Messages.format(RefactoringCoreMessages.ReorgUtils_1, resourceLabel); - case IResource.PROJECT: - return Messages.format(RefactoringCoreMessages.ReorgUtils_2, resourceLabel); - default: - Assert.isTrue(false); - return null; - } - } - - public static String getName(IJavaElement element) throws JavaModelException { - String pattern= createNamePattern(element); - String arg= JavaElementLabelsCore.getElementLabel(element, JavaElementLabelsCore.ALL_DEFAULT); - return Messages.format(pattern, arg); - } - - private static String createNamePattern(IJavaElement element) throws JavaModelException { - switch(element.getElementType()){ - case IJavaElement.CLASS_FILE: - return RefactoringCoreMessages.ReorgUtils_3; - case IJavaElement.COMPILATION_UNIT: - return RefactoringCoreMessages.ReorgUtils_4; - case IJavaElement.FIELD: - return RefactoringCoreMessages.ReorgUtils_5; - case IJavaElement.IMPORT_CONTAINER: - return RefactoringCoreMessages.ReorgUtils_6; - case IJavaElement.IMPORT_DECLARATION: - return RefactoringCoreMessages.ReorgUtils_7; - case IJavaElement.INITIALIZER: - return RefactoringCoreMessages.ReorgUtils_8; - case IJavaElement.JAVA_PROJECT: - return RefactoringCoreMessages.ReorgUtils_9; - case IJavaElement.METHOD: - if (((IMethod)element).isConstructor()) { - return RefactoringCoreMessages.ReorgUtils_10; - } else { - return RefactoringCoreMessages.ReorgUtils_11; - } - case IJavaElement.PACKAGE_DECLARATION: - return RefactoringCoreMessages.ReorgUtils_12; - case IJavaElement.PACKAGE_FRAGMENT: - if (JavaElementUtil.isDefaultPackage(element)) { - return RefactoringCoreMessages.ReorgUtils_13; - } else { - return RefactoringCoreMessages.ReorgUtils_14; - } - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - if (((IPackageFragmentRoot) element).isArchive()) { - return RefactoringCoreMessages.ReorgUtils_21; - } - if (isSourceFolder(element)) { - return RefactoringCoreMessages.ReorgUtils_15; - } - if (isClassFolder(element)) { - return RefactoringCoreMessages.ReorgUtils_16; - } - return RefactoringCoreMessages.ReorgUtils_17; - case IJavaElement.TYPE: - IType type= (IType)element; - if (type.isAnonymous()) { - return RefactoringCoreMessages.ReorgUtils_20; - } - return RefactoringCoreMessages.ReorgUtils_18; - default: - Assert.isTrue(false); - return null; - } - } - - public static IResource[] getResources(List elements) { - List resources= new ArrayList<>(elements.size()); - for (Iterator iter= elements.iterator(); iter.hasNext();) { - Object element= iter.next(); - if (element instanceof IResource) { - resources.add((IResource) element); - } - } - return resources.toArray(new IResource[resources.size()]); - } - - public static IJavaElement[] getJavaElements(List elements) { - List resources= new ArrayList<>(elements.size()); - for (Iterator iter= elements.iterator(); iter.hasNext();) { - Object element= iter.next(); - if (element instanceof IJavaElement) { - resources.add((IJavaElement) element); - } - } - return resources.toArray(new IJavaElement[resources.size()]); - } - - /** - * Returns the jar entry resources from the list of elements. - * - * @param elements the list of elements - * @return the array of jar entry resources - * @since 3.6 - */ - public static IJarEntryResource[] getJarEntryResources(List elements) { - List resources= new ArrayList<>(elements.size()); - for (Iterator iter= elements.iterator(); iter.hasNext();) { - Object element= iter.next(); - if (element instanceof IJarEntryResource) { - resources.add((IJarEntryResource) element); - } - } - return resources.toArray(new IJarEntryResource[resources.size()]); - } - - // public static IWorkingSet[] getWorkingSets(List elements) { - // List result= new ArrayList<>(1); - // for (Iterator iter= elements.iterator(); iter.hasNext();) { - // Object element= iter.next(); - // if (element instanceof IWorkingSet) { - // result.add((IWorkingSet) element); - // } - // } - // return result.toArray(new IWorkingSet[result.size()]); - // } - - public static boolean hasSourceAvailable(IMember member) throws JavaModelException{ - return ! member.isBinary() || - (member.getSourceRange() != null && ! fgUnknownRange.equals(member.getSourceRange())); - } - - public static IResource[] setMinus(IResource[] setToRemoveFrom, IResource[] elementsToRemove) { - Set setMinus= new HashSet<>(setToRemoveFrom.length - setToRemoveFrom.length); - setMinus.addAll(Arrays.asList(setToRemoveFrom)); - setMinus.removeAll(Arrays.asList(elementsToRemove)); - return setMinus.toArray(new IResource[setMinus.size()]); - } - - public static IJavaElement[] setMinus(IJavaElement[] setToRemoveFrom, IJavaElement[] elementsToRemove) { - Set setMinus= new HashSet<>(setToRemoveFrom.length - setToRemoveFrom.length); - setMinus.addAll(Arrays.asList(setToRemoveFrom)); - setMinus.removeAll(Arrays.asList(elementsToRemove)); - return setMinus.toArray(new IJavaElement[setMinus.size()]); - } - - public static IJavaElement[] union(IJavaElement[] set1, IJavaElement[] set2) { - //use linked set to keep element order - Set union= new LinkedHashSet<>(set1.length + set2.length); - union.addAll(Arrays.asList(set1)); - union.addAll(Arrays.asList(set2)); - return union.toArray(new IJavaElement[union.size()]); - } - - public static IResource[] union(IResource[] set1, IResource[] set2) { - Stream nonNullResources= Stream.concat(Arrays.stream(set1), Arrays.stream(set2)).filter(Objects::nonNull); - //use linked set to keep element order - Set union= new LinkedHashSet<>(set1.length + set2.length); - nonNullResources.forEach(x -> union.add(x)); - return union.toArray(new IResource[union.size()]); - } - - public static IType[] getMainTypes(IJavaElement[] javaElements) throws JavaModelException { - List result= new ArrayList<>(); - for (int i= 0; i < javaElements.length; i++) { - IJavaElement element= javaElements[i]; - if (element instanceof IType && JavaElementUtil.isMainType((IType)element)) { - result.add(element); - } - } - return result.toArray(new IType[result.size()]); - } - - public static IFolder[] getFolders(IResource[] resources) { - Set result= getResourcesOfType(resources, IResource.FOLDER); - return result.toArray(new IFolder[result.size()]); - } - - public static IFile[] getFiles(IResource[] resources) { - Set result= getResourcesOfType(resources, IResource.FILE); - return result.toArray(new IFile[result.size()]); - } - - //the result can be cast down to the requested type array - public static Set getResourcesOfType(IResource[] resources, int typeMask){ - Set result= new HashSet<>(resources.length); - for (int i= 0; i < resources.length; i++) { - if (isOfType(resources[i], typeMask)) { - result.add(resources[i]); - } - } - return result; - } - - //the result can be cast down to the requested type array - //type is _not_ a mask - public static List getElementsOfType(IJavaElement[] javaElements, int type){ - List result= new ArrayList<>(javaElements.length); - for (int i= 0; i < javaElements.length; i++) { - if (isOfType(javaElements[i], type)) { - result.add(javaElements[i]); - } - } - return result; - } - - public static boolean hasElementsNotOfType(IResource[] resources, int typeMask) { - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource != null && ! isOfType(resource, typeMask)) { - return true; - } - } - return false; - } - - //type is _not_ a mask - public static boolean hasElementsNotOfType(IJavaElement[] javaElements, int type) { - for (int i= 0; i < javaElements.length; i++) { - IJavaElement element= javaElements[i]; - if (element != null && ! isOfType(element, type)) { - return true; - } - } - return false; - } - - //type is _not_ a mask - public static boolean hasElementsOfType(IJavaElement[] javaElements, int type) { - for (int i= 0; i < javaElements.length; i++) { - IJavaElement element= javaElements[i]; - if (element != null && isOfType(element, type)) { - return true; - } - } - return false; - } - - public static boolean hasElementsOfType(IJavaElement[] javaElements, int[] types) { - for (int i= 0; i < types.length; i++) { - if (hasElementsOfType(javaElements, types[i])) { - return true; - } - } - return false; - } - - - public static boolean hasOnlyElementsOfType(IJavaElement[] javaElements, int[] types) { - for (int i= 0; i < javaElements.length; i++) { - IJavaElement element= javaElements[i]; - boolean found= false; - for (int j= 0; j < types.length && !found; j++) { - if (isOfType(element, types[j])) { - found= true; - } - } - if (!found) { - return false; - } - } - - return true; - } - - public static boolean hasElementsOfType(IResource[] resources, int typeMask) { - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource != null && isOfType(resource, typeMask)) { - return true; - } - } - return false; - } - - private static boolean isOfType(IJavaElement element, int type) { - return element.getElementType() == type;//this is _not_ a mask - } - - private static boolean isOfType(IResource resource, int type) { - return resource != null && isFlagSet(resource.getType(), type); - } - - private static boolean isFlagSet(int flags, int flag){ - return (flags & flag) != 0; - } - - public static boolean isSourceFolder(IJavaElement javaElement) throws JavaModelException { - return (javaElement instanceof IPackageFragmentRoot) && - ((IPackageFragmentRoot)javaElement).getKind() == IPackageFragmentRoot.K_SOURCE; - } - - public static boolean isClassFolder(IJavaElement javaElement) throws JavaModelException { - return (javaElement instanceof IPackageFragmentRoot) && - ((IPackageFragmentRoot)javaElement).getKind() == IPackageFragmentRoot.K_BINARY; - } - - public static boolean isPackageFragmentRoot(IJavaProject javaProject) throws JavaModelException{ - return getCorrespondingPackageFragmentRoot(javaProject) != null; - } - - private static boolean isPackageFragmentRootCorrespondingToProject(IPackageFragmentRoot root) { - return root.getResource() instanceof IProject; - } - - public static IPackageFragmentRoot getCorrespondingPackageFragmentRoot(IJavaProject p) throws JavaModelException { - IPackageFragmentRoot[] roots= p.getPackageFragmentRoots(); - for (int i= 0; i < roots.length; i++) { - if (isPackageFragmentRootCorrespondingToProject(roots[i])) { - return roots[i]; - } - } - return null; - } - - public static boolean containsLinkedResources(IResource[] resources){ - for (int i= 0; i < resources.length; i++) { - if (resources[i] != null && resources[i].isLinked()) { - return true; - } - } - return false; - } - - public static boolean containsLinkedResources(IJavaElement[] javaElements){ - for (int i= 0; i < javaElements.length; i++) { - IResource res= getResource(javaElements[i]); - if (res != null && res.isLinked()) { - return true; - } - } - return false; - } - - public static boolean canBeDestinationForLinkedResources(IResource resource) { - return resource.isAccessible() && resource instanceof IProject; - } - - public static boolean canBeDestinationForLinkedResources(IJavaElement javaElement) { - if (javaElement instanceof IPackageFragmentRoot){ - return isPackageFragmentRootCorrespondingToProject((IPackageFragmentRoot)javaElement); - } else if (javaElement instanceof IJavaProject){ - return true;//XXX ??? - } else { - return false; - } - } - - public static boolean isParentInWorkspaceOrOnDisk(IPackageFragment pack, IPackageFragmentRoot root){ - if (pack == null) { - return false; - } - IJavaElement packParent= pack.getParent(); - if (packParent == null) { - return false; - } - if (packParent.equals(root)) { - return true; - } - IResource packageResource= ResourceUtil.getResource(pack); - IResource packageRootResource= ResourceUtil.getResource(root); - return isParentInWorkspaceOrOnDisk(packageResource, packageRootResource); - } - - public static boolean isParentInWorkspaceOrOnDisk(IPackageFragmentRoot root, IJavaProject javaProject){ - if (root == null) { - return false; - } - IJavaElement rootParent= root.getParent(); - if (rootParent == null) { - return false; - } - if (rootParent.equals(root)) { - return true; - } - IResource packageResource= ResourceUtil.getResource(root); - IResource packageRootResource= ResourceUtil.getResource(javaProject); - return isParentInWorkspaceOrOnDisk(packageResource, packageRootResource); - } - - public static boolean isParentInWorkspaceOrOnDisk(ICompilationUnit cu, IPackageFragment dest){ - if (cu == null) { - return false; - } - IJavaElement cuParent= cu.getParent(); - if (cuParent == null) { - return false; - } - if (cuParent.equals(dest)) { - return true; - } - IResource cuResource= cu.getResource(); - IResource packageResource= ResourceUtil.getResource(dest); - return isParentInWorkspaceOrOnDisk(cuResource, packageResource); - } - - public static boolean isParentInWorkspaceOrOnDisk(IResource res, IResource maybeParent){ - if (res == null) { - return false; - } - return areEqualInWorkspaceOrOnDisk(res.getParent(), maybeParent); - } - - public static boolean areEqualInWorkspaceOrOnDisk(IResource r1, IResource r2){ - if (r1 == null || r2 == null) { - return false; - } - if (r1.equals(r2)) { - return true; - } - URI r1Location= r1.getLocationURI(); - URI r2Location= r2.getLocationURI(); - if (r1Location == null || r2Location == null) { - return false; - } - return r1Location.equals(r2Location); - } - - public static IResource[] getNotNulls(IResource[] resources) { - Set result= new LinkedHashSet<>(resources.length); - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource != null) { - result.add(resource); - } - } - return result.toArray(new IResource[result.size()]); - } - - public static IResource[] getNotLinked(IResource[] resources) { - Collection result= new LinkedHashSet<>(resources.length); - for (int i= 0; i < resources.length; i++) { - IResource resource= resources[i]; - if (resource != null && ! result.contains(resource) && ! resource.isLinked()) { - result.add(resource); - } - } - return result.toArray(new IResource[result.size()]); - } - - /* List javaElements - * return ICompilationUnit -> List - */ - public static Map> groupByCompilationUnit(List javaElements){ - Map> result= new HashMap<>(); - for (Iterator iter= javaElements.iterator(); iter.hasNext();) { - IJavaElement element= iter.next(); - ICompilationUnit cu= ReorgUtils.getCompilationUnit(element); - if (cu != null){ - if (! result.containsKey(cu)) { - result.put(cu, new ArrayList<>(1)); - } - result.get(cu).add(element); - } - } - return result; - } - - public static void splitIntoJavaElementsAndResources(Object[] elements, List javaElementResult, List resourceResult) { - for (int i= 0; i < elements.length; i++) { - Object element= elements[i]; - if (element instanceof IJavaElement) { - javaElementResult.add((IJavaElement) element); - } else if (element instanceof IResource) { - IResource resource= (IResource)element; - IJavaElement jElement= JavaCore.create(resource); - if (jElement != null && jElement.exists()) { - javaElementResult.add(jElement); - } else { - resourceResult.add(resource); - } - } - } - } - - public static boolean containsElementOrParent(Set elements, IJavaElement element) { - IJavaElement curr= element; - do { - if (elements.contains(curr)) { - return true; - } - curr= curr.getParent(); - } while (curr != null); - return false; - } - - public static boolean containsElementOrParent(Set elements, IResource element) { - IResource curr= element; - do { - if (elements.contains(curr)) { - return true; - } - IJavaElement jElement= JavaCore.create(curr); - if (jElement != null && jElement.exists()) { - return containsElementOrParent(elements, jElement); - } - curr= curr.getParent(); - } while (curr != null); - return false; - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/surround/ExceptionAnalyzer.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/surround/ExceptionAnalyzer.java deleted file mode 100644 index 3d35fd1f7e..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/refactoring/surround/ExceptionAnalyzer.java +++ /dev/null @@ -1,233 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.refactoring.surround; - -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.ConstructorInvocation; -import org.eclipse.jdt.core.dom.CreationReference; -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.LambdaExpression; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodReference; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SuperMethodReference; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeMethodReference; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.internal.corext.dom.Bindings; -import org.eclipse.jdt.internal.corext.dom.Selection; -import org.eclipse.jdt.internal.corext.refactoring.util.AbstractExceptionAnalyzer; -import org.eclipse.jdt.ls.core.internal.text.correction.QuickAssistProcessor; - -public class ExceptionAnalyzer extends AbstractExceptionAnalyzer { - - private Selection fSelection; - private static ASTNode fEnclosingNode; - - private static class ExceptionComparator implements Comparator { - @Override - public int compare(ITypeBinding o1, ITypeBinding o2) { - int d1 = getDepth(o1); - int d2 = getDepth(o2); - if (d1 < d2) { - return 1; - } - if (d1 > d2) { - return -1; - } - return 0; - } - - private int getDepth(ITypeBinding binding) { - int result = 0; - while (binding != null) { - binding = binding.getSuperclass(); - result++; - } - return result; - } - } - - private ExceptionAnalyzer(ASTNode enclosingNode, Selection selection) { - Assert.isNotNull(selection); - fEnclosingNode = enclosingNode; - fSelection = selection; - } - - public static ITypeBinding[] perform(ASTNode enclosingNode, Selection selection) { - ExceptionAnalyzer analyzer = new ExceptionAnalyzer(enclosingNode, selection); - enclosingNode.accept(analyzer); - List exceptions = analyzer.getCurrentExceptions(); - if (enclosingNode.getNodeType() == ASTNode.METHOD_DECLARATION) { - List thrownExceptions = ((MethodDeclaration) enclosingNode).thrownExceptionTypes(); - for (Iterator thrown = thrownExceptions.iterator(); thrown.hasNext();) { - ITypeBinding thrownException = thrown.next().resolveBinding(); - if (thrownException != null) { - updateExceptionsList(exceptions, thrownException); - } - } - } else { - ITypeBinding typeBinding = null; - if (enclosingNode.getLocationInParent() == LambdaExpression.BODY_PROPERTY) { - typeBinding = ((LambdaExpression) enclosingNode.getParent()).resolveTypeBinding(); - } else if (enclosingNode instanceof MethodReference) { - typeBinding = ((MethodReference) enclosingNode).resolveTypeBinding(); - } - if (typeBinding != null) { - IMethodBinding methodBinding = typeBinding.getFunctionalInterfaceMethod(); - if (methodBinding != null) { - for (ITypeBinding thrownException : methodBinding.getExceptionTypes()) { - updateExceptionsList(exceptions, thrownException); - } - } - } - } - Collections.sort(exceptions, new ExceptionComparator()); - return exceptions.toArray(new ITypeBinding[exceptions.size()]); - } - - private static void updateExceptionsList(List exceptions, ITypeBinding thrownException) { - for (Iterator excep = exceptions.iterator(); excep.hasNext();) { - ITypeBinding exception = excep.next(); - if (exception.isAssignmentCompatible(thrownException)) { - excep.remove(); - } - } - } - - @Override - public boolean visit(ExpressionMethodReference node) { - return handleMethodReference(node); - } - - @Override - public boolean visit(TypeMethodReference node) { - return handleMethodReference(node); - } - - @Override - public boolean visit(SuperMethodReference node) { - return handleMethodReference(node); - } - - @Override - public boolean visit(CreationReference node) { - return handleMethodReference(node); - } - - @Override - public boolean visit(ThrowStatement node) { - ITypeBinding exception = node.getExpression().resolveTypeBinding(); - if (!isSelected(node) || exception == null || Bindings.isRuntimeException(exception)) { - return true; - } - - addException(exception, node.getAST()); - return true; - } - - @Override - public boolean visit(MethodInvocation node) { - if (!isSelected(node)) { - return false; - } - return handleExceptions(node.resolveMethodBinding(), node); - } - - @Override - public boolean visit(SuperMethodInvocation node) { - if (!isSelected(node)) { - return false; - } - return handleExceptions(node.resolveMethodBinding(), node); - } - - @Override - public boolean visit(ClassInstanceCreation node) { - if (!isSelected(node)) { - return false; - } - return handleExceptions(node.resolveConstructorBinding(), node); - } - - @Override - public boolean visit(ConstructorInvocation node) { - if (!isSelected(node)) { - return false; - } - return handleExceptions(node.resolveConstructorBinding(), node); - } - - @Override - public boolean visit(SuperConstructorInvocation node) { - if (!isSelected(node)) { - return false; - } - return handleExceptions(node.resolveConstructorBinding(), node); - } - - @Override - public boolean visit(VariableDeclarationExpression node) { - if (!isSelected(node)) { - return false; - } - return super.visit(node); - } - - private boolean handleMethodReference(MethodReference node) { - if (!isSelected(node)) { - return false; - } - if (!fEnclosingNode.equals(node)) { - return false; - } - IMethodBinding referredMethodBinding = node.resolveMethodBinding(); - if (referredMethodBinding == null) { - return false; - } - IMethodBinding functionalMethod = QuickAssistProcessor.getFunctionalMethodForMethodReference(node); - if (functionalMethod == null || functionalMethod.isGenericMethod()) { // generic lambda expressions are not allowed - return false; - } - return handleExceptions(referredMethodBinding, node); - } - - 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], node.getAST()); - } - return true; - } - - private boolean isSelected(ASTNode node) { - return fSelection.getVisitSelectionMode(node) == Selection.SELECTED; - } -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/util/PatternConstructor.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/util/PatternConstructor.java deleted file mode 100644 index 90b0d62fe5..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corext/util/PatternConstructor.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.ui.util.PatternConstructor - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corext.util; - -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -/** - * - */ -public class PatternConstructor { - - - private PatternConstructor() { - // don't instantiate - } - - /** - * Creates a pattern element from the pattern string which is either a reg-ex expression or in our old - * 'StringMatcher' format. - * @param pattern The search pattern - * @param isCaseSensitive Set to true to create a case insensitive pattern - * @param isRegexSearch true if the passed string already is a reg-ex pattern - * @return The created pattern - * @throws PatternSyntaxException - */ - public static Pattern createPattern(String pattern, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException { - if (!isRegexSearch) { - pattern= asRegEx(pattern, new StringBuffer()).toString(); - } - - if (!isCaseSensitive) { - return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE); - } - - return Pattern.compile(pattern, Pattern.MULTILINE); - } - - /** - * Creates a pattern element from the pattern string which is either a reg-ex expression or in our old - * 'StringMatcher' format. - * @param patterns The search patterns - * @param isCaseSensitive Set to true to create a case insensitive pattern - * @param isRegexSearch true if the passed string already is a reg-ex pattern - * @return The created pattern - * @throws PatternSyntaxException - */ - public static Pattern createPattern(String[] patterns, boolean isCaseSensitive, boolean isRegexSearch) throws PatternSyntaxException { - StringBuffer pattern= new StringBuffer(); - for (int i= 0; i < patterns.length; i++) { - if (i > 0) { - pattern.append('|'); - } - if (isRegexSearch) { - pattern.append(patterns[i]); - } else { - asRegEx(patterns[i], pattern); - } - } - return createPattern(pattern.toString(), isCaseSensitive, true); - } - - - /** - * Translates a StringMatcher pattern (using '*' and '?') to a regex pattern string - * @param stringMatcherPattern a pattern using '*' and '?' - * @param out string buffer - * @return string buffer - */ - private static StringBuffer asRegEx(String stringMatcherPattern, StringBuffer out) { - boolean escaped= false; - boolean quoting= false; - - int i= 0; - while (i < stringMatcherPattern.length()) { - char ch= stringMatcherPattern.charAt(i++); - - if (ch == '*' && !escaped) { - if (quoting) { - out.append("\\E"); //$NON-NLS-1$ - quoting= false; - } - out.append(".*"); //$NON-NLS-1$ - escaped= false; - continue; - } else if (ch == '?' && !escaped) { - if (quoting) { - out.append("\\E"); //$NON-NLS-1$ - quoting= false; - } - out.append("."); //$NON-NLS-1$ - escaped= false; - continue; - } else if (ch == '\\' && !escaped) { - escaped= true; - continue; - - } else if (ch == '\\' && escaped) { - escaped= false; - if (quoting) { - out.append("\\E"); //$NON-NLS-1$ - quoting= false; - } - out.append("\\\\"); //$NON-NLS-1$ - continue; - } - - if (!quoting) { - out.append("\\Q"); //$NON-NLS-1$ - quoting= true; - } - if (escaped && ch != '*' && ch != '?' && ch != '\\') { - out.append('\\'); - } - out.append(ch); - escaped= ch == '\\'; - - } - if (quoting) - { - out.append("\\E"); //$NON-NLS-1$ - } - - return out; - } - -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/FixCorrectionProposal.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/FixCorrectionProposal.java deleted file mode 100644 index 5df5043122..0000000000 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/FixCorrectionProposal.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Originally copied from org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposal - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ls.core.internal.corrections.proposals; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.refactoring.CompilationUnitChange; -import org.eclipse.jdt.internal.corext.fix.ICleanUpCore; -import org.eclipse.jdt.internal.corext.fix.IProposableFix; -import org.eclipse.jdt.internal.ui.text.correction.IInvocationContextCore; -import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposalCore; -import org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages; -import org.eclipse.ltk.core.refactoring.TextChange; -import org.eclipse.ltk.core.refactoring.TextFileChange; - -/** - * A correction proposal which uses an {@link ICleanUpFix} to fix a problem. A - * fix correction proposal may have an {@link ICleanUp} attached which can be - * executed instead of the provided IFix. - */ -public class FixCorrectionProposal extends LinkedCorrectionProposalCore { - - private final IProposableFix fFix; - private final ICleanUpCore fCleanUp; - private CompilationUnit fCompilationUnit; - - public FixCorrectionProposal(IProposableFix fix, ICleanUpCore cleanUp, int relevance, IInvocationContextCore context) { - super(fix.getDisplayString(), context.getCompilationUnit(), null, relevance); - fFix = fix; - fCleanUp = cleanUp; - fCompilationUnit = context.getASTRoot(); - } - - public IStatus getFixStatus() { - return fFix.getStatus(); - } - - public ICleanUpCore getCleanUp() { - return fCleanUp; - } - - @Override - public String getAdditionalProposalInfo(IProgressMonitor monitor) { - StringBuffer result = new StringBuffer(); - - IStatus status = getFixStatus(); - if (status != null && !status.isOK()) { - result.append(""); //$NON-NLS-1$ - if (status.getSeverity() == IStatus.WARNING) { - result.append(CorrectionMessages.FixCorrectionProposal_WarningAdditionalProposalInfo); - } else if (status.getSeverity() == IStatus.ERROR) { - result.append(CorrectionMessages.FixCorrectionProposal_ErrorAdditionalProposalInfo); - } - result.append(""); //$NON-NLS-1$ - result.append(status.getMessage()); - result.append("

"); //$NON-NLS-1$ - } - - String info = fFix.getAdditionalProposalInfo(); - if (info != null) { - result.append(info); - } else { - result.append(super.getAdditionalProposalInfo(monitor)); - } - - return result.toString(); - } - - @Override - public int getRelevance() { - IStatus status = getFixStatus(); - if (status != null && !status.isOK()) { - return super.getRelevance() - 100; - } else { - return super.getRelevance(); - } - } - - @Override - public TextChange createTextChange() throws CoreException { - CompilationUnitChange createChange = fFix.createChange(null); - createChange.setSaveMode(TextFileChange.LEAVE_DIRTY); - - // if (fFix instanceof ILinkedFix) { - // setLinkedProposalModel(((ILinkedFix) fFix).getLinkedPositions()); - // } - - return createChange; - } - -} diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/GetterSetterCorrectionSubProcessor.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/GetterSetterCorrectionSubProcessor.java index 60e8b2f6b4..a28acedefa 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/GetterSetterCorrectionSubProcessor.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/GetterSetterCorrectionSubProcessor.java @@ -46,6 +46,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore; import org.eclipse.jdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.text.correction.IInvocationContextCore; @@ -53,7 +54,6 @@ import org.eclipse.jdt.internal.ui.text.correction.IProposalRelevance; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.Messages; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.RefactoringAvailabilityTester; import org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages; import org.eclipse.jdt.ls.core.internal.corrections.ProposalKindWrapper; import org.eclipse.jdt.ls.core.internal.handlers.CodeActionHandler; @@ -226,7 +226,7 @@ private static ProposalKindWrapper addGetterProposal(ProposalParameter context, IJavaElement element = context.variableBinding.getJavaElement(); if (element instanceof IField field) { try { - if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) { + if (RefactoringAvailabilityTesterCore.isSelfEncapsulateAvailable(field)) { return CodeActionHandler.wrap(new SelfEncapsulateFieldProposal(relevance, field), CodeActionKind.Refactor); } } catch (JavaModelException e) { @@ -310,7 +310,7 @@ private static ProposalKindWrapper addSetterProposal(ProposalParameter context, IJavaElement element = context.variableBinding.getJavaElement(); if (element instanceof IField field) { try { - if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field)) { + if (RefactoringAvailabilityTesterCore.isSelfEncapsulateAvailable(field)) { return CodeActionHandler.wrap(new SelfEncapsulateFieldProposal(relevance, field), CodeActionKind.Refactor); } } catch (JavaModelException e) { diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/LocalCorrectionsSubProcessor.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/LocalCorrectionsSubProcessor.java index e68be98c70..dcdd02ff9f 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/LocalCorrectionsSubProcessor.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/corrections/proposals/LocalCorrectionsSubProcessor.java @@ -95,6 +95,7 @@ import org.eclipse.jdt.internal.corext.fix.SealedClassFixCore; import org.eclipse.jdt.internal.corext.fix.UnimplementedCodeFixCore; import org.eclipse.jdt.internal.corext.fix.UnusedCodeFixCore; +import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer; import org.eclipse.jdt.internal.corext.refactoring.util.SurroundWithAnalyzer; @@ -113,7 +114,6 @@ import org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposalCore; import org.eclipse.jdt.internal.ui.util.ASTHelper; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages; import org.eclipse.jdt.ls.core.internal.corrections.InnovationContext; import org.eclipse.jdt.ls.core.internal.corrections.InvertBooleanUtility; diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/MoveHandler.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/MoveHandler.java index ca9727c679..eeff31f754 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/MoveHandler.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/MoveHandler.java @@ -66,6 +66,7 @@ import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory; +import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtilsCore; import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInnerToTopRefactoring; import org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMethodProcessor; import org.eclipse.jdt.internal.corext.refactoring.structure.MoveStaticMembersProcessor; @@ -76,7 +77,6 @@ import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.ProjectUtils; import org.eclipse.jdt.ls.core.internal.ResourceUtils; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.reorg.ReorgUtils; import org.eclipse.jdt.ls.core.internal.corrections.DiagnosticsHelper; import org.eclipse.jdt.ls.core.internal.corrections.InnovationContext; import org.eclipse.jdt.ls.core.internal.handlers.GetRefactorEditHandler.RefactorWorkspaceEdit; @@ -345,8 +345,8 @@ private static RefactorWorkspaceEdit moveCU(String[] sourceUris, String targetUr SubMonitor submonitor = SubMonitor.convert(monitor, "Moving File...", 100); try { - IResource[] resources = ReorgUtils.getResources(elements); - IJavaElement[] javaElements = ReorgUtils.getJavaElements(elements); + IResource[] resources = ReorgUtilsCore.getResources(elements); + IJavaElement[] javaElements = ReorgUtilsCore.getJavaElements(elements); IContainer[] targetContainers = ResourcesPlugin.getWorkspace().getRoot().findContainersForLocationURI(targetURI); if (targetContainers == null || targetContainers.length == 0) { return new RefactorWorkspaceEdit("Failed to move the files because cannot find the target folder '" + targetUri + "' in the workspace."); diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/PrepareRenameHandler.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/PrepareRenameHandler.java index 8f27b98d77..3b891bb087 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/PrepareRenameHandler.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/handlers/PrepareRenameHandler.java @@ -25,9 +25,9 @@ import org.eclipse.jdt.core.manipulation.CoreASTProvider; import org.eclipse.jdt.internal.core.manipulation.search.IOccurrencesFinder.OccurrenceLocation; import org.eclipse.jdt.internal.core.manipulation.search.OccurrencesFinder; +import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore; import org.eclipse.jdt.ls.core.internal.JDTUtils; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.RefactoringAvailabilityTester; import org.eclipse.jdt.ls.core.internal.corrections.InnovationContext; import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; import org.eclipse.lsp4j.Range; @@ -97,7 +97,7 @@ private boolean isBinaryOrPackage(ASTNode node) { IBinding resolvedBinding = name.resolveBinding(); IJavaElement element = resolvedBinding != null ? resolvedBinding.getJavaElement() : null; try { - if (element == null || element.getElementType() == IJavaElement.PACKAGE_FRAGMENT || !RefactoringAvailabilityTester.isRenameElementAvailable(element)) { + if (element == null || element.getElementType() == IJavaElement.PACKAGE_FRAGMENT || !RefactoringAvailabilityTesterCore.isRenameElementAvailable(element)) { return true; } } catch (CoreException e) { diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/text/correction/RefactorProposalUtility.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/text/correction/RefactorProposalUtility.java index 67c484f18e..33161b5808 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/text/correction/RefactorProposalUtility.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/text/correction/RefactorProposalUtility.java @@ -84,7 +84,6 @@ import org.eclipse.jdt.ls.core.internal.JavaCodeActionKind; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.Messages; -import org.eclipse.jdt.ls.core.internal.corext.refactoring.RefactoringAvailabilityTester; import org.eclipse.jdt.ls.core.internal.corext.refactoring.code.ExtractFieldRefactoring; import org.eclipse.jdt.ls.core.internal.corrections.CorrectionMessages; import org.eclipse.jdt.ls.core.internal.corrections.ProposalKindWrapper; @@ -215,7 +214,7 @@ private static ASTNode getDeclarationNode(ASTNode node, boolean alwaysShowMove) private static boolean isMoveMethodAvailable(MethodDeclaration declaration) throws JavaModelException { IMethodBinding methodBinding = declaration.resolveBinding(); IMethod method = methodBinding == null ? null : (IMethod) methodBinding.getJavaElement(); - return method != null && RefactoringAvailabilityTester.isMoveMethodAvailable(method); + return method != null && RefactoringAvailabilityTesterCore.isMoveMethodAvailable(method); } private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException { @@ -242,7 +241,7 @@ private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws J private static boolean isMoveInnerAvailable(AbstractTypeDeclaration declaration) throws JavaModelException { ITypeBinding type = declaration.resolveBinding(); if (type != null) { - return RefactoringAvailabilityTester.isMoveInnerAvailable((IType) type.getJavaElement()); + return RefactoringAvailabilityTesterCore.isMoveInnerAvailable((IType) type.getJavaElement()); } return false; @@ -926,7 +925,7 @@ public static ProposalKindWrapper getExtractInterfaceProposal(CodeActionParams p try { CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(cu); ExtractInterfaceProcessor processor = new ExtractInterfaceProcessor(type, settings); - if (RefactoringAvailabilityTester.isExtractInterfaceAvailable(type) && processor.checkInitialConditions(new NullProgressMonitor()).isOK()) { + if (RefactoringAvailabilityTesterCore.isExtractInterfaceAvailable(type) && processor.checkInitialConditions(new NullProgressMonitor()).isOK()) { CUCorrectionCommandProposal p = new CUCorrectionCommandProposal(CorrectionMessages.RefactorProcessor_extract_interface, cu, IProposalRelevance.EXTRACT_INTERFACE, RefactorProposalUtility.APPLY_REFACTORING_COMMAND_ID, Arrays.asList(RefactorProposalUtility.EXTRACT_INTERFACE_COMMAND, params)); return CodeActionHandler.wrap(p, JavaCodeActionKind.REFACTOR_EXTRACT_INTERFACE); @@ -954,7 +953,7 @@ public static ProposalKindWrapper getChangeSignatureProposal(CodeActionParams pa if (element instanceof IMethod method) { try { ChangeSignatureProcessor processor = new ChangeSignatureProcessor(method); - if (RefactoringAvailabilityTester.isChangeSignatureAvailable(method) && processor.checkInitialConditions(new NullProgressMonitor()).isOK()) { + if (RefactoringAvailabilityTesterCore.isChangeSignatureAvailable(method) && processor.checkInitialConditions(new NullProgressMonitor()).isOK()) { List parameters = new ArrayList<>(); for (ParameterInfo info : processor.getParameterInfos()) { parameters.add(new MethodParameter(info.getOldTypeName(), info.getOldName(), info.getDefaultValue() == null ? "null" : info.getDefaultValue(), info.getOldIndex()));