diff options
Diffstat (limited to 'org.eclipse.jdt.ui/core extension/org')
52 files changed, 206 insertions, 12225 deletions
diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/buildpath/ClasspathModifier.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/buildpath/ClasspathModifier.java index 927787b4a4..8f10ae5d81 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/buildpath/ClasspathModifier.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/buildpath/ClasspathModifier.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -55,7 +55,7 @@ import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.buildpaths.ArchiveFileFilter; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathSupport; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchy.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchy.java index 2e4b01abaf..336e049e2c 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchy.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/callhierarchy/CallHierarchy.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -38,7 +38,7 @@ import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.ui.util.StringMatcher; public class CallHierarchy { @@ -284,7 +284,7 @@ public class CallHierarchy { ITypeRoot typeRoot= member.getTypeRoot(); try { if (typeRoot.exists() && typeRoot.getBuffer() != null) { - ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(typeRoot); parser.setResolveBindings(resolveBindings); return (CompilationUnit) parser.createAST(null); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java index 447c160153..47ca9e87fa 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2010 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -36,9 +36,10 @@ import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; /** * Workspace runnable to add custom constructors initializing fields. @@ -187,7 +188,7 @@ public final class AddCustomConstructorOperation implements IWorkspaceRunnable { fResultingEdit.addChild(importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1))); if (fApply) { - JavaModelUtil.applyEdit(cu, fResultingEdit, fSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(cu, fResultingEdit, fSave, new SubProgressMonitor(monitor, 1)); } } } finally { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java index c5de8c0112..09284330a8 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -43,7 +43,7 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.internal.corext.util.DelegateEntryComparator; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; /** * Workspace runnable to add delegate methods. @@ -194,7 +194,7 @@ public final class AddDelegateMethodsOperation implements IWorkspaceRunnable { fResultingEdit.addChild(importRewrite.rewriteImports(new SubProgressMonitor(monitor, 1))); if (fApply) { - JavaModelUtil.applyEdit(cu, fResultingEdit, fSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(cu, fResultingEdit, fSave, new SubProgressMonitor(monitor, 1)); } } } finally { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java index a7124596e0..8ee4fdd1f2 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -52,6 +52,7 @@ import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; @@ -351,7 +352,7 @@ public final class AddGetterSetterOperation implements IWorkspaceRunnable { } fEdit= astRewrite.rewriteAST(); if (fApply) { - JavaModelUtil.applyEdit(unit, fEdit, fSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(unit, fEdit, fSave, new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java index d13054312d..4fffb50e89 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -62,7 +62,9 @@ import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatch; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; @@ -73,7 +75,6 @@ import org.eclipse.jdt.ui.SharedASTProvider; import org.eclipse.jdt.internal.ui.JavaUIStatus; import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.text.correction.SimilarElementsRequestor; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; /** @@ -186,7 +187,7 @@ public class AddImportsOperation implements IWorkspaceRunnable { fResultingEdit= res; if (fApply) { - JavaModelUtil.applyEdit(fCompilationUnit, res, fDoSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(fCompilationUnit, res, fDoSave, new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java index 200071cf7e..1bb77d72fc 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -47,7 +47,7 @@ import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.util.MethodOverrideTester; -import org.eclipse.jdt.internal.corext.util.Strings; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache; import org.eclipse.jdt.ui.CodeGeneration; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java index f7a14f5355..1ea4b4f059 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -41,7 +41,7 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; @@ -251,7 +251,7 @@ public final class AddUnimplementedConstructorsOperation implements IWorkspaceRu edit.addChild(astRewrite.rewriteAST()); if (fApply) { - JavaModelUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java index c065d72081..cf005f8c2b 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedMethodsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -43,7 +43,7 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.MethodsSourcePositionComparator; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; @@ -231,7 +231,7 @@ public final class AddUnimplementedMethodsOperation implements IWorkspaceRunnabl edit.addChild(astRewrite.rewriteAST()); if (fApply) { - JavaModelUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(cu, edit, fSave, new SubProgressMonitor(monitor, 1)); } } finally { monitor.done(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java index 598e3d2294..de4075825a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java @@ -76,6 +76,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.CodeGeneration; @@ -338,7 +339,7 @@ public final class GenerateHashCodeEqualsOperation implements IWorkspaceRunnable fEdit= fRewrite.createChange(true).getEdit(); if (fApply) - JavaModelUtil.applyEdit(cu, fEdit, fSave, monitor); + JavaElementUtil.applyEdit(cu, fEdit, fSave, monitor); } } finally { monitor.done(); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java index fec65431f1..2ea1f69b55 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java @@ -59,20 +59,21 @@ import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.TypeNameMatch; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; -import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.TypeNameMatchCollector; import org.eclipse.jdt.ui.SharedASTProvider; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation; import org.eclipse.jdt.internal.ui.text.correction.SimilarElementsRequestor; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; public class OrganizeImportsOperation implements IWorkspaceRunnable { public static interface IChooseImportQuery { @@ -192,7 +193,7 @@ public class OrganizeImportsOperation implements IWorkspaceRunnable { public UnresolvedTypeData(SimpleName ref) { this.ref= ref; - this.typeKinds= ASTResolving.getPossibleTypeKinds(ref, true); + this.typeKinds= org.eclipse.jdt.internal.ui.text.correction.ASTResolving.getPossibleTypeKinds(ref, true); this.foundInfos= new ArrayList<>(3); } @@ -348,7 +349,7 @@ public class OrganizeImportsOperation implements IWorkspaceRunnable { TypeNameMatchCollector collector= new TypeNameMatchCollector(typesFound); new SearchEngine().searchAllTypeNames(null, allTypes, scope, collector, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor); - boolean is50OrHigher= JavaModelUtil.is50OrHigher(project); + boolean is50OrHigher= JavaModelUtil.is50OrHigher(project); for (i= 0; i < typesFound.size(); i++) { TypeNameMatch curr= typesFound.get(i); @@ -526,7 +527,7 @@ public class OrganizeImportsOperation implements IWorkspaceRunnable { if (edit == null) return; - JavaModelUtil.applyEdit(fCompilationUnit, edit, fDoSave, new SubProgressMonitor(monitor, 1)); + JavaElementUtil.applyEdit(fCompilationUnit, edit, fDoSave, new SubProgressMonitor(monitor, 1)); } finally { monitor.done(); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/SortMembersOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/SortMembersOperation.java index 84302e45ea..5fb4bbb764 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/SortMembersOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/SortMembersOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -41,7 +41,7 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache; /** @@ -323,7 +323,7 @@ public class SortMembersOperation implements IWorkspaceRunnable { */ @Override public void run(IProgressMonitor monitor) throws CoreException { - CompilationUnitSorter.sort(ASTProvider.SHARED_AST_LEVEL, fCompilationUnit, fPositions, new DefaultJavaElementComparator(fDoNotSortFields), 0, monitor); + CompilationUnitSorter.sort(IASTSharedValues.SHARED_AST_LEVEL, fCompilationUnit, fPositions, new DefaultJavaElementComparator(fDoNotSortFields), 0, monitor); } /** diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java index 77395269d2..97e3b5c37f 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -101,7 +101,8 @@ import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext; import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType; import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; -import org.eclipse.jdt.internal.corext.util.Strings; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.ui.CodeStyleConfiguration; @@ -109,8 +110,8 @@ import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIStatus; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; + import org.eclipse.jdt.internal.ui.viewsupport.ProjectTemplateStore; /** @@ -332,7 +333,7 @@ public class StubUtility { */ private static String[] getParameterTypeNamesForSeeTag(IMethod overridden) { try { - ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(overridden.getJavaProject()); IBinding[] bindings= parser.createBindings(new IJavaElement[] { overridden }, null); if (bindings.length == 1 && bindings[0] instanceof IMethodBinding) { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java index 749198c4fe..e3a7aa63f0 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2.java @@ -80,7 +80,7 @@ import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.CodeGeneration; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; /** * Utilities for code generation based on AST rewrite. @@ -738,7 +738,7 @@ public final class StubUtility2 { // need an AST of the source method to preserve order of modifiers IMethod iMethod= (IMethod) method.getJavaElement(); if (iMethod != null && JavaElementUtil.isSourceAvailable(iMethod)) { - ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(iMethod.getTypeRoot()); parser.setIgnoreMethodBodies(true); CompilationUnit otherCU= (CompilationUnit) parser.createAST(null); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/GenerateToStringOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/GenerateToStringOperation.java index 4042b3632e..a2e75b6784 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/GenerateToStringOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/GenerateToStringOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2010, 2011 Mateusz Matela and others. + * Copyright (c) 2010, 2016 Mateusz Matela and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -41,7 +41,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationMessages; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; /** @@ -101,7 +101,7 @@ public class GenerateToStringOperation implements IWorkspaceRunnable { } } - JavaModelUtil.applyEdit((ICompilationUnit)fUnit.getJavaElement(), fRewrite.createChange(true).getEdit(), false, monitor); + JavaElementUtil.applyEdit((ICompilationUnit)fUnit.getJavaElement(), fRewrite.createChange(true).getEdit(), false, monitor); } } finally { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTBatchParser.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTBatchParser.java index 28e9b542ed..665a99dd4f 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTBatchParser.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTBatchParser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2013 IBM Corporation and others. + * Copyright (c) 2007, 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 v1.0 * which accompanies this distribution, and is available at @@ -27,8 +27,6 @@ import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.ASTRequestor; import org.eclipse.jdt.core.dom.IBinding; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; - /** * Creates AST from a set of compilation units. Uses the * batch parser. Splits the set of compilation units in subsets @@ -113,7 +111,7 @@ public class ASTBatchParser { * @return an AST parser capable of creating ASTs of compilation units in project */ protected ASTParser createParser(IJavaProject project) { - ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser result= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); result.setResolveBindings(true); result.setProject(project); diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java deleted file mode 100644 index 17e6913918..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTFlattener.java +++ /dev/null @@ -1,1814 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import java.util.Iterator; -import java.util.List; - -import org.eclipse.core.runtime.Assert; - -import org.eclipse.jdt.core.dom.*; - -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; - - -public class ASTFlattener extends GenericVisitor { - - /** - * @deprecated to avoid deprecation warnings - */ - @Deprecated - private static final int JLS3= AST.JLS3; - /** - * @deprecated to avoid deprecation warnings - */ - @Deprecated - private static final int JLS4= AST.JLS4; - - /** - * The string buffer into which the serialized representation of the AST is - * written. - */ - protected StringBuffer fBuffer; - - /** - * Creates a new AST printer. - */ - public ASTFlattener() { - this.fBuffer= new StringBuffer(); - } - - /** - * Returns the string accumulated in the visit. - * - * @return the serialized - */ - public String getResult() { - return this.fBuffer.toString(); - } - - /** - * Resets this printer so that it can be used again. - */ - public void reset() { - this.fBuffer.setLength(0); - } - - public static String asString(ASTNode node) { - Assert.isTrue(node.getAST().apiLevel() == ASTProvider.SHARED_AST_LEVEL); - - ASTFlattener flattener= new ASTFlattener(); - node.accept(flattener); - return flattener.getResult(); - } - - - @Override - protected boolean visitNode(ASTNode node) { - Assert.isTrue(false, "No implementation to flatten node: " + node.toString()); //$NON-NLS-1$ - return false; - } - - /** - * Appends the text representation of the given modifier flags, followed by a single space. - * Used for 3.0 modifiers and annotations. - * - * @param ext the list of modifier and annotation nodes - * (element type: <code>IExtendedModifier</code>) - */ - private void printModifiers(List<IExtendedModifier> ext) { - for (Iterator<IExtendedModifier> it= ext.iterator(); it.hasNext();) { - ASTNode p= (ASTNode) it.next(); - p.accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - } - } - - private void printReferenceTypeArguments(List<Type> typeArguments) { - this.fBuffer.append("::");//$NON-NLS-1$ - if (!typeArguments.isEmpty()) { - this.fBuffer.append('<'); - for (Iterator<Type> it = typeArguments.iterator(); it.hasNext(); ) { - Type t = it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(','); - } - } - this.fBuffer.append('>'); - } - } - - void printTypeAnnotations(AnnotatableType node) { - if (node.getAST().apiLevel() >= AST.JLS8) { - printAnnotationsList(node.annotations()); - } - } - - void printAnnotationsList(List<? extends Annotation> annotations) { - for (Iterator<? extends Annotation> it = annotations.iterator(); it.hasNext(); ) { - Annotation annotation = it.next(); - annotation.accept(this); - this.fBuffer.append(' '); - } - } - - /** - * @param node node - * @return component type - * @deprecated to avoid deprecation warning - */ - @Deprecated - private static Type getComponentType(ArrayType node) { - return node.getComponentType(); - } - - /** - * @param node node - * @return thrown exception names - * @deprecated to avoid deprecation warning - */ - @Deprecated - private static List<Name> getThrownExceptions(MethodDeclaration node) { - return node.thrownExceptions(); - } - - /* - * @see ASTVisitor#visit(AnnotationTypeDeclaration) - * @since 3.0 - */ - @Override - public boolean visit(AnnotationTypeDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - printModifiers(node.modifiers()); - this.fBuffer.append("@interface ");//$NON-NLS-1$ - node.getName().accept(this); - this.fBuffer.append(" {");//$NON-NLS-1$ - for (Iterator<BodyDeclaration> it= node.bodyDeclarations().iterator(); it.hasNext();) { - BodyDeclaration d= it.next(); - d.accept(this); - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(AnnotationTypeMemberDeclaration) - * @since 3.0 - */ - @Override - public boolean visit(AnnotationTypeMemberDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - printModifiers(node.modifiers()); - node.getType().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getName().accept(this); - this.fBuffer.append("()");//$NON-NLS-1$ - if (node.getDefault() != null) { - this.fBuffer.append(" default ");//$NON-NLS-1$ - node.getDefault().accept(this); - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(AnonymousClassDeclaration) - */ - @Override - public boolean visit(AnonymousClassDeclaration node) { - this.fBuffer.append("{");//$NON-NLS-1$ - List<BodyDeclaration> bodyDeclarations= node.bodyDeclarations(); - for (Iterator<BodyDeclaration> it= bodyDeclarations.iterator(); it.hasNext();) { - BodyDeclaration b= it.next(); - b.accept(this); - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ArrayAccess) - */ - @Override - public boolean visit(ArrayAccess node) { - node.getArray().accept(this); - this.fBuffer.append("[");//$NON-NLS-1$ - node.getIndex().accept(this); - this.fBuffer.append("]");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ArrayCreation) - */ - @Override - public boolean visit(ArrayCreation node) { - this.fBuffer.append("new ");//$NON-NLS-1$ - ArrayType at= node.getType(); - int dims= at.getDimensions(); - Type elementType= at.getElementType(); - elementType.accept(this); - for (Iterator<Expression> it= node.dimensions().iterator(); it.hasNext();) { - this.fBuffer.append("[");//$NON-NLS-1$ - Expression e= it.next(); - e.accept(this); - this.fBuffer.append("]");//$NON-NLS-1$ - dims--; - } - // add empty "[]" for each extra array dimension - for (int i= 0; i < dims; i++) { - this.fBuffer.append("[]");//$NON-NLS-1$ - } - if (node.getInitializer() != null) { - node.getInitializer().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(ArrayInitializer) - */ - @Override - public boolean visit(ArrayInitializer node) { - this.fBuffer.append("{");//$NON-NLS-1$ - for (Iterator<Expression> it= node.expressions().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ArrayType) - */ - @Override - public boolean visit(ArrayType node) { - if (node.getAST().apiLevel() < AST.JLS8) { - getComponentType(node).accept(this); - this.fBuffer.append("[]");//$NON-NLS-1$ - } else { - node.getElementType().accept(this); - List<Dimension> dimensions = node.dimensions(); - for (int i = 0; i < dimensions.size() ; i++) { - Dimension dimension = dimensions.get(i); - dimension.accept(this); - } - } - return false; - } - - /* - * @see ASTVisitor#visit(AssertStatement) - */ - @Override - public boolean visit(AssertStatement node) { - this.fBuffer.append("assert ");//$NON-NLS-1$ - node.getExpression().accept(this); - if (node.getMessage() != null) { - this.fBuffer.append(" : ");//$NON-NLS-1$ - node.getMessage().accept(this); - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(Assignment) - */ - @Override - public boolean visit(Assignment node) { - node.getLeftHandSide().accept(this); - this.fBuffer.append(node.getOperator().toString()); - node.getRightHandSide().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(Block) - */ - @Override - public boolean visit(Block node) { - this.fBuffer.append("{");//$NON-NLS-1$ - for (Iterator<Statement> it= node.statements().iterator(); it.hasNext();) { - Statement s= it.next(); - s.accept(this); - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(BlockComment) - * @since 3.0 - */ - @Override - public boolean visit(BlockComment node) { - this.fBuffer.append("/* */");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(BooleanLiteral) - */ - @Override - public boolean visit(BooleanLiteral node) { - if (node.booleanValue() == true) { - this.fBuffer.append("true");//$NON-NLS-1$ - } else { - this.fBuffer.append("false");//$NON-NLS-1$ - } - return false; - } - - /* - * @see ASTVisitor#visit(BreakStatement) - */ - @Override - public boolean visit(BreakStatement node) { - this.fBuffer.append("break");//$NON-NLS-1$ - if (node.getLabel() != null) { - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getLabel().accept(this); - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(CastExpression) - */ - @Override - public boolean visit(CastExpression node) { - this.fBuffer.append("(");//$NON-NLS-1$ - node.getType().accept(this); - this.fBuffer.append(")");//$NON-NLS-1$ - node.getExpression().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(CatchClause) - */ - @Override - public boolean visit(CatchClause node) { - this.fBuffer.append("catch (");//$NON-NLS-1$ - node.getException().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(CharacterLiteral) - */ - @Override - public boolean visit(CharacterLiteral node) { - this.fBuffer.append(node.getEscapedValue()); - return false; - } - - /* - * @see ASTVisitor#visit(ClassInstanceCreation) - */ - @Override - public boolean visit(ClassInstanceCreation node) { - if (node.getExpression() != null) { - node.getExpression().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - this.fBuffer.append("new ");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeArguments().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - node.getType().accept(this); - } - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - if (node.getAnonymousClassDeclaration() != null) { - node.getAnonymousClassDeclaration().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(CompilationUnit) - */ - @Override - public boolean visit(CompilationUnit node) { - if (node.getPackage() != null) { - node.getPackage().accept(this); - } - for (Iterator<ImportDeclaration> it= node.imports().iterator(); it.hasNext();) { - ImportDeclaration d= it.next(); - d.accept(this); - } - for (Iterator<AbstractTypeDeclaration> it= node.types().iterator(); it.hasNext();) { - AbstractTypeDeclaration d= it.next(); - d.accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(ConditionalExpression) - */ - @Override - public boolean visit(ConditionalExpression node) { - node.getExpression().accept(this); - this.fBuffer.append("?");//$NON-NLS-1$ - node.getThenExpression().accept(this); - this.fBuffer.append(":");//$NON-NLS-1$ - node.getElseExpression().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(ConstructorInvocation) - */ - @Override - public boolean visit(ConstructorInvocation node) { - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeArguments().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - } - this.fBuffer.append("this(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(");");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ContinueStatement) - */ - @Override - public boolean visit(ContinueStatement node) { - this.fBuffer.append("continue");//$NON-NLS-1$ - if (node.getLabel() != null) { - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getLabel().accept(this); - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(CreationReference) - */ - @Override - public boolean visit(CreationReference node) { - node.getType().accept(this); - printReferenceTypeArguments(node.typeArguments()); - this.fBuffer.append("new");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(Dimension) - */ - @Override - public boolean visit(Dimension node) { - this.fBuffer.append(" ");//$NON-NLS-1$ - printAnnotationsList(node.annotations()); - this.fBuffer.append("[]"); //$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(DoStatement) - */ - @Override - public boolean visit(DoStatement node) { - this.fBuffer.append("do ");//$NON-NLS-1$ - node.getBody().accept(this); - this.fBuffer.append(" while (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(");");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(EmptyStatement) - */ - @Override - public boolean visit(EmptyStatement node) { - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(EnhancedForStatement) - * @since 3.0 - */ - @Override - public boolean visit(EnhancedForStatement node) { - this.fBuffer.append("for (");//$NON-NLS-1$ - node.getParameter().accept(this); - this.fBuffer.append(" : ");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(EnumConstantDeclaration) - * @since 3.0 - */ - @Override - public boolean visit(EnumConstantDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - printModifiers(node.modifiers()); - node.getName().accept(this); - if (!node.arguments().isEmpty()) { - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - } - if (node.getAnonymousClassDeclaration() != null) { - node.getAnonymousClassDeclaration().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(EnumDeclaration) - * @since 3.0 - */ - @Override - public boolean visit(EnumDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - printModifiers(node.modifiers()); - this.fBuffer.append("enum ");//$NON-NLS-1$ - node.getName().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - if (!node.superInterfaceTypes().isEmpty()) { - this.fBuffer.append("implements ");//$NON-NLS-1$ - for (Iterator<Type> it= node.superInterfaceTypes().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(" ");//$NON-NLS-1$ - } - this.fBuffer.append("{");//$NON-NLS-1$ - for (Iterator<EnumConstantDeclaration> it = node.enumConstants().iterator(); it.hasNext(); ) { - EnumConstantDeclaration d = it.next(); - d.accept(this); - // enum constant declarations do not include punctuation - if (it.hasNext()) { - // enum constant declarations are separated by commas - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - if (!node.bodyDeclarations().isEmpty()) { - this.fBuffer.append("; ");//$NON-NLS-1$ - for (Iterator<BodyDeclaration> it = node.bodyDeclarations().iterator(); it.hasNext(); ) { - BodyDeclaration d = it.next(); - d.accept(this); - // other body declarations include trailing punctuation - } - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ExpressionMethodReference) - */ - @Override - public boolean visit(ExpressionMethodReference node) { - node.getExpression().accept(this); - printReferenceTypeArguments(node.typeArguments()); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(ExpressionStatement) - */ - @Override - public boolean visit(ExpressionStatement node) { - node.getExpression().accept(this); - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(FieldAccess) - */ - @Override - public boolean visit(FieldAccess node) { - node.getExpression().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(FieldDeclaration) - */ - @Override - public boolean visit(FieldDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - node.getType().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - for (Iterator<VariableDeclarationFragment> it= node.fragments().iterator(); it.hasNext();) { - VariableDeclarationFragment f= it.next(); - f.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ForStatement) - */ - @Override - public boolean visit(ForStatement node) { - this.fBuffer.append("for (");//$NON-NLS-1$ - for (Iterator<Expression> it= node.initializers().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - } - this.fBuffer.append("; ");//$NON-NLS-1$ - if (node.getExpression() != null) { - node.getExpression().accept(this); - } - this.fBuffer.append("; ");//$NON-NLS-1$ - for (Iterator<Expression> it= node.updaters().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - } - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(IfStatement) - */ - @Override - public boolean visit(IfStatement node) { - this.fBuffer.append("if (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getThenStatement().accept(this); - if (node.getElseStatement() != null) { - this.fBuffer.append(" else ");//$NON-NLS-1$ - node.getElseStatement().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(ImportDeclaration) - */ - @Override - public boolean visit(ImportDeclaration node) { - this.fBuffer.append("import ");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= JLS3) { - if (node.isStatic()) { - this.fBuffer.append("static ");//$NON-NLS-1$ - } - } - node.getName().accept(this); - if (node.isOnDemand()) { - this.fBuffer.append(".*");//$NON-NLS-1$ - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(InfixExpression) - */ - @Override - public boolean visit(InfixExpression node) { - node.getLeftOperand().accept(this); - this.fBuffer.append(' '); // for cases like x= i - -1; or x= i++ + ++i; - this.fBuffer.append(node.getOperator().toString()); - this.fBuffer.append(' '); - node.getRightOperand().accept(this); - final List<Expression>extendedOperands = node.extendedOperands(); - if (extendedOperands.size() != 0) { - this.fBuffer.append(' '); - for (Iterator<Expression> it = extendedOperands.iterator(); it.hasNext(); ) { - this.fBuffer.append(node.getOperator().toString()).append(' '); - Expression e = it.next(); - e.accept(this); - } - } - return false; - } - - /* - * @see ASTVisitor#visit(Initializer) - */ - @Override - public boolean visit(Initializer node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(InstanceofExpression) - */ - @Override - public boolean visit(InstanceofExpression node) { - node.getLeftOperand().accept(this); - this.fBuffer.append(" instanceof ");//$NON-NLS-1$ - node.getRightOperand().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(IntersectionType) - */ - @Override - public boolean visit(IntersectionType node) { - for (Iterator<Type> it = node.types().iterator(); it.hasNext(); ) { - Type t = it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(" & "); //$NON-NLS-1$ - } - } - return false; - } - - /* - * @see ASTVisitor#visit(Javadoc) - */ - @Override - public boolean visit(Javadoc node) { - this.fBuffer.append("/** ");//$NON-NLS-1$ - for (Iterator<TagElement> it= node.tags().iterator(); it.hasNext();) { - ASTNode e= it.next(); - e.accept(this); - } - this.fBuffer.append("\n */");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(LabeledStatement) - */ - @Override - public boolean visit(LabeledStatement node) { - node.getLabel().accept(this); - this.fBuffer.append(": ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(LambdaExpression) - */ - @Override - public boolean visit(LambdaExpression node) { - boolean hasParentheses= node.hasParentheses(); - if (hasParentheses) - this.fBuffer.append('('); - for (Iterator<? extends VariableDeclaration> it= node.parameters().iterator(); it.hasNext(); ) { - VariableDeclaration v= it.next(); - v.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - if (hasParentheses) - this.fBuffer.append(')'); - this.fBuffer.append(" -> "); //$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(LineComment) - * @since 3.0 - */ - @Override - public boolean visit(LineComment node) { - this.fBuffer.append("//\n");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(MarkerAnnotation) - * @since 3.0 - */ - @Override - public boolean visit(MarkerAnnotation node) { - this.fBuffer.append("@");//$NON-NLS-1$ - node.getTypeName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(MemberRef) - * @since 3.0 - */ - @Override - public boolean visit(MemberRef node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - } - this.fBuffer.append("#");//$NON-NLS-1$ - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(MemberValuePair) - * @since 3.0 - */ - @Override - public boolean visit(MemberValuePair node) { - node.getName().accept(this); - this.fBuffer.append("=");//$NON-NLS-1$ - node.getValue().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(MethodRef) - * @since 3.0 - */ - @Override - public boolean visit(MethodRef node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - } - this.fBuffer.append("#");//$NON-NLS-1$ - node.getName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<MethodRefParameter> it= node.parameters().iterator(); it.hasNext();) { - MethodRefParameter e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(MethodRefParameter) - * @since 3.0 - */ - @Override - public boolean visit(MethodRefParameter node) { - node.getType().accept(this); - if (node.getAST().apiLevel() >= JLS3) { - if (node.isVarargs()) { - this.fBuffer.append("...");//$NON-NLS-1$ - } - } - if (node.getName() != null) { - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getName().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(MethodDeclaration) - */ - @Override - public boolean visit(MethodDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - if (!node.typeParameters().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<TypeParameter> it= node.typeParameters().iterator(); it.hasNext();) { - TypeParameter t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append("> ");//$NON-NLS-1$ - } - } - if (!node.isConstructor()) { - if (node.getReturnType2() != null) { - node.getReturnType2().accept(this); - } else { - // methods really ought to have a return type - this.fBuffer.append("void");//$NON-NLS-1$ - } - this.fBuffer.append(" ");//$NON-NLS-1$ - } - node.getName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= AST.JLS8) { - Type receiverType= node.getReceiverType(); - if (receiverType != null) { - receiverType.accept(this); - this.fBuffer.append(' '); - SimpleName qualifier= node.getReceiverQualifier(); - if (qualifier != null) { - qualifier.accept(this); - this.fBuffer.append('.'); - } - this.fBuffer.append("this"); //$NON-NLS-1$ - if (node.parameters().size() > 0) { - this.fBuffer.append(','); - } - } - } - for (Iterator<SingleVariableDeclaration> it= node.parameters().iterator(); it.hasNext();) { - SingleVariableDeclaration v= it.next(); - v.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= AST.JLS8) { - List<Dimension> dimensions = node.extraDimensions(); - for (Iterator<Dimension> it= dimensions.iterator(); it.hasNext(); ) { - Dimension e= it.next(); - e.accept(this); - } - } else { - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]"); //$NON-NLS-1$ - } - } - List<? extends ASTNode> thrownExceptions= node.getAST().apiLevel() >= AST.JLS8 ? node.thrownExceptionTypes() : getThrownExceptions(node); - if (!thrownExceptions.isEmpty()) { - this.fBuffer.append(" throws ");//$NON-NLS-1$ - for (Iterator<? extends ASTNode> it= thrownExceptions.iterator(); it.hasNext();) { - ASTNode n = it.next(); - n.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(" ");//$NON-NLS-1$ - } - if (node.getBody() == null) { - this.fBuffer.append(";");//$NON-NLS-1$ - } else { - node.getBody().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(MethodInvocation) - */ - @Override - public boolean visit(MethodInvocation node) { - if (node.getExpression() != null) { - node.getExpression().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeArguments().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - } - node.getName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(Modifier) - * @since 3.0 - */ - @Override - public boolean visit(Modifier node) { - this.fBuffer.append(node.getKeyword().toString()); - return false; - } - - /* - * @see ASTVisitor#visit(NameQualifiedType) - */ - @Override - public boolean visit(NameQualifiedType node) { - node.getQualifier().accept(this); - this.fBuffer.append('.'); - printTypeAnnotations(node); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(NormalAnnotation) - * @since 3.0 - */ - @Override - public boolean visit(NormalAnnotation node) { - this.fBuffer.append("@");//$NON-NLS-1$ - node.getTypeName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<MemberValuePair> it= node.values().iterator(); it.hasNext();) { - MemberValuePair p= it.next(); - p.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(NullLiteral) - */ - @Override - public boolean visit(NullLiteral node) { - this.fBuffer.append("null");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(NumberLiteral) - */ - @Override - public boolean visit(NumberLiteral node) { - this.fBuffer.append(node.getToken()); - return false; - } - - /* - * @see ASTVisitor#visit(PackageDeclaration) - */ - @Override - public boolean visit(PackageDeclaration node) { - if (node.getAST().apiLevel() >= JLS3) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - for (Iterator<Annotation> it= node.annotations().iterator(); it.hasNext();) { - Annotation p= it.next(); - p.accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - } - } - this.fBuffer.append("package ");//$NON-NLS-1$ - node.getName().accept(this); - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ParameterizedType) - * @since 3.0 - */ - @Override - public boolean visit(ParameterizedType node) { - node.getType().accept(this); - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ParenthesizedExpression) - */ - @Override - public boolean visit(ParenthesizedExpression node) { - this.fBuffer.append("(");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(PostfixExpression) - */ - @Override - public boolean visit(PostfixExpression node) { - node.getOperand().accept(this); - this.fBuffer.append(node.getOperator().toString()); - return false; - } - - /* - * @see ASTVisitor#visit(PrefixExpression) - */ - @Override - public boolean visit(PrefixExpression node) { - this.fBuffer.append(node.getOperator().toString()); - node.getOperand().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(PrimitiveType) - */ - @Override - public boolean visit(PrimitiveType node) { - printTypeAnnotations(node); - this.fBuffer.append(node.getPrimitiveTypeCode().toString()); - return false; - } - - /* - * @see ASTVisitor#visit(QualifiedName) - */ - @Override - public boolean visit(QualifiedName node) { - node.getQualifier().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(QualifiedType) - * @since 3.0 - */ - @Override - public boolean visit(QualifiedType node) { - node.getQualifier().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - printTypeAnnotations(node); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(ReturnStatement) - */ - @Override - public boolean visit(ReturnStatement node) { - this.fBuffer.append("return");//$NON-NLS-1$ - if (node.getExpression() != null) { - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getExpression().accept(this); - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(SimpleName) - */ - @Override - public boolean visit(SimpleName node) { - this.fBuffer.append(node.getIdentifier()); - return false; - } - - /* - * @see ASTVisitor#visit(SimpleType) - */ - @Override - public boolean visit(SimpleType node) { - printTypeAnnotations(node); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(SingleMemberAnnotation) - * @since 3.0 - */ - @Override - public boolean visit(SingleMemberAnnotation node) { - this.fBuffer.append("@");//$NON-NLS-1$ - node.getTypeName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - node.getValue().accept(this); - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(SingleVariableDeclaration) - */ - @Override - public boolean visit(SingleVariableDeclaration node) { - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - node.getType().accept(this); - if (node.getAST().apiLevel() >= JLS3) { - if (node.isVarargs()) { - if (node.getAST().apiLevel() >= AST.JLS8) { - this.fBuffer.append(' '); - List<Annotation> annotations= node.varargsAnnotations(); - printAnnotationsList(annotations); - } - this.fBuffer.append("...");//$NON-NLS-1$ - } - } - this.fBuffer.append(" ");//$NON-NLS-1$ - node.getName().accept(this); - if (node.getAST().apiLevel() >= AST.JLS8) { - List<Dimension> dimensions = node.extraDimensions(); - for (Iterator<Dimension> it= dimensions.iterator(); it.hasNext(); ) { - Dimension e= it.next(); - e.accept(this); - } - } else { - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]"); //$NON-NLS-1$ - } - } - if (node.getInitializer() != null) { - this.fBuffer.append("=");//$NON-NLS-1$ - node.getInitializer().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(StringLiteral) - */ - @Override - public boolean visit(StringLiteral node) { - this.fBuffer.append(node.getEscapedValue()); - return false; - } - - /* - * @see ASTVisitor#visit(SuperConstructorInvocation) - */ - @Override - public boolean visit(SuperConstructorInvocation node) { - if (node.getExpression() != null) { - node.getExpression().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeArguments().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - } - this.fBuffer.append("super(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(");");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(SuperFieldAccess) - */ - @Override - public boolean visit(SuperFieldAccess node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - this.fBuffer.append("super.");//$NON-NLS-1$ - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(SuperMethodInvocation) - */ - @Override - public boolean visit(SuperMethodInvocation node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - this.fBuffer.append("super.");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeArguments().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeArguments().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - } - node.getName().accept(this); - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<Expression> it= node.arguments().iterator(); it.hasNext();) { - Expression e= it.next(); - e.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(")");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(SuperMethodReference) - */ - @Override - public boolean visit(SuperMethodReference node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - this.fBuffer.append('.'); - } - this.fBuffer.append("super");//$NON-NLS-1$ - printReferenceTypeArguments(node.typeArguments()); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(SwitchCase) - */ - @Override - public boolean visit(SwitchCase node) { - if (node.isDefault()) { - this.fBuffer.append("default :");//$NON-NLS-1$ - } else { - this.fBuffer.append("case ");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(":");//$NON-NLS-1$ - } - return false; - } - - /* - * @see ASTVisitor#visit(SwitchStatement) - */ - @Override - public boolean visit(SwitchStatement node) { - this.fBuffer.append("switch (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - this.fBuffer.append("{");//$NON-NLS-1$ - for (Iterator<Statement> it= node.statements().iterator(); it.hasNext();) { - Statement s= it.next(); - s.accept(this); - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(SynchronizedStatement) - */ - @Override - public boolean visit(SynchronizedStatement node) { - this.fBuffer.append("synchronized (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(TagElement) - * @since 3.0 - */ - @Override - public boolean visit(TagElement node) { - if (node.isNested()) { - // nested tags are always enclosed in braces - this.fBuffer.append("{");//$NON-NLS-1$ - } else { - // top-level tags always begin on a new line - this.fBuffer.append("\n * ");//$NON-NLS-1$ - } - boolean previousRequiresWhiteSpace= false; - if (node.getTagName() != null) { - this.fBuffer.append(node.getTagName()); - previousRequiresWhiteSpace= true; - } - boolean previousRequiresNewLine= false; - for (Iterator<? extends ASTNode> it= node.fragments().iterator(); it.hasNext();) { - ASTNode e= it.next(); - // assume text elements include necessary leading and trailing whitespace - // but Name, MemberRef, MethodRef, and nested TagElement do not include white space - boolean currentIncludesWhiteSpace= (e instanceof TextElement); - if (previousRequiresNewLine && currentIncludesWhiteSpace) { - this.fBuffer.append("\n * ");//$NON-NLS-1$ - } - previousRequiresNewLine= currentIncludesWhiteSpace; - // add space if required to separate - if (previousRequiresWhiteSpace && !currentIncludesWhiteSpace) { - this.fBuffer.append(" "); //$NON-NLS-1$ - } - e.accept(this); - previousRequiresWhiteSpace= !currentIncludesWhiteSpace && !(e instanceof TagElement); - } - if (node.isNested()) { - this.fBuffer.append("}");//$NON-NLS-1$ - } - return false; - } - - /* - * @see ASTVisitor#visit(TextElement) - * @since 3.0 - */ - @Override - public boolean visit(TextElement node) { - this.fBuffer.append(node.getText()); - return false; - } - - /* - * @see ASTVisitor#visit(ThisExpression) - */ - @Override - public boolean visit(ThisExpression node) { - if (node.getQualifier() != null) { - node.getQualifier().accept(this); - this.fBuffer.append(".");//$NON-NLS-1$ - } - this.fBuffer.append("this");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(ThrowStatement) - */ - @Override - public boolean visit(ThrowStatement node) { - this.fBuffer.append("throw ");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(TryStatement) - */ - @Override - public boolean visit(TryStatement node) { - this.fBuffer.append("try ");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= JLS4) { - if (!node.resources().isEmpty()) { - this.fBuffer.append("(");//$NON-NLS-1$ - for (Iterator<VariableDeclarationExpression> it= node.resources().iterator(); it.hasNext();) { - VariableDeclarationExpression var= it.next(); - var.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(") ");//$NON-NLS-1$ - } - } - node.getBody().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - for (Iterator<CatchClause> it= node.catchClauses().iterator(); it.hasNext();) { - CatchClause cc= it.next(); - cc.accept(this); - } - if (node.getFinally() != null) { - this.fBuffer.append("finally ");//$NON-NLS-1$ - node.getFinally().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(TypeDeclaration) - */ - @Override - public boolean visit(TypeDeclaration node) { - if (node.getJavadoc() != null) { - node.getJavadoc().accept(this); - } - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - this.fBuffer.append(node.isInterface() ? "interface " : "class ");//$NON-NLS-2$//$NON-NLS-1$ - node.getName().accept(this); - if (node.getAST().apiLevel() >= JLS3) { - if (!node.typeParameters().isEmpty()) { - this.fBuffer.append("<");//$NON-NLS-1$ - for (Iterator<TypeParameter> it= node.typeParameters().iterator(); it.hasNext();) { - TypeParameter t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(",");//$NON-NLS-1$ - } - } - this.fBuffer.append(">");//$NON-NLS-1$ - } - } - this.fBuffer.append(" ");//$NON-NLS-1$ - if (node.getAST().apiLevel() >= JLS3) { - if (node.getSuperclassType() != null) { - this.fBuffer.append("extends ");//$NON-NLS-1$ - node.getSuperclassType().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - } - if (!node.superInterfaceTypes().isEmpty()) { - this.fBuffer.append(node.isInterface() ? "extends " : "implements ");//$NON-NLS-2$//$NON-NLS-1$ - for (Iterator<Type> it= node.superInterfaceTypes().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(" ");//$NON-NLS-1$ - } - } - this.fBuffer.append("{");//$NON-NLS-1$ - BodyDeclaration prev= null; - for (Iterator<BodyDeclaration> it= node.bodyDeclarations().iterator(); it.hasNext();) { - BodyDeclaration d= it.next(); - if (prev instanceof EnumConstantDeclaration) { - // enum constant declarations do not include punctuation - if (d instanceof EnumConstantDeclaration) { - // enum constant declarations are separated by commas - this.fBuffer.append(", ");//$NON-NLS-1$ - } else { - // semicolon separates last enum constant declaration from - // first class body declarations - this.fBuffer.append("; ");//$NON-NLS-1$ - } - } - d.accept(this); - prev= d; - } - this.fBuffer.append("}");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(TypeDeclarationStatement) - */ - @Override - public boolean visit(TypeDeclarationStatement node) { - if (node.getAST().apiLevel() >= JLS3) { - node.getDeclaration().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(TypeLiteral) - */ - @Override - public boolean visit(TypeLiteral node) { - node.getType().accept(this); - this.fBuffer.append(".class");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(TypeMethodReference) - */ - @Override - public boolean visit(TypeMethodReference node) { - node.getType().accept(this); - printReferenceTypeArguments(node.typeArguments()); - node.getName().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(TypeParameter) - * @since 3.0 - */ - @Override - public boolean visit(TypeParameter node) { - printModifiers(node.modifiers()); - node.getName().accept(this); - if (!node.typeBounds().isEmpty()) { - this.fBuffer.append(" extends ");//$NON-NLS-1$ - for (Iterator<Type> it= node.typeBounds().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append(" & ");//$NON-NLS-1$ - } - } - } - return false; - } - - /* - * @see ASTVisitor#visit(UnionType) - */ - @Override - public boolean visit(UnionType node) { - for (Iterator<Type> it= node.types().iterator(); it.hasNext();) { - Type t= it.next(); - t.accept(this); - if (it.hasNext()) { - this.fBuffer.append("|");//$NON-NLS-1$ - } - } - return false; - } - - /* - * @see ASTVisitor#visit(VariableDeclarationExpression) - */ - @Override - public boolean visit(VariableDeclarationExpression node) { - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - node.getType().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - for (Iterator<VariableDeclarationFragment> it= node.fragments().iterator(); it.hasNext();) { - VariableDeclarationFragment f= it.next(); - f.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - return false; - } - - /* - * @see ASTVisitor#visit(VariableDeclarationFragment) - */ - @Override - public boolean visit(VariableDeclarationFragment node) { - node.getName().accept(this); - if (node.getAST().apiLevel() >= AST.JLS8) { - List<Dimension> dimensions = node.extraDimensions(); - for (Iterator<Dimension> it= dimensions.iterator(); it.hasNext(); ) { - Dimension e= it.next(); - e.accept(this); - } - } else { - for (int i= 0; i < node.getExtraDimensions(); i++) { - this.fBuffer.append("[]"); //$NON-NLS-1$ - } - } - if (node.getInitializer() != null) { - this.fBuffer.append("=");//$NON-NLS-1$ - node.getInitializer().accept(this); - } - return false; - } - - /* - * @see ASTVisitor#visit(VariableDeclarationStatement) - */ - @Override - public boolean visit(VariableDeclarationStatement node) { - if (node.getAST().apiLevel() >= JLS3) { - printModifiers(node.modifiers()); - } - node.getType().accept(this); - this.fBuffer.append(" ");//$NON-NLS-1$ - for (Iterator<VariableDeclarationFragment> it= node.fragments().iterator(); it.hasNext();) { - VariableDeclarationFragment f= it.next(); - f.accept(this); - if (it.hasNext()) { - this.fBuffer.append(", ");//$NON-NLS-1$ - } - } - this.fBuffer.append(";");//$NON-NLS-1$ - return false; - } - - /* - * @see ASTVisitor#visit(WhileStatement) - */ - @Override - public boolean visit(WhileStatement node) { - this.fBuffer.append("while (");//$NON-NLS-1$ - node.getExpression().accept(this); - this.fBuffer.append(") ");//$NON-NLS-1$ - node.getBody().accept(this); - return false; - } - - /* - * @see ASTVisitor#visit(WildcardType) - * @since 3.0 - */ - @Override - public boolean visit(WildcardType node) { - printTypeAnnotations(node); - this.fBuffer.append("?");//$NON-NLS-1$ - Type bound= node.getBound(); - if (bound != null) { - if (node.isUpperBound()) { - this.fBuffer.append(" extends ");//$NON-NLS-1$ - } else { - this.fBuffer.append(" super ");//$NON-NLS-1$ - } - bound.accept(this); - } - return false; - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java deleted file mode 100644 index a23eeb8eb5..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java +++ /dev/null @@ -1,1604 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for - * bug "inline method - doesn't handle implicit cast" (see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941). - * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for - * bug Encapsulate field can fail when two variables in one variable declaration (see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=51540). - * Stephan Herrmann - Configuration for - * Bug 463360 - [override method][null] generating method override should not create redundant null annotations - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; - -import org.eclipse.text.edits.TextEdit; -import org.eclipse.text.edits.TextEditGroup; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; - -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IBuffer; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMember; -import org.eclipse.jdt.core.ISourceReference; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeRoot; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.compiler.IProblem; -import org.eclipse.jdt.core.compiler.ITerminalSymbols; -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.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CharacterLiteral; -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.ConditionalExpression; -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.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IBinding; -import org.eclipse.jdt.core.dom.IExtendedModifier; -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.InfixExpression; -import org.eclipse.jdt.core.dom.LambdaExpression; -import org.eclipse.jdt.core.dom.MemberValuePair; -import org.eclipse.jdt.core.dom.Message; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodReference; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.NameQualifiedType; -import org.eclipse.jdt.core.dom.NodeFinder; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.ReturnStatement; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.UnionType; -import org.eclipse.jdt.core.dom.VariableDeclaration; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -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.internal.corext.codemanipulation.StubUtility; -import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; -import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; -import org.eclipse.jdt.internal.corext.util.Strings; - -import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; -import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; - -/** - * JDT-UI-internal helper methods that deal with {@link ASTNode}s: - * <ul> - * <li>additional operations on {@link ASTNode}s and subtypes</li> - * <li>finding related nodes in an AST</li> - * <li>some methods that deal with bindings (new such methods should go into {@link Bindings})</li> - * </ul> - * - * @see JDTUIHelperClasses - */ -public class ASTNodes { - - public static final int NODE_ONLY= 0; - public static final int INCLUDE_FIRST_PARENT= 1; - public static final int INCLUDE_ALL_PARENTS= 2; - - public static final int WARNING= 1 << 0; - public static final int ERROR= 1 << 1; - public static final int INFO= 1 << 2; - public static final int PROBLEMS= WARNING | ERROR | INFO; - - private static final Message[] EMPTY_MESSAGES= new Message[0]; - private static final IProblem[] EMPTY_PROBLEMS= new IProblem[0]; - - private static final int CLEAR_VISIBILITY= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE); - - - private ASTNodes() { - // no instance; - } - - public static String asString(ASTNode node) { - ASTFlattener flattener= new ASTFlattener(); - node.accept(flattener); - return flattener.getResult(); - } - - public static String asFormattedString(ASTNode node, int indent, String lineDelim, Map<String, String> options) { - String unformatted= asString(node); - TextEdit edit= CodeFormatterUtil.format2(node, unformatted, indent, lineDelim, options); - if (edit != null) { - Document document= new Document(unformatted); - try { - edit.apply(document, TextEdit.NONE); - } catch (BadLocationException e) { - JavaPlugin.log(e); - } - return document.get(); - } - return unformatted; // unknown node - } - - - /** - * Returns the source of the given node from the location where it was parsed. - * @param node the node to get the source from - * @param extendedRange if set, the extended ranges of the nodes should ne used - * @param removeIndent if set, the indentation is removed. - * @return return the source for the given node or null if accessing the source failed. - */ - public static String getNodeSource(ASTNode node, boolean extendedRange, boolean removeIndent) { - ASTNode root= node.getRoot(); - if (root instanceof CompilationUnit) { - CompilationUnit astRoot= (CompilationUnit) root; - ITypeRoot typeRoot= astRoot.getTypeRoot(); - try { - if (typeRoot != null && typeRoot.getBuffer() != null) { - IBuffer buffer= typeRoot.getBuffer(); - int offset= extendedRange ? astRoot.getExtendedStartPosition(node) : node.getStartPosition(); - int length= extendedRange ? astRoot.getExtendedLength(node) : node.getLength(); - String str= buffer.getText(offset, length); - if (removeIndent) { - IJavaProject project= typeRoot.getJavaProject(); - int indent= StubUtility.getIndentUsed(buffer, node.getStartPosition(), project); - str= Strings.changeIndent(str, indent, project, new String(), typeRoot.findRecommendedLineSeparator()); - } - return str; - } - } catch (JavaModelException e) { - // ignore - } - } - return null; - } - - /** - * Returns the list that contains the given ASTNode. If the node - * isn't part of any list, <code>null</code> is returned. - * - * @param node the node in question - * @return the list that contains the node or <code>null</code> - */ - public static List<? extends ASTNode> getContainingList(ASTNode node) { - StructuralPropertyDescriptor locationInParent= node.getLocationInParent(); - if (locationInParent != null && locationInParent.isChildListProperty()) { - return getChildListProperty(node.getParent(), (ChildListPropertyDescriptor) locationInParent); - } - return null; - } - - /** - * Variant of {@link ASTNode#getStructuralProperty(StructuralPropertyDescriptor)} that avoids - * unchecked casts in the caller. - * <p> - * To improve type-safety, callers can add the expected element type as explicit type argument, e.g.: - * <p> - * {@code ASTNodes.<BodyDeclaration>getChildListProperty(typeDecl, bodyDeclarationsProperty)} - * - * @param node the node - * @param propertyDescriptor the child list property to get - * @return the child list - * @exception RuntimeException if this node does not have the given property - */ - @SuppressWarnings("unchecked") - public static <T extends ASTNode> List<T> getChildListProperty(ASTNode node, ChildListPropertyDescriptor propertyDescriptor) { - return (List<T>) node.getStructuralProperty(propertyDescriptor); - } - - /** - * Returns a list of the direct children of a node. The siblings are ordered by start offset. - * @param node the node to get the children for - * @return the children - */ - public static List<ASTNode> getChildren(ASTNode node) { - ChildrenCollector visitor= new ChildrenCollector(); - node.accept(visitor); - return visitor.result; - } - - private static class ChildrenCollector extends GenericVisitor { - public List<ASTNode> result; - - public ChildrenCollector() { - super(true); - result= null; - } - @Override - protected boolean visitNode(ASTNode node) { - if (result == null) { // first visitNode: on the node's parent: do nothing, return true - result= new ArrayList<>(); - return true; - } - result.add(node); - return false; - } - } - - /** - * Returns true if this is an existing node, i.e. it was created as part of - * a parsing process of a source code file. Returns false if this is a newly - * created node which has not yet been given a source position. - * - * @param node the node to be tested. - * @return true if this is an existing node, false if not. - */ - public static boolean isExistingNode(ASTNode node) { - return node.getStartPosition() != -1; - } - - /** - * Returns the element type. This is a convenience method that returns its - * argument if it is a simple type and the element type if the parameter is an array type. - * @param type The type to get the element type from. - * @return The element type of the type or the type itself. - */ - public static Type getElementType(Type type) { - if (! type.isArrayType()) - return type; - return ((ArrayType)type).getElementType(); - } - - public static ASTNode findDeclaration(IBinding binding, ASTNode root) { - root= root.getRoot(); - if (root instanceof CompilationUnit) { - return ((CompilationUnit)root).findDeclaringNode(binding); - } - return null; - } - - public static VariableDeclaration findVariableDeclaration(IVariableBinding binding, ASTNode root) { - if (binding.isField()) - return null; - ASTNode result= findDeclaration(binding, root); - if (result instanceof VariableDeclaration) - return (VariableDeclaration)result; - - return null; - } - - /** - * Returns the type node for the given declaration. - * - * @param declaration the declaration - * @return the type node or <code>null</code> if the given declaration represents a type - * inferred parameter in lambda expression - */ - public static Type getType(VariableDeclaration declaration) { - if (declaration instanceof SingleVariableDeclaration) { - return ((SingleVariableDeclaration)declaration).getType(); - } else if (declaration instanceof VariableDeclarationFragment) { - ASTNode parent= ((VariableDeclarationFragment)declaration).getParent(); - if (parent instanceof VariableDeclarationExpression) - return ((VariableDeclarationExpression)parent).getType(); - else if (parent instanceof VariableDeclarationStatement) - return ((VariableDeclarationStatement)parent).getType(); - else if (parent instanceof FieldDeclaration) - return ((FieldDeclaration)parent).getType(); - else if (parent instanceof LambdaExpression) - return null; - } - Assert.isTrue(false, "Unknown VariableDeclaration"); //$NON-NLS-1$ - return null; - } - - public static int getDimensions(VariableDeclaration declaration) { - int dim= declaration.getExtraDimensions(); - if (declaration instanceof VariableDeclarationFragment && declaration.getParent() instanceof LambdaExpression) { - LambdaExpression lambda= (LambdaExpression) declaration.getParent(); - IMethodBinding methodBinding= lambda.resolveMethodBinding(); - if (methodBinding != null) { - ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); - int index= lambda.parameters().indexOf(declaration); - ITypeBinding typeBinding= parameterTypes[index]; - return typeBinding.getDimensions(); - } - } else { - Type type= getType(declaration); - if (type instanceof ArrayType) { - dim+= ((ArrayType) type).getDimensions(); - } - } - return dim; - } - - public static List<IExtendedModifier> getModifiers(VariableDeclaration declaration) { - Assert.isNotNull(declaration); - if (declaration instanceof SingleVariableDeclaration) { - return ((SingleVariableDeclaration)declaration).modifiers(); - } else if (declaration instanceof VariableDeclarationFragment) { - ASTNode parent= declaration.getParent(); - if (parent instanceof VariableDeclarationExpression) - return ((VariableDeclarationExpression)parent).modifiers(); - else if (parent instanceof VariableDeclarationStatement) - return ((VariableDeclarationStatement)parent).modifiers(); - } - return new ArrayList<>(0); - } - - public static boolean isSingleDeclaration(VariableDeclaration declaration) { - Assert.isNotNull(declaration); - if (declaration instanceof SingleVariableDeclaration) { - return true; - } else if (declaration instanceof VariableDeclarationFragment) { - ASTNode parent= declaration.getParent(); - if (parent instanceof VariableDeclarationExpression) - return ((VariableDeclarationExpression)parent).fragments().size() == 1; - else if (parent instanceof VariableDeclarationStatement) - return ((VariableDeclarationStatement)parent).fragments().size() == 1; - } - return false; - } - - public static boolean isLiteral(Expression expression) { - int type= expression.getNodeType(); - return type == ASTNode.BOOLEAN_LITERAL || type == ASTNode.CHARACTER_LITERAL || type == ASTNode.NULL_LITERAL || - type == ASTNode.NUMBER_LITERAL || type == ASTNode.STRING_LITERAL || type == ASTNode.TYPE_LITERAL; - } - - public static boolean isLabel(SimpleName name) { - int parentType= name.getParent().getNodeType(); - return parentType == ASTNode.LABELED_STATEMENT || - parentType == ASTNode.BREAK_STATEMENT || parentType != ASTNode.CONTINUE_STATEMENT; - } - - public static boolean isStatic(BodyDeclaration declaration) { - return Modifier.isStatic(declaration.getModifiers()); - } - - public static List<BodyDeclaration> getBodyDeclarations(ASTNode node) { - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration)node).bodyDeclarations(); - } else if (node instanceof AnonymousClassDeclaration) { - return ((AnonymousClassDeclaration)node).bodyDeclarations(); - } - // should not happen. - Assert.isTrue(false); - return null; - } - - /** - * Returns the structural property descriptor for the "bodyDeclarations" property - * of this node (element type: {@link BodyDeclaration}). - * - * @param node the node, either an {@link AbstractTypeDeclaration} or an {@link AnonymousClassDeclaration} - * @return the property descriptor - */ - public static ChildListPropertyDescriptor getBodyDeclarationsProperty(ASTNode node) { - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration)node).getBodyDeclarationsProperty(); - } else if (node instanceof AnonymousClassDeclaration) { - return AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY; - } - // should not happen. - Assert.isTrue(false); - return null; - } - - /** - * Returns the simple name of the type, followed by array dimensions. - * Skips qualifiers, type arguments, and type annotations. - * <p> - * Does <b>not</b> work for WildcardTypes, etc.! - * - * @param type a type that has a simple name - * @return the simple name, followed by array dimensions - * @see #getSimpleNameIdentifier(Name) - * @since 3.10 - */ - public static String getTypeName(Type type) { - final StringBuffer buffer= new StringBuffer(); - ASTVisitor visitor= new ASTVisitor() { - @Override - public boolean visit(PrimitiveType node) { - buffer.append(node.getPrimitiveTypeCode().toString()); - return false; - } - @Override - public boolean visit(SimpleType node) { - buffer.append(getSimpleNameIdentifier(node.getName())); - return false; - } - @Override - public boolean visit(QualifiedType node) { - buffer.append(node.getName().getIdentifier()); - return false; - } - @Override - public boolean visit(NameQualifiedType node) { - buffer.append(node.getName().getIdentifier()); - return false; - } - @Override - public boolean visit(ParameterizedType node) { - node.getType().accept(this); - return false; - } - @Override - public void endVisit(ArrayType node) { - for (int i= 0; i < node.dimensions().size(); i++) { - buffer.append("[]"); //$NON-NLS-1$ - } - } - }; - type.accept(visitor); - return buffer.toString(); - } - - /** - * Returns the (potentially qualified) name of a type, followed by array dimensions. - * Skips type arguments and type annotations. - * - * @param type a type that has a name - * @return the name, followed by array dimensions - * @since 3.10 - */ - public static String getQualifiedTypeName(Type type) { - final StringBuffer buffer= new StringBuffer(); - ASTVisitor visitor= new ASTVisitor() { - @Override - public boolean visit(SimpleType node) { - buffer.append(node.getName().getFullyQualifiedName()); - return false; - } - @Override - public boolean visit(QualifiedType node) { - node.getQualifier().accept(this); - buffer.append('.'); - buffer.append(node.getName().getIdentifier()); - return false; - } - @Override - public boolean visit(NameQualifiedType node) { - buffer.append(node.getQualifier().getFullyQualifiedName()); - buffer.append('.'); - buffer.append(node.getName().getIdentifier()); - return false; - } - @Override - public boolean visit(ParameterizedType node) { - node.getType().accept(this); - return false; - } - @Override - public void endVisit(ArrayType node) { - for (int i= 0; i < node.dimensions().size(); i++) { - buffer.append("[]"); //$NON-NLS-1$ - } - } - }; - type.accept(visitor); - return buffer.toString(); - } - - public static InfixExpression.Operator convertToInfixOperator(Assignment.Operator operator) { - if (operator.equals(Assignment.Operator.PLUS_ASSIGN)) - return InfixExpression.Operator.PLUS; - - if (operator.equals(Assignment.Operator.MINUS_ASSIGN)) - return InfixExpression.Operator.MINUS; - - if (operator.equals(Assignment.Operator.TIMES_ASSIGN)) - return InfixExpression.Operator.TIMES; - - if (operator.equals(Assignment.Operator.DIVIDE_ASSIGN)) - return InfixExpression.Operator.DIVIDE; - - if (operator.equals(Assignment.Operator.BIT_AND_ASSIGN)) - return InfixExpression.Operator.AND; - - if (operator.equals(Assignment.Operator.BIT_OR_ASSIGN)) - return InfixExpression.Operator.OR; - - if (operator.equals(Assignment.Operator.BIT_XOR_ASSIGN)) - return InfixExpression.Operator.XOR; - - if (operator.equals(Assignment.Operator.REMAINDER_ASSIGN)) - return InfixExpression.Operator.REMAINDER; - - if (operator.equals(Assignment.Operator.LEFT_SHIFT_ASSIGN)) - return InfixExpression.Operator.LEFT_SHIFT; - - if (operator.equals(Assignment.Operator.RIGHT_SHIFT_SIGNED_ASSIGN)) - return InfixExpression.Operator.RIGHT_SHIFT_SIGNED; - - if (operator.equals(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN)) - return InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED; - - Assert.isTrue(false, "Cannot convert assignment operator"); //$NON-NLS-1$ - return null; - } - - /** - * Returns true if a node at a given location is a body of a control statement. Such body nodes are - * interesting as when replacing them, it has to be evaluates if a Block is needed instead. - * E.g. <code> if (x) do(); -> if (x) { do1(); do2() } </code> - * - * @param locationInParent Location of the body node - * @return Returns true if the location is a body node location of a control statement. - */ - public static boolean isControlStatementBody(StructuralPropertyDescriptor locationInParent) { - return locationInParent == IfStatement.THEN_STATEMENT_PROPERTY - || locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY - || locationInParent == ForStatement.BODY_PROPERTY - || locationInParent == EnhancedForStatement.BODY_PROPERTY - || locationInParent == WhileStatement.BODY_PROPERTY - || locationInParent == DoStatement.BODY_PROPERTY; - } - - /** - * Returns the type to which an inlined variable initializer should be cast, or - * <code>null</code> if no cast is necessary. - * - * @param initializer the initializer expression of the variable to inline - * @param reference the reference to the variable (which is to be inlined) - * @return a type binding to which the initializer should be cast, or <code>null</code> iff no cast is necessary - * @since 3.6 - */ - public static ITypeBinding getExplicitCast(Expression initializer, Expression reference) { - ITypeBinding initializerType= initializer.resolveTypeBinding(); - ITypeBinding referenceType= reference.resolveTypeBinding(); - if (initializerType == null || referenceType == null) - return null; - - if (initializerType.isPrimitive() && referenceType.isPrimitive() && ! referenceType.isEqualTo(initializerType)) { - return referenceType; - - } else if (initializerType.isPrimitive() && ! referenceType.isPrimitive()) { // initializer is autoboxed - ITypeBinding unboxedReferenceType= Bindings.getUnboxedTypeBinding(referenceType, reference.getAST()); - if (!unboxedReferenceType.isEqualTo(initializerType)) - return unboxedReferenceType; - else if (needsExplicitBoxing(reference)) - return referenceType; - - } else if (! initializerType.isPrimitive() && referenceType.isPrimitive()) { // initializer is autounboxed - ITypeBinding unboxedInitializerType= Bindings.getUnboxedTypeBinding(initializerType, reference.getAST()); - if (!unboxedInitializerType.isEqualTo(referenceType)) - return referenceType; - - } else if (initializerType.isRawType() && referenceType.isParameterizedType()) { - return referenceType; // don't lose the unchecked conversion - - } else if (initializer instanceof LambdaExpression || initializer instanceof MethodReference) { - if (isTargetAmbiguous(reference, isExplicitlyTypedLambda(initializer))) { - return referenceType; - } else { - ITypeBinding targetType= getTargetType(reference); - if (targetType == null || targetType != referenceType) { - return referenceType; - } - } - - } else if (! TypeRules.canAssign(initializerType, referenceType)) { - if (!Bindings.containsTypeVariables(referenceType)) - return referenceType; - } - - return null; - } - - /** - * Checks whether overloaded methods can result in an ambiguous method call or a semantic change when the - * <code>expression</code> argument is replaced with a poly expression form of the functional - * interface instance. - * - * @param expression the method argument, which is a functional interface instance - * @param expressionIsExplicitlyTyped <code>true</code> iff the intended replacement for <code>expression</code> - * is an explicitly typed lambda expression (JLS8 15.27.1) - * @return <code>true</code> if overloaded methods can result in an ambiguous method call or a semantic change, - * <code>false</code> otherwise - * - * @since 3.10 - */ - public static boolean isTargetAmbiguous(Expression expression, boolean expressionIsExplicitlyTyped) { - StructuralPropertyDescriptor locationInParent= expression.getLocationInParent(); - - while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY - || locationInParent == ConditionalExpression.THEN_EXPRESSION_PROPERTY - || locationInParent == ConditionalExpression.ELSE_EXPRESSION_PROPERTY) { - expression= (Expression) expression.getParent(); - locationInParent= expression.getLocationInParent(); - } - - ASTNode parent= expression.getParent(); - IMethodBinding methodBinding; - int argumentIndex; - int argumentCount; - Expression invocationQualifier= null; - if (locationInParent == MethodInvocation.ARGUMENTS_PROPERTY) { - MethodInvocation methodInvocation= (MethodInvocation) parent; - methodBinding= methodInvocation.resolveMethodBinding(); - argumentIndex= methodInvocation.arguments().indexOf(expression); - argumentCount= methodInvocation.arguments().size(); - invocationQualifier= methodInvocation.getExpression(); - } else if (locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY) { - SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent; - methodBinding= superMethodInvocation.resolveMethodBinding(); - argumentIndex= superMethodInvocation.arguments().indexOf(expression); - argumentCount= superMethodInvocation.arguments().size(); - invocationQualifier= superMethodInvocation.getQualifier(); - } else if (locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY) { - ConstructorInvocation constructorInvocation= (ConstructorInvocation) parent; - methodBinding= constructorInvocation.resolveConstructorBinding(); - argumentIndex= constructorInvocation.arguments().indexOf(expression); - argumentCount= constructorInvocation.arguments().size(); - } else if (locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY) { - SuperConstructorInvocation superConstructorInvocation= (SuperConstructorInvocation) parent; - methodBinding= superConstructorInvocation.resolveConstructorBinding(); - argumentIndex= superConstructorInvocation.arguments().indexOf(expression); - argumentCount= superConstructorInvocation.arguments().size(); - } else if (locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY) { - ClassInstanceCreation creation= (ClassInstanceCreation) parent; - methodBinding= creation.resolveConstructorBinding(); - argumentIndex= creation.arguments().indexOf(expression); - argumentCount= creation.arguments().size(); - } else if (locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY) { - EnumConstantDeclaration enumConstantDecl= (EnumConstantDeclaration) parent; - methodBinding= enumConstantDecl.resolveConstructorBinding(); - argumentIndex= enumConstantDecl.arguments().indexOf(expression); - argumentCount= enumConstantDecl.arguments().size(); - } else { - return false; - } - - if (methodBinding != null) { - ITypeBinding invocationTargetType; - invocationTargetType= getInvocationType(parent, methodBinding, invocationQualifier); - if (invocationTargetType != null) { - TypeBindingVisitor visitor= new AmbiguousTargetMethodAnalyzer(invocationTargetType, methodBinding, argumentIndex, argumentCount, expressionIsExplicitlyTyped); - return !(visitor.visit(invocationTargetType) && Bindings.visitHierarchy(invocationTargetType, visitor)); - } - } - - return true; - } - - /** - * Returns the binding of the type which declares the method being invoked. - * - * @param invocationNode the method invocation node - * @param methodBinding binding of the method being invoked - * @param invocationQualifier the qualifier used for method invocation, or <code>null</code> if - * none - * @return the binding of the type which declares the method being invoked, or <code>null</code> - * if the type cannot be resolved - */ - public static ITypeBinding getInvocationType(ASTNode invocationNode, IMethodBinding methodBinding, Expression invocationQualifier) { - ITypeBinding invocationType; - if (invocationNode instanceof MethodInvocation || invocationNode instanceof SuperMethodInvocation) { - if (invocationQualifier != null) { - invocationType= invocationQualifier.resolveTypeBinding(); - if (invocationType != null && invocationNode instanceof SuperMethodInvocation) { - invocationType= invocationType.getSuperclass(); - } - } else { - ITypeBinding enclosingType= getEnclosingType(invocationNode); - if (enclosingType != null && invocationNode instanceof SuperMethodInvocation) { - enclosingType= enclosingType.getSuperclass(); - } - if (enclosingType != null) { - IMethodBinding methodInHierarchy= Bindings.findMethodInHierarchy(enclosingType, methodBinding.getName(), methodBinding.getParameterTypes()); - if (methodInHierarchy != null) { - invocationType= enclosingType; - } else { - invocationType= methodBinding.getDeclaringClass(); - } - } else { - // not expected - invocationType= methodBinding.getDeclaringClass(); - } - } - } else { - invocationType= methodBinding.getDeclaringClass(); - } - return invocationType; - } - - private static class AmbiguousTargetMethodAnalyzer implements TypeBindingVisitor { - private ITypeBinding fDeclaringType; - private IMethodBinding fOriginalMethod; - private int fArgIndex; - private int fArgumentCount; - private boolean fExpressionIsExplicitlyTyped; - - /** - * @param declaringType the type binding declaring the <code>originalMethod</code> - * @param originalMethod the method declaration binding corresponding to the method call - * @param argumentIndex the index of the functional interface instance argument in the - * method call - * @param argumentCount the number of arguments in the method call - * @param expressionIsExplicitlyTyped <code>true</code> iff the intended replacement for <code>expression</code> - * is an explicitly typed lambda expression (JLS8 15.27.1) - */ - public AmbiguousTargetMethodAnalyzer(ITypeBinding declaringType, IMethodBinding originalMethod, int argumentIndex, int argumentCount, boolean expressionIsExplicitlyTyped) { - fDeclaringType= declaringType; - fOriginalMethod= originalMethod; - fArgIndex= argumentIndex; - fArgumentCount= argumentCount; - fExpressionIsExplicitlyTyped= expressionIsExplicitlyTyped; - } - - @Override - public boolean visit(ITypeBinding type) { - IMethodBinding[] methods= type.getDeclaredMethods(); - for (int i= 0; i < methods.length; i++) { - IMethodBinding candidate= methods[i]; - if (candidate.getMethodDeclaration() == fOriginalMethod.getMethodDeclaration()) { - continue; - } - ITypeBinding candidateDeclaringType= candidate.getDeclaringClass(); - if (fDeclaringType != candidateDeclaringType) { - int modifiers= candidate.getModifiers(); - if (candidateDeclaringType.isInterface() && Modifier.isStatic(modifiers)) { - continue; - } - if (Modifier.isPrivate(modifiers)) { - continue; - } - } - if (fOriginalMethod.getName().equals(candidate.getName()) && !fOriginalMethod.overrides(candidate)) { - ITypeBinding[] originalParameterTypes= fOriginalMethod.getParameterTypes(); - ITypeBinding[] candidateParameterTypes= candidate.getParameterTypes(); - - boolean couldBeAmbiguous; - if (originalParameterTypes.length == candidateParameterTypes.length) { - couldBeAmbiguous= true; - } else if (fOriginalMethod.isVarargs() || candidate.isVarargs() ) { - int candidateMinArgumentCount= candidateParameterTypes.length; - if (candidate.isVarargs()) - candidateMinArgumentCount--; - couldBeAmbiguous= fArgumentCount >= candidateMinArgumentCount; - } else { - couldBeAmbiguous= false; - } - if (couldBeAmbiguous) { - ITypeBinding parameterType= ASTResolving.getParameterTypeBinding(candidate, fArgIndex); - if (parameterType != null && parameterType.getFunctionalInterfaceMethod() != null) { - if (!fExpressionIsExplicitlyTyped) { - /* According to JLS8 15.12.2.2, implicitly typed lambda expressions are not "pertinent to applicability" - * and hence potentially applicable methods are always "applicable by strict invocation", - * regardless of whether argument expressions are compatible with the method's parameter types or not. - * If there are multiple such methods, 15.12.2.5 results in an ambiguous method invocation. - */ - return false; - } - /* Explicitly typed lambda expressions are pertinent to applicability, and hence - * compatibility with the corresponding method parameter type is checked. And since this check - * separates functional interface methods by their void-compatibility state, functional interfaces - * with a different void compatibility are not applicable any more and hence can't cause - * an ambiguous method invocation. - */ - ITypeBinding origParamType= ASTResolving.getParameterTypeBinding(fOriginalMethod, fArgIndex); - boolean originalIsVoidCompatible= Bindings.isVoidType(origParamType.getFunctionalInterfaceMethod().getReturnType()); - boolean candidateIsVoidCompatible= Bindings.isVoidType(parameterType.getFunctionalInterfaceMethod().getReturnType()); - if (originalIsVoidCompatible == candidateIsVoidCompatible) { - return false; - } - } - } - } - } - return true; - } - } - - /** - * Derives the target type defined at the location of the given expression if the target context - * supports poly expressions. - * - * @param expression the expression at whose location the target type is required - * @return the type binding of the target type defined at the location of the given expression - * if the target context supports poly expressions, or <code>null</code> if the target - * type could not be derived - * - * @since 3.10 - */ - public static ITypeBinding getTargetType(Expression expression) { - ASTNode parent= expression.getParent(); - StructuralPropertyDescriptor locationInParent= expression.getLocationInParent(); - - if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY || locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY) { - return ((VariableDeclaration) parent).getName().resolveTypeBinding(); - - } else if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY) { - return ((Assignment) parent).getLeftHandSide().resolveTypeBinding(); - - } else if (locationInParent == ReturnStatement.EXPRESSION_PROPERTY) { - return getTargetTypeForReturnStmt((ReturnStatement) parent); - - } else if (locationInParent == ArrayInitializer.EXPRESSIONS_PROPERTY) { - return getTargetTypeForArrayInitializer((ArrayInitializer) parent); - - } else if (locationInParent == MethodInvocation.ARGUMENTS_PROPERTY) { - MethodInvocation methodInvocation= (MethodInvocation) parent; - IMethodBinding methodBinding= methodInvocation.resolveMethodBinding(); - if (methodBinding != null) { - return getParameterTypeBinding(expression, methodInvocation.arguments(), methodBinding); - } - - } else if (locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY) { - SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent; - IMethodBinding superMethodBinding= superMethodInvocation.resolveMethodBinding(); - if (superMethodBinding != null) { - return getParameterTypeBinding(expression, superMethodInvocation.arguments(), superMethodBinding); - } - - } else if (locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY) { - ConstructorInvocation constructorInvocation= (ConstructorInvocation) parent; - IMethodBinding constructorBinding= constructorInvocation.resolveConstructorBinding(); - if (constructorBinding != null) { - return getParameterTypeBinding(expression, constructorInvocation.arguments(), constructorBinding); - } - - } else if (locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY) { - SuperConstructorInvocation superConstructorInvocation= (SuperConstructorInvocation) parent; - IMethodBinding superConstructorBinding= superConstructorInvocation.resolveConstructorBinding(); - if (superConstructorBinding != null) { - return getParameterTypeBinding(expression, superConstructorInvocation.arguments(), superConstructorBinding); - } - - } else if (locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY) { - ClassInstanceCreation creation= (ClassInstanceCreation) parent; - IMethodBinding creationBinding= creation.resolveConstructorBinding(); - if (creationBinding != null) { - return getParameterTypeBinding(expression, creation.arguments(), creationBinding); - } - - } else if (locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY) { - EnumConstantDeclaration enumConstantDecl= (EnumConstantDeclaration) parent; - IMethodBinding enumConstructorBinding= enumConstantDecl.resolveConstructorBinding(); - if (enumConstructorBinding != null) { - return getParameterTypeBinding(expression, enumConstantDecl.arguments(), enumConstructorBinding); - } - - } else if (locationInParent == LambdaExpression.BODY_PROPERTY) { - IMethodBinding methodBinding= ((LambdaExpression) parent).resolveMethodBinding(); - if (methodBinding != null) { - return methodBinding.getReturnType(); - } - - } else if (locationInParent == ConditionalExpression.THEN_EXPRESSION_PROPERTY || locationInParent == ConditionalExpression.ELSE_EXPRESSION_PROPERTY) { - return getTargetType((ConditionalExpression) parent); - - } else if (locationInParent == CastExpression.EXPRESSION_PROPERTY) { - return ((CastExpression) parent).getType().resolveBinding(); - - } else if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) { - return getTargetType((ParenthesizedExpression) parent); - - } - return null; - } - - private static ITypeBinding getParameterTypeBinding(Expression expression, List<Expression> arguments, IMethodBinding methodBinding) { - int index= arguments.indexOf(expression); - return ASTResolving.getParameterTypeBinding(methodBinding, index); - } - - private static ITypeBinding getTargetTypeForArrayInitializer(ArrayInitializer arrayInitializer) { - ASTNode initializerParent= arrayInitializer.getParent(); - while (initializerParent instanceof ArrayInitializer) { - initializerParent= initializerParent.getParent(); - } - if (initializerParent instanceof ArrayCreation) { - return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding(); - } else if (initializerParent instanceof VariableDeclaration) { - ITypeBinding typeBinding= ((VariableDeclaration) initializerParent).getName().resolveTypeBinding(); - if (typeBinding != null) { - return typeBinding.getElementType(); - } - } - return null; - } - - private static ITypeBinding getTargetTypeForReturnStmt(ReturnStatement returnStmt) { - LambdaExpression enclosingLambdaExpr= ASTResolving.findEnclosingLambdaExpression(returnStmt); - if (enclosingLambdaExpr != null) { - IMethodBinding methodBinding= enclosingLambdaExpr.resolveMethodBinding(); - return methodBinding == null ? null : methodBinding.getReturnType(); - } - MethodDeclaration enclosingMethodDecl= ASTResolving.findParentMethodDeclaration(returnStmt); - if (enclosingMethodDecl != null) { - IMethodBinding methodBinding= enclosingMethodDecl.resolveBinding(); - return methodBinding == null ? null : methodBinding.getReturnType(); - } - return null; - } - - /** - * Returns whether an expression at the given location needs explicit boxing. - * - * @param expression the expression - * @return <code>true</code> iff an expression at the given location needs explicit boxing - * @since 3.6 - */ - private static boolean needsExplicitBoxing(Expression expression) { - StructuralPropertyDescriptor locationInParent= expression.getLocationInParent(); - if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) - return needsExplicitBoxing((ParenthesizedExpression) expression.getParent()); - - if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY - || locationInParent == FieldAccess.EXPRESSION_PROPERTY - || locationInParent == MethodInvocation.EXPRESSION_PROPERTY) - return true; - - return false; - } - - /** - * Checks whether the given expression is a lambda expression with explicitly typed parameters. - * - * @param expression the expression to check - * @return <code>true</code> if the expression is a lambda expression with explicitly typed - * parameters or no parameters, <code>false</code> otherwise - */ - public static boolean isExplicitlyTypedLambda(Expression expression) { - if (!(expression instanceof LambdaExpression)) - return false; - LambdaExpression lambda= (LambdaExpression) expression; - List<VariableDeclaration> parameters= lambda.parameters(); - if (parameters.isEmpty()) - return true; - return parameters.get(0) instanceof SingleVariableDeclaration; - } - - /** - * Returns the closest ancestor of <code>node</code> that is an instance of <code>parentClass</code>, or <code>null</code> if none. - * <p> - * <b>Warning:</b> This method does not stop at any boundaries like parentheses, statements, body declarations, etc. - * The resulting node may be in a totally different scope than the given node. - * Consider using one of the {@link ASTResolving}<code>.find(..)</code> methods instead. - * </p> - * @param node the node - * @param parentClass the class of the sought ancestor node - * @return the closest ancestor of <code>node</code> that is an instance of <code>parentClass</code>, or <code>null</code> if none - */ - public static ASTNode getParent(ASTNode node, Class<? extends ASTNode> parentClass) { - do { - node= node.getParent(); - } while (node != null && !parentClass.isInstance(node)); - return node; - } - - /** - * Returns the closest ancestor of <code>node</code> whose type is <code>nodeType</code>, or <code>null</code> if none. - * <p> - * <b>Warning:</b> This method does not stop at any boundaries like parentheses, statements, body declarations, etc. - * The resulting node may be in a totally different scope than the given node. - * Consider using one of the {@link ASTResolving}<code>.find(..)</code> methods instead. - * </p> - * @param node the node - * @param nodeType the node type constant from {@link ASTNode} - * @return the closest ancestor of <code>node</code> whose type is <code>nodeType</code>, or <code>null</code> if none - */ - public static ASTNode getParent(ASTNode node, int nodeType) { - do { - node= node.getParent(); - } while (node != null && node.getNodeType() != nodeType); - return node; - } - - public static ASTNode findParent(ASTNode node, StructuralPropertyDescriptor[][] pathes) { - for (int p= 0; p < pathes.length; p++) { - StructuralPropertyDescriptor[] path= pathes[p]; - ASTNode current= node; - int d= path.length - 1; - for (; d >= 0 && current != null; d--) { - StructuralPropertyDescriptor descriptor= path[d]; - if (!descriptor.equals(current.getLocationInParent())) - break; - current= current.getParent(); - } - if (d < 0) - return current; - } - return null; - } - - /** - * For {@link Name} or {@link Type} nodes, returns the topmost {@link Type} node - * that shares the same type binding as the given node. - * - * @param node an ASTNode - * @return the normalized {@link Type} node or the original node - */ - public static ASTNode getNormalizedNode(ASTNode node) { - ASTNode current= node; - // normalize name - if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) { - current= current.getParent(); - } - // normalize type - if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent()) - || SimpleType.NAME_PROPERTY.equals(current.getLocationInParent()) - || NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) { - current= current.getParent(); - } - // normalize parameterized types - if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) { - current= current.getParent(); - } - return current; - } - - /** - * Returns <code>true</code> iff <code>parent</code> is a true ancestor of <code>node</code> - * (i.e. returns <code>false</code> if <code>parent == node</code>). - * - * @param node node to test - * @param parent assumed parent - * @return <code>true</code> iff <code>parent</code> is a true ancestor of <code>node</code> - */ - public static boolean isParent(ASTNode node, ASTNode parent) { - Assert.isNotNull(parent); - do { - node= node.getParent(); - if (node == parent) - return true; - } while (node != null); - return false; - } - - public static int getExclusiveEnd(ASTNode node){ - return node.getStartPosition() + node.getLength(); - } - - public static int getInclusiveEnd(ASTNode node){ - return node.getStartPosition() + node.getLength() - 1; - } - - public static IMethodBinding getMethodBinding(Name node) { - IBinding binding= node.resolveBinding(); - if (binding instanceof IMethodBinding) - return (IMethodBinding)binding; - return null; - } - - public static IVariableBinding getVariableBinding(Name node) { - IBinding binding= node.resolveBinding(); - if (binding instanceof IVariableBinding) - return (IVariableBinding)binding; - return null; - } - - public static IVariableBinding getLocalVariableBinding(Name node) { - IVariableBinding result= getVariableBinding(node); - if (result == null || result.isField()) - return null; - - return result; - } - - public static IVariableBinding getFieldBinding(Name node) { - IVariableBinding result= getVariableBinding(node); - if (result == null || !result.isField()) - return null; - - return result; - } - - public static ITypeBinding getTypeBinding(Name node) { - IBinding binding= node.resolveBinding(); - if (binding instanceof ITypeBinding) - return (ITypeBinding)binding; - return null; - } - - /** - * Returns the receiver's type binding of the given method invocation. - * - * @param invocation method invocation to resolve type of - * @return the type binding of the receiver - */ - public static ITypeBinding getReceiverTypeBinding(MethodInvocation invocation) { - ITypeBinding result= null; - Expression exp= invocation.getExpression(); - if(exp != null) { - return exp.resolveTypeBinding(); - } - else { - AbstractTypeDeclaration type= (AbstractTypeDeclaration)getParent(invocation, AbstractTypeDeclaration.class); - if (type != null) - return type.resolveBinding(); - } - return result; - } - - public static ITypeBinding getEnclosingType(ASTNode node) { - while(node != null) { - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration)node).resolveBinding(); - } else if (node instanceof AnonymousClassDeclaration) { - return ((AnonymousClassDeclaration)node).resolveBinding(); - } - node= node.getParent(); - } - return null; - } - - public static IBinding getEnclosingDeclaration(ASTNode node) { - while(node != null) { - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration)node).resolveBinding(); - } else if (node instanceof AnonymousClassDeclaration) { - return ((AnonymousClassDeclaration)node).resolveBinding(); - } else if (node instanceof MethodDeclaration) { - return ((MethodDeclaration)node).resolveBinding(); - } else if (node instanceof FieldDeclaration) { - List<?> fragments= ((FieldDeclaration)node).fragments(); - if (fragments.size() > 0) - return ((VariableDeclarationFragment)fragments.get(0)).resolveBinding(); - } else if (node instanceof VariableDeclarationFragment) { - IVariableBinding variableBinding= ((VariableDeclarationFragment)node).resolveBinding(); - if (variableBinding.getDeclaringMethod() != null || variableBinding.getDeclaringClass() != null) - return variableBinding; - // workaround for incomplete wiring of DOM bindings: keep searching when variableBinding is unparented - } - node= node.getParent(); - } - return null; - } - - public static IProblem[] getProblems(ASTNode node, int scope, int severity) { - ASTNode root= node.getRoot(); - if (!(root instanceof CompilationUnit)) - return EMPTY_PROBLEMS; - IProblem[] problems= ((CompilationUnit)root).getProblems(); - if (root == node) - return problems; - final int iterations= computeIterations(scope); - List<IProblem> result= new ArrayList<>(5); - for (int i= 0; i < problems.length; i++) { - IProblem problem= problems[i]; - boolean consider= false; - if ((severity & PROBLEMS) == PROBLEMS) - consider= true; - else if ((severity & WARNING) != 0) - consider= problem.isWarning(); - else if ((severity & ERROR) != 0) - consider= problem.isError(); - else if ((severity & INFO) != 0) - consider= problem.isInfo(); - if (consider) { - ASTNode temp= node; - int count= iterations; - do { - int nodeOffset= temp.getStartPosition(); - int problemOffset= problem.getSourceStart(); - if (nodeOffset <= problemOffset && problemOffset < nodeOffset + temp.getLength()) { - result.add(problem); - count= 0; - } else { - count--; - } - } while ((temp= temp.getParent()) != null && count > 0); - } - } - return result.toArray(new IProblem[result.size()]); - } - - public static Message[] getMessages(ASTNode node, int flags) { - ASTNode root= node.getRoot(); - if (!(root instanceof CompilationUnit)) - return EMPTY_MESSAGES; - Message[] messages= ((CompilationUnit)root).getMessages(); - if (root == node) - return messages; - final int iterations= computeIterations(flags); - List<Message> result= new ArrayList<>(5); - for (int i= 0; i < messages.length; i++) { - Message message= messages[i]; - ASTNode temp= node; - int count= iterations; - do { - int nodeOffset= temp.getStartPosition(); - int messageOffset= message.getStartPosition(); - if (nodeOffset <= messageOffset && messageOffset < nodeOffset + temp.getLength()) { - result.add(message); - count= 0; - } else { - count--; - } - } while ((temp= temp.getParent()) != null && count > 0); - } - return result.toArray(new Message[result.size()]); - } - - private static int computeIterations(int flags) { - switch (flags) { - case NODE_ONLY: - return 1; - case INCLUDE_ALL_PARENTS: - return Integer.MAX_VALUE; - case INCLUDE_FIRST_PARENT: - return 2; - default: - return 1; - } - } - - - private static int getOrderPreference(BodyDeclaration member, MembersOrderPreferenceCache store) { - int memberType= member.getNodeType(); - int modifiers= member.getModifiers(); - - switch (memberType) { - case ASTNode.TYPE_DECLARATION: - case ASTNode.ENUM_DECLARATION : - case ASTNode.ANNOTATION_TYPE_DECLARATION : - return store.getCategoryIndex(MembersOrderPreferenceCache.TYPE_INDEX) * 2; - case ASTNode.FIELD_DECLARATION: - if (Modifier.isStatic(modifiers)) { - int index= store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX) * 2; - if (Modifier.isFinal(modifiers)) { - return index; // first final static, then static - } - return index + 1; - } - return store.getCategoryIndex(MembersOrderPreferenceCache.FIELDS_INDEX) * 2; - case ASTNode.INITIALIZER: - if (Modifier.isStatic(modifiers)) { - return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX) * 2; - } - return store.getCategoryIndex(MembersOrderPreferenceCache.INIT_INDEX) * 2; - case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: - return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; - case ASTNode.METHOD_DECLARATION: - if (Modifier.isStatic(modifiers)) { - return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_METHODS_INDEX) * 2; - } - if (((MethodDeclaration) member).isConstructor()) { - return store.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX) * 2; - } - return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; - default: - return 100; - } - } - - /** - * Computes the insertion index to be used to add the given member to the - * the list <code>container</code>. - * @param member the member to add - * @param container a list containing objects of type <code>BodyDeclaration</code> - * @return the insertion index to be used - */ - public static int getInsertionIndex(BodyDeclaration member, List<? extends BodyDeclaration> container) { - int containerSize= container.size(); - - MembersOrderPreferenceCache orderStore= JavaPlugin.getDefault().getMemberOrderPreferenceCache(); - - int orderIndex= getOrderPreference(member, orderStore); - - int insertPos= containerSize; - int insertPosOrderIndex= -1; - - for (int i= containerSize - 1; i >= 0; i--) { - int currOrderIndex= getOrderPreference(container.get(i), orderStore); - if (orderIndex == currOrderIndex) { - if (insertPosOrderIndex != orderIndex) { // no perfect match yet - insertPos= i + 1; // after a same kind - insertPosOrderIndex= orderIndex; // perfect match - } - } else if (insertPosOrderIndex != orderIndex) { // not yet a perfect match - if (currOrderIndex < orderIndex) { // we are bigger - if (insertPosOrderIndex == -1) { - insertPos= i + 1; // after - insertPosOrderIndex= currOrderIndex; - } - } else { - insertPos= i; // before - insertPosOrderIndex= currOrderIndex; - } - } - } - return insertPos; - } - - public static SimpleName getLeftMostSimpleName(Name name) { - if (name instanceof SimpleName) { - return (SimpleName)name; - } else { - final SimpleName[] result= new SimpleName[1]; - ASTVisitor visitor= new ASTVisitor() { - @Override - public boolean visit(QualifiedName qualifiedName) { - Name left= qualifiedName.getQualifier(); - if (left instanceof SimpleName) - result[0]= (SimpleName)left; - else - left.accept(this); - return false; - } - }; - name.accept(visitor); - return result[0]; - } - } - - /** - * Returns the topmost ancestor of <code>name</code> that is still a {@link Name}. - * <p> - * <b>Note:</b> The returned node may resolve to a different binding than the given <code>name</code>! - * - * @param name a name node - * @return the topmost name - * @see #getNormalizedNode(ASTNode) - */ - public static Name getTopMostName(Name name) { - Name result= name; - while(result.getParent() instanceof Name) { - result= (Name)result.getParent(); - } - return result; - } - - /** - * Returns the topmost ancestor of <code>node</code> that is a {@link Type} (but not a {@link UnionType}). - * <p> - * <b>Note:</b> The returned node often resolves to a different binding than the given <code>node</code>! - * - * @param node the starting node, can be <code>null</code> - * @return the topmost type or <code>null</code> if the node is not a descendant of a type node - * @see #getNormalizedNode(ASTNode) - */ - public static Type getTopMostType(ASTNode node) { - ASTNode result= null; - while (node instanceof Type && !(node instanceof UnionType) - || node instanceof Name - || node instanceof Annotation || node instanceof MemberValuePair - || node instanceof Expression) { // Expression could maybe be reduced to expression node types that can appear in an annotation - result= node; - node= node.getParent(); - } - - if (result instanceof Type) - return (Type) result; - - return null; - } - - public static int changeVisibility(int modifiers, int visibility) { - return (modifiers & CLEAR_VISIBILITY) | visibility; - } - - /** - * Adds flags to the given node and all its descendants. - * @param root The root node - * @param flags The flags to set - */ - public static void setFlagsToAST(ASTNode root, final int flags) { - root.accept(new GenericVisitor(true) { - @Override - protected boolean visitNode(ASTNode node) { - node.setFlags(node.getFlags() | flags); - return true; - } - }); - } - - public static String getQualifier(Name name) { - if (name.isQualifiedName()) { - return ((QualifiedName) name).getQualifier().getFullyQualifiedName(); - } - return ""; //$NON-NLS-1$ - } - - public static String getSimpleNameIdentifier(Name name) { - if (name.isQualifiedName()) { - return ((QualifiedName) name).getName().getIdentifier(); - } else { - return ((SimpleName) name).getIdentifier(); - } - } - - public static boolean isDeclaration(Name name) { - if (name.isQualifiedName()) { - return ((QualifiedName) name).getName().isDeclaration(); - } else { - return ((SimpleName) name).isDeclaration(); - } - } - - public static Modifier findModifierNode(int flag, List<IExtendedModifier> modifiers) { - for (int i= 0; i < modifiers.size(); i++) { - Object curr= modifiers.get(i); - if (curr instanceof Modifier && ((Modifier) curr).getKeyword().toFlagValue() == flag) { - return (Modifier) curr; - } - } - return null; - } - - public static ITypeBinding getTypeBinding(CompilationUnit root, IType type) throws JavaModelException { - if (type.isAnonymous()) { - final IJavaElement parent= type.getParent(); - if (parent instanceof IField && Flags.isEnum(((IMember) parent).getFlags())) { - final EnumConstantDeclaration constant= (EnumConstantDeclaration) NodeFinder.perform(root, ((ISourceReference) parent).getSourceRange()); - if (constant != null) { - final AnonymousClassDeclaration declaration= constant.getAnonymousClassDeclaration(); - if (declaration != null) - return declaration.resolveBinding(); - } - } else { - final ClassInstanceCreation creation= (ClassInstanceCreation) getParent(NodeFinder.perform(root, type.getNameRange()), ClassInstanceCreation.class); - if (creation != null) - return creation.resolveTypeBinding(); - } - } else { - final AbstractTypeDeclaration declaration= (AbstractTypeDeclaration) getParent(NodeFinder.perform(root, type.getNameRange()), AbstractTypeDeclaration.class); - if (declaration != null) - return declaration.resolveBinding(); - } - return null; - } - - /** - * Escapes a string value to a literal that can be used in Java source. - * - * @param stringValue the string value - * @return the escaped string - * @see StringLiteral#getEscapedValue() - */ - public static String getEscapedStringLiteral(String stringValue) { - StringLiteral stringLiteral= AST.newAST(ASTProvider.SHARED_AST_LEVEL).newStringLiteral(); - stringLiteral.setLiteralValue(stringValue); - return stringLiteral.getEscapedValue(); - } - - /** - * Escapes a character value to a literal that can be used in Java source. - * - * @param ch the character value - * @return the escaped string - * @see CharacterLiteral#getEscapedValue() - */ - public static String getEscapedCharacterLiteral(char ch) { - CharacterLiteral characterLiteral= AST.newAST(ASTProvider.SHARED_AST_LEVEL).newCharacterLiteral(); - characterLiteral.setCharValue(ch); - return characterLiteral.getEscapedValue(); - } - - /** - * If the given <code>node</code> has already been rewritten, undo that rewrite and return the - * replacement version of the node. Otherwise, return the result of - * {@link ASTRewrite#createCopyTarget(ASTNode)}. - * - * @param rewrite ASTRewrite for the given node - * @param node the node to get the replacement or to create a copy placeholder for - * @param group the edit group which collects the corresponding text edits, or <code>null</code> - * if ungrouped - * @return the replacement node if the given <code>node</code> has already been rewritten or the - * new copy placeholder node - */ - public static ASTNode getCopyOrReplacement(ASTRewrite rewrite, ASTNode node, TextEditGroup group) { - ASTNode rewrittenNode= (ASTNode) rewrite.get(node.getParent(), node.getLocationInParent()); - if (rewrittenNode != node) { - // Undo previous rewrite to avoid the problem that the same node would be inserted in two places: - rewrite.replace(rewrittenNode, node, group); - return rewrittenNode; - } - return rewrite.createCopyTarget(node); - } - - /** - * Type-safe variant of {@link ASTRewrite#createMoveTarget(ASTNode)}. - * - * @param rewrite ASTRewrite for the given node - * @param node the node to create a move placeholder for - * @return the new placeholder node - * @throws IllegalArgumentException if the node is null, or if the node - * is not part of the rewrite's AST - */ - @SuppressWarnings("unchecked") - public static <T extends ASTNode> T createMoveTarget(ASTRewrite rewrite, T node) { - return (T) rewrite.createMoveTarget(node); - } - - /** - * Type-safe variant of {@link ASTNode#copySubtree(AST, ASTNode)}. - * - * @param target the AST that is to own the nodes in the result - * @param node the node to copy, or <code>null</code> if none - * @return the copied node, or <code>null</code> if <code>node</code> - * is <code>null</code> - */ - @SuppressWarnings("unchecked") - public static <T extends ASTNode> T copySubtree(AST target, T node) { - return (T) ASTNode.copySubtree(target, node); - } - - /** - * Returns a list of local variable names which are visible at the given node. - * - * @param node the AST node - * @return a list of local variable names visible at the given node - * @see ScopeAnalyzer#getDeclarationsInScope(int, int) - * @since 3.10 - */ - public static List<String> getVisibleLocalVariablesInScope(ASTNode node) { - List<String> variableNames= new ArrayList<>(); - CompilationUnit root= (CompilationUnit) node.getRoot(); - IBinding[] bindings= new ScopeAnalyzer(root). - getDeclarationsInScope(node.getStartPosition(), ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY); - for (IBinding binding : bindings) { - if (binding instanceof IVariableBinding && !((IVariableBinding) binding).isField()) { - variableNames.add(binding.getName()); - } - } - return variableNames; - } - - /** - * Checks whether the given <code>exprStatement</code> has a semicolon at the end. - * - * @param exprStatement the {@link ExpressionStatement} to check the semicolon - * @param cu the compilation unit - * @return <code>true</code> if the given <code>exprStatement</code> has a semicolon at the end, - * <code>false</code> otherwise - */ - public static boolean hasSemicolon(ExpressionStatement exprStatement, ICompilationUnit cu) { - boolean hasSemicolon= true; - if ((exprStatement.getFlags() & ASTNode.RECOVERED) != 0) { - try { - Expression expression= exprStatement.getExpression(); - TokenScanner scanner= new TokenScanner(cu); - hasSemicolon= scanner.readNext(expression.getStartPosition() + expression.getLength(), true) == ITerminalSymbols.TokenNameSEMICOLON; - } catch (CoreException e) { - hasSemicolon= false; - } - } - return hasSemicolon; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java deleted file mode 100644 index 5a449c1929..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/Bindings.java +++ /dev/null @@ -1,1642 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for - * bug "inline method - doesn't handle implicit cast" (see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941). - * Rabea Gransberger <rgransberger@gmx.de> - [quick fix] Fix several visibility issues - https://bugs.eclipse.org/394692 - * Stephan Herrmann - Contribution for Bug 463360 - [override method][null] generating method override should not create redundant null annotations - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.eclipse.core.runtime.Assert; - -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.dom.AST; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.Annotation; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayAccess; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.IAnnotationBinding; -import org.eclipse.jdt.core.dom.IBinding; -import org.eclipse.jdt.core.dom.IMethodBinding; -import org.eclipse.jdt.core.dom.IPackageBinding; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.IVariableBinding; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.Name; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PostfixExpression; -import org.eclipse.jdt.core.dom.PrefixExpression; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; - -import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; -import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; - -/** - * JDT-UI-internal helper methods that deal with {@link IBinding}s: - * <ul> - * <li>additional operations on {@link IBinding}s and subtypes</li> - * <li>finding corresponding elements in the type hierarchy</li> - * <li>resolve bindings from a family of {@link ASTNode} types</li> - * </ul> - * - * @see JDTUIHelperClasses - */ -public class Bindings { - - public static final String ARRAY_LENGTH_FIELD_BINDING_STRING= "(array type):length";//$NON-NLS-1$ - private Bindings() { - // No instance - } - - /** - * Checks if the two bindings are equals. Also works across binding environments. - * @param b1 first binding treated as <code>this</code>. So it must - * not be <code>null</code> - * @param b2 the second binding. - * @return boolean - */ - public static boolean equals(IBinding b1, IBinding b2) { - return b1.isEqualTo(b2); - } - - - /** - * Checks if the declarations of two bindings are equals. - * Also works across binding environments. - * @param b1 first binding, must not be <code>null</code> - * @param b2 second binding, must not be <code>null</code> - * @return boolean - */ - public static boolean equalDeclarations(IBinding b1, IBinding b2) { - if (b1.getKind() != b2.getKind()) - return false; - return getDeclaration(b1).isEqualTo(getDeclaration(b2)); - } - - /** - * Checks if the two arrays of bindings have the same length and - * their elements are equal. Uses - * <code>Bindings.equals(IBinding, IBinding)</code> to compare. - * @param b1 the first array of bindings. Must not be <code>null</code>. - * @param b2 the second array of bindings. - * @return boolean - */ - public static boolean equals(IBinding[] b1, IBinding[] b2) { - Assert.isNotNull(b1); - if (b1 == b2) - return true; - if (b2 == null) - return false; - if (b1.length != b2.length) - return false; - for (int i= 0; i < b1.length; i++) { - if (! Bindings.equals(b1[i], b2[i])) - return false; - } - return true; - } - - public static int hashCode(IBinding binding){ - Assert.isNotNull(binding); - String key= binding.getKey(); - if (key == null) - return binding.hashCode(); - return key.hashCode(); - } - - /** - * Note: this method is for debugging and testing purposes only. - * There are tests whose pre-computed test results rely on the returned String's format. - * @param binding the binding - * @return a string representation of given binding - * @see org.eclipse.jdt.internal.ui.viewsupport.BindingLabelProvider - */ - public static String asString(IBinding binding) { - if (binding instanceof IMethodBinding) - return asString((IMethodBinding)binding); - else if (binding instanceof ITypeBinding) - return ((ITypeBinding)binding).getQualifiedName(); - else if (binding instanceof IVariableBinding) - return asString((IVariableBinding)binding); - return binding.toString(); - } - - private static String asString(IVariableBinding variableBinding) { - if (! variableBinding.isField()) - return variableBinding.toString(); - if (variableBinding.getDeclaringClass() == null) { - Assert.isTrue(variableBinding.getName().equals("length"));//$NON-NLS-1$ - return ARRAY_LENGTH_FIELD_BINDING_STRING; - } - StringBuffer result= new StringBuffer(); - result.append(variableBinding.getDeclaringClass().getName()); - result.append(':'); - result.append(variableBinding.getName()); - return result.toString(); - } - - private static String asString(IMethodBinding method) { - StringBuffer result= new StringBuffer(); - result.append(method.getDeclaringClass().getName()); - result.append(':'); - result.append(method.getName()); - result.append('('); - ITypeBinding[] parameters= method.getParameterTypes(); - int lastComma= parameters.length - 1; - for (int i= 0; i < parameters.length; i++) { - ITypeBinding parameter= parameters[i]; - result.append(parameter.getName()); - if (i < lastComma) - result.append(", "); //$NON-NLS-1$ - } - result.append(')'); - return result.toString(); - } - - public static String getTypeQualifiedName(ITypeBinding type) { - List<String> result= new ArrayList<>(5); - createName(type, false, result); - - StringBuffer buffer= new StringBuffer(); - for (int i= 0; i < result.size(); i++) { - if (i > 0) { - buffer.append('.'); - } - buffer.append(result.get(i)); - } - return buffer.toString(); - } - - /** - * Returns the fully qualified name of the specified type binding. - * <p> - * If the binding resolves to a generic type, the fully qualified name of the raw type is returned. - * - * @param type the type binding to get its fully qualified name - * @return the fully qualified name - */ - public static String getFullyQualifiedName(ITypeBinding type) { - String name= type.getQualifiedName(); - final int index= name.indexOf('<'); - if (index > 0) - name= name.substring(0, index); - return name; - } - - public static String getImportName(IBinding binding) { - ITypeBinding declaring= null; - switch (binding.getKind()) { - case IBinding.TYPE: - return getRawQualifiedName((ITypeBinding) binding); - case IBinding.PACKAGE: - return binding.getName() + ".*"; //$NON-NLS-1$ - case IBinding.METHOD: - declaring= ((IMethodBinding) binding).getDeclaringClass(); - break; - case IBinding.VARIABLE: - declaring= ((IVariableBinding) binding).getDeclaringClass(); - if (declaring == null) { - return binding.getName(); // array.length - } - - break; - default: - return binding.getName(); - } - return JavaModelUtil.concatenateName(getRawQualifiedName(declaring), binding.getName()); - } - - - private static void createName(ITypeBinding type, boolean includePackage, List<String> list) { - ITypeBinding baseType= type; - if (type.isArray()) { - baseType= type.getElementType(); - } - if (!baseType.isPrimitive() && !baseType.isNullType()) { - ITypeBinding declaringType= baseType.getDeclaringClass(); - if (declaringType != null) { - createName(declaringType, includePackage, list); - } else if (includePackage && !baseType.getPackage().isUnnamed()) { - String[] components= baseType.getPackage().getNameComponents(); - for (int i= 0; i < components.length; i++) { - list.add(components[i]); - } - } - } - if (!baseType.isAnonymous()) { - list.add(type.getName()); - } else { - list.add("$local$"); //$NON-NLS-1$ - } - } - - - public static String[] getNameComponents(ITypeBinding type) { - List<String> result= new ArrayList<>(5); - createName(type, false, result); - return result.toArray(new String[result.size()]); - } - - public static String[] getAllNameComponents(ITypeBinding type) { - List<String> result= new ArrayList<>(5); - createName(type, true, result); - return result.toArray(new String[result.size()]); - } - - public static ITypeBinding getTopLevelType(ITypeBinding type) { - ITypeBinding parent= type.getDeclaringClass(); - while (parent != null) { - type= parent; - parent= type.getDeclaringClass(); - } - return type; - } - - /** - * Checks whether the passed type binding is a runtime exception. - * - * @param thrownException the type binding - * - * @return <code>true</code> if the passed type binding is a runtime exception; - * otherwise <code>false</code> is returned - */ - public static boolean isRuntimeException(ITypeBinding thrownException) { - if (thrownException == null || thrownException.isPrimitive() || thrownException.isArray()) - return false; - return findTypeInHierarchy(thrownException, "java.lang.RuntimeException") != null; //$NON-NLS-1$ - } - - /** - * Finds the field specified by <code>fieldName</code> in - * the given <code>type</code>. Returns <code>null</code> if no such field exists. - * @param type the type to search the field in - * @param fieldName the field name - * @return the binding representing the field or <code>null</code> - */ - public static IVariableBinding findFieldInType(ITypeBinding type, String fieldName) { - if (type.isPrimitive()) - return null; - IVariableBinding[] fields= type.getDeclaredFields(); - for (int i= 0; i < fields.length; i++) { - IVariableBinding field= fields[i]; - if (field.getName().equals(fieldName)) - return field; - } - return null; - } - - /** - * Finds the field specified by <code>fieldName</code> in - * the type hierarchy denoted by the given type. Returns <code>null</code> if no such field - * exists. If the field is defined in more than one super type only the first match is - * returned. First the super class is examined and then the implemented interfaces. - * @param type The type to search the field in - * @param fieldName The name of the field to find - * @return the variable binding representing the field - */ - public static IVariableBinding findFieldInHierarchy(ITypeBinding type, String fieldName) { - IVariableBinding field= findFieldInType(type, fieldName); - if (field != null) - return field; - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - field= findFieldInHierarchy(superClass, fieldName); - if (field != null) - return field; - } - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - field= findFieldInHierarchy(interfaces[i], fieldName); - if (field != null) // no private fields in interfaces - return field; - } - return null; - } - - /** - * Finds the method specified by <code>methodName</code> and <code>parameters</code> in - * the given <code>type</code>. Returns <code>null</code> if no such method exists. - * @param type The type to search the method in - * @param methodName The name of the method to find - * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only - * the name is matched and parameters are ignored. - * @return the method binding representing the method - */ - public static IMethodBinding findMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) { - if (type.isPrimitive()) - return null; - IMethodBinding[] methods= type.getDeclaredMethods(); - for (int i= 0; i < methods.length; i++) { - if (parameters == null) { - if (methodName.equals(methods[i].getName())) - return methods[i]; - } else { - if (isEqualMethod(methods[i], methodName, parameters)) - return methods[i]; - } - } - return null; - } - - /** - * Finds the method specified by <code>methodName</code> and <code>parameters</code> in - * the type hierarchy denoted by the given type. Returns <code>null</code> if no such method - * exists. If the method is defined in more than one super type only the first match is - * returned. First the super class is examined and then the implemented interfaces. - * - * @param type The type to search the method in - * @param methodName The name of the method to find - * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored. - * @return the method binding representing the method - */ - public static IMethodBinding findMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding[] parameters) { - IMethodBinding method= findMethodInType(type, methodName, parameters); - if (method != null) - return method; - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - method= findMethodInHierarchy(superClass, methodName, parameters); - if (method != null) - return method; - } - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - method= findMethodInHierarchy(interfaces[i], methodName, parameters); - if (method != null) - return method; - } - return null; - } - - /** - * Finds the method specified by <code>methodName</code> and <code>parameters</code> in - * the given <code>type</code>. Returns <code>null</code> if no such method exists. - * @param type The type to search the method in - * @param methodName The name of the method to find - * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored. - * @return the method binding representing the method - */ - public static IMethodBinding findMethodInType(ITypeBinding type, String methodName, String[] parameters) { - if (type.isPrimitive()) - return null; - IMethodBinding[] methods= type.getDeclaredMethods(); - for (int i= 0; i < methods.length; i++) { - if (parameters == null) { - if (methodName.equals(methods[i].getName())) - return methods[i]; - } else { - if (isEqualMethod(methods[i], methodName, parameters)) - return methods[i]; - } - } - return null; - } - - /** - * Finds the method specified by <code>methodName</code> and <code>parameters</code> in - * the given <code>type</code>. Returns <code>null</code> if no such method exists. - * <p> - * This variant of {@link #findMethodInType(ITypeBinding, String, String[])} looks for a method - * whose {@link IMethodBinding#getMethodDeclaration() declaration}'s parameters matches the - * given parameters. - * </p> - * - * @param type The type to search the method in - * @param methodName The name of the method to find - * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored. - * @return the method binding representing the method - */ - public static IMethodBinding findMethodWithDeclaredParameterTypesInType(ITypeBinding type, String methodName, String[] parameters) { - if (type.isPrimitive()) - return null; - IMethodBinding[] methods= type.getDeclaredMethods(); - for (int i= 0; i < methods.length; i++) { - if (parameters == null) { - if (methodName.equals(methods[i].getName())) - return methods[i]; - } else { - if (isEqualMethod(methods[i].getMethodDeclaration(), methodName, parameters)) - return methods[i]; - } - } - return null; - } - - /** - * Finds the method specified by <code>methodName</code> and <code>parameters</code> in - * the type hierarchy denoted by the given type. Returns <code>null</code> if no such method - * exists. If the method is defined in more than one super type only the first match is - * returned. First the super class is examined and then the implemented interfaces. - * @param type the type to search the method in - * @param methodName The name of the method to find - * @param parameters The parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored. - * @return the method binding representing the method - */ - public static IMethodBinding findMethodInHierarchy(ITypeBinding type, String methodName, String[] parameters) { - IMethodBinding method= findMethodInType(type, methodName, parameters); - if (method != null) - return method; - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - method= findMethodInHierarchy(superClass, methodName, parameters); - if (method != null) - return method; - } - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - method= findMethodInHierarchy(interfaces[i], methodName, parameters); - if (method != null) - return method; - } - return null; - } - - /** - * Finds the method in the given <code>type</code> that is overridden by the specified <code>method</code>. - * Returns <code>null</code> if no such method exists. - * @param type The type to search the method in - * @param method The specified method that would override the result - * @return the method binding of the method that is overridden by the specified <code>method</code>, or <code>null</code> - */ - public static IMethodBinding findOverriddenMethodInType(ITypeBinding type, IMethodBinding method) { - IMethodBinding[] methods= type.getDeclaredMethods(); - for (int i= 0; i < methods.length; i++) { - if (isSubsignature(method, methods[i])) - return methods[i]; - } - return null; - } - - /** - * Finds a method in the hierarchy of <code>type</code> that is overridden by <code>binding</code>. - * Returns <code>null</code> if no such method exists. If the method is defined in more than one super type only the first match is - * returned. First the super class is examined and then the implemented interfaces. - * @param type The type to search the method in - * @param binding The method that overrides - * @return the method binding overridden the method - */ - public static IMethodBinding findOverriddenMethodInHierarchy(ITypeBinding type, IMethodBinding binding) { - IMethodBinding method= findOverriddenMethodInType(type, binding); - if (method != null) - return method; - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - method= findOverriddenMethodInHierarchy(superClass, binding); - if (method != null) - return method; - } - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - method= findOverriddenMethodInHierarchy(interfaces[i], binding); - if (method != null) - return method; - } - return null; - } - - - /** - * Finds the method that is overridden by the given method. The search is bottom-up, so this - * returns the nearest defining/declaring method. - * @param overriding overriding method - * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. - * @return the method binding representing the method - */ - public static IMethodBinding findOverriddenMethod(IMethodBinding overriding, boolean testVisibility) { - List<IMethodBinding> findOverriddenMethods= findOverriddenMethods(overriding, testVisibility, true); - if (findOverriddenMethods.isEmpty()) { - return null; - } - return findOverriddenMethods.get(0); - } - - /** - * Finds all methods that are overridden by the given method. The search is bottom-up, so this - * returns the nearest defining/declaring methods in order. - * - * @param overriding overriding method - * @param testVisibility if <code>true</code> the result is tested on visibility - * @param firstOnly if <code>true</code> this method will return when the first overridden - * method is found - * @return the method bindings representing the overridden method or an empty list if no result - * is found - * @since 3.9 - */ - public static List<IMethodBinding> findOverriddenMethods(IMethodBinding overriding, boolean testVisibility, boolean firstOnly) { - List<IMethodBinding> methodList= new ArrayList<>(); - - int modifiers= overriding.getModifiers(); - if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || overriding.isConstructor()) { - return methodList; - } - - ITypeBinding type= overriding.getDeclaringClass(); - if (type.getSuperclass() != null) { - IMethodBinding res= findOverriddenMethodInHierarchy(type.getSuperclass(), overriding); - if (res != null && !Modifier.isPrivate(res.getModifiers())) { - if (!testVisibility || isVisibleInHierarchy(res, overriding.getDeclaringClass().getPackage())) { - methodList.add(res); - if (firstOnly) { - return methodList; - } - } - } - } - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - IMethodBinding res= findOverriddenMethodInHierarchy(interfaces[i], overriding); - if (res != null) { - methodList.add(res); // methods from interfaces are always public and therefore visible - if (firstOnly) { - return methodList; - } - } - } - return methodList; - } - - - public static boolean isVisibleInHierarchy(IMethodBinding member, IPackageBinding pack) { - int otherflags= member.getModifiers(); - ITypeBinding declaringType= member.getDeclaringClass(); - if (Modifier.isPublic(otherflags) || Modifier.isProtected(otherflags) || (declaringType != null && declaringType.isInterface())) { - return true; - } else if (Modifier.isPrivate(otherflags)) { - return false; - } - return declaringType != null && pack == declaringType.getPackage(); - } - - /** - * Returns all super types (classes and interfaces) for the given type. - * @param type The type to get the supertypes of. - * @return all super types (excluding <code>type</code>) - */ - public static ITypeBinding[] getAllSuperTypes(ITypeBinding type) { - Set<ITypeBinding> result= new HashSet<>(); - collectSuperTypes(type, result); - result.remove(type); - return result.toArray(new ITypeBinding[result.size()]); - } - - private static void collectSuperTypes(ITypeBinding curr, Set<ITypeBinding> collection) { - if (collection.add(curr)) { - ITypeBinding[] interfaces= curr.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - collectSuperTypes(interfaces[i], collection); - } - ITypeBinding superClass= curr.getSuperclass(); - if (superClass != null) { - collectSuperTypes(superClass, collection); - } - } - } - - /** - * Method to visit a type hierarchy defined by a given type. - * The given type itself is not visited. - * - * @param type the type whose hierarchy is to be visited - * @param visitor the visitor - * @return <code>true</code> if all types were visited, - * or <code>false</code> if the visiting got aborted because the <code>visit</code> - * method returned <code>false</code> for a type - */ - public static boolean visitHierarchy(ITypeBinding type, TypeBindingVisitor visitor) { - boolean result= visitSuperclasses(type, visitor); - if (result) { - result= visitInterfaces(type, visitor); - } - return result; - } - - /** - * Method to visit an interface hierarchy defined by a given type. - * The given type itself is not visited. - * - * @param type the type whose interface hierarchy is to be visited - * @param visitor the visitor - * @return <code>true</code> if all types were visited, - * or <code>false</code> if the visiting got aborted because the <code>visit</code> - * method returned <code>false</code> for a type - */ - public static boolean visitInterfaces(ITypeBinding type, TypeBindingVisitor visitor) { - return visitInterfaces(type, visitor, new HashSet<ITypeBinding>()); - } - - private static boolean visitInterfaces(ITypeBinding type, TypeBindingVisitor visitor, HashSet<ITypeBinding> visited) { - boolean unvisited= visited.add(type); - if (!unvisited) - return true; - ITypeBinding[] interfaces= type.getInterfaces(); - for (int i= 0; i < interfaces.length; i++) { - if (!visitor.visit(interfaces[i])) { - return false; - } - if (!visitInterfaces(interfaces[i], visitor, visited)) { - return false; - } - } - return true; - } - - /** - * Method to visit a super class hierarchy defined by a given type. - * The given type itself is not visited. - * - * @param type the type whose super class hierarchy is to be visited - * @param visitor the visitor - * @return <code>true</code> if all types were visited, - * or <code>false</code> if the visiting got aborted because the <code>visit</code> - * method returned <code>false</code> for a type - */ - public static boolean visitSuperclasses(ITypeBinding type, TypeBindingVisitor visitor) { - while ((type= type.getSuperclass()) != null) { - if (!visitor.visit(type)) { - return false; - } - } - return true; - } - - /** - * Tests whether the two methods are erasure-equivalent. - * @param method the first method - * @param methodName the name of the second method - * @param parameters the parameters of the second method - * @return return <code>true</code> if the two bindings are equal - * @deprecated use {@link #isSubsignature(IMethodBinding, IMethodBinding)} - */ - //TODO: rename to isErasureEquivalentMethod and change to two IMethodBinding parameters - @Deprecated - public static boolean isEqualMethod(IMethodBinding method, String methodName, ITypeBinding[] parameters) { - if (!method.getName().equals(methodName)) - return false; - - ITypeBinding[] methodParameters= method.getParameterTypes(); - if (methodParameters.length != parameters.length) - return false; - for (int i= 0; i < parameters.length; i++) { - if (!equals(methodParameters[i].getErasure(), parameters[i].getErasure())) - return false; - } - //Can't use this fix, since some clients assume that this method tests erasure equivalence: -// if (method.getTypeParameters().length == 0) { -// //a method without type parameters cannot be overridden by one that declares type parameters -> can be exact here -// for (int i= 0; i < parameters.length; i++) { -// if ( ! (equals(methodParameters[i], parameters[i]) -// || equals(methodParameters[i].getErasure(), parameters[i]))) // subsignature -// return false; -// } -// } else { -// //this will find all overridden methods, but may generate false positives in some cases: -// for (int i= 0; i < parameters.length; i++) { -// if (!equals(methodParameters[i].getErasure(), parameters[i].getErasure())) -// return false; -// } -// } - return true; - } - - /** - * @param overriding overriding method (m1) - * @param overridden overridden method (m2) - * @return <code>true</code> iff the method <code>m1</code> is a subsignature of the method <code>m2</code>. - * This is one of the requirements for m1 to override m2. - * Accessibility and return types are not taken into account. - * Note that subsignature is <em>not</em> symmetric! - */ - public static boolean isSubsignature(IMethodBinding overriding, IMethodBinding overridden) { - //TODO: use IMethodBinding#isSubsignature(..) once it is tested and fixed (only erasure of m1's parameter types, considering type variable counts, doing type variable substitution - if (!overriding.getName().equals(overridden.getName())) - return false; - - ITypeBinding[] m1Params= overriding.getParameterTypes(); - ITypeBinding[] m2Params= overridden.getParameterTypes(); - if (m1Params.length != m2Params.length) - return false; - - ITypeBinding[] m1TypeParams= overriding.getTypeParameters(); - ITypeBinding[] m2TypeParams= overridden.getTypeParameters(); - if (m1TypeParams.length != m2TypeParams.length - && m1TypeParams.length != 0) //non-generic m1 can override a generic m2 - return false; - - //m1TypeParameters.length == (m2TypeParameters.length || 0) - if (m2TypeParams.length != 0) { - //Note: this branch does not 100% adhere to the spec and may report some false positives. - // Full compliance would require major duplication of compiler code. - - //Compare type parameter bounds: - for (int i= 0; i < m1TypeParams.length; i++) { - // loop over m1TypeParams, which is either empty, or equally long as m2TypeParams - Set<ITypeBinding> m1Bounds= getTypeBoundsForSubsignature(m1TypeParams[i]); - Set<ITypeBinding> m2Bounds= getTypeBoundsForSubsignature(m2TypeParams[i]); - if (! m1Bounds.equals(m2Bounds)) - return false; - } - //Compare parameter types: - if (equals(m2Params, m1Params)) - return true; - for (int i= 0; i < m1Params.length; i++) { - ITypeBinding m1Param= m1Params[i]; - ITypeBinding m2Param= m2Params[i]; - if (containsTypeVariables(m1Param) || m1Param.isRawType()) - m1Param= m1Param.getErasure(); // try to achieve effect of "rename type variables" - if (! (equals(m1Param, m2Param) || equals(m1Param, m2Param.getErasure()))) - return false; - } - return true; - - } else { - // m1TypeParams.length == m2TypeParams.length == 0 - if (equals(m1Params, m2Params)) - return true; - for (int i= 0; i < m1Params.length; i++) { - ITypeBinding m1Param= m1Params[i]; - ITypeBinding m2Param= m2Params[i]; - if (m1Param.isRawType()) - m1Param= m1Param.getTypeDeclaration(); - if (! (equals(m1Param, m2Param) || equals(m1Param, m2Param.getErasure()))) - return false; - } - return true; - } - } - - static boolean containsTypeVariables(ITypeBinding type) { - if (type.isTypeVariable()) - return true; - if (type.isArray()) - return containsTypeVariables(type.getElementType()); - if (type.isCapture()) - return containsTypeVariables(type.getWildcard()); - if (type.isParameterizedType()) - return containsTypeVariables(type.getTypeArguments()); - if (type.isWildcardType() && type.getBound() != null) - return containsTypeVariables(type.getBound()); - return false; - } - - private static boolean containsTypeVariables(ITypeBinding[] types) { - for (int i= 0; i < types.length; i++) - if (containsTypeVariables(types[i])) - return true; - return false; - } - - private static Set<ITypeBinding> getTypeBoundsForSubsignature(ITypeBinding typeParameter) { - ITypeBinding[] typeBounds= typeParameter.getTypeBounds(); - int count= typeBounds.length; - if (count == 0) - return Collections.emptySet(); - - Set<ITypeBinding> result= new HashSet<>(typeBounds.length); - for (int i= 0; i < typeBounds.length; i++) { - ITypeBinding bound= typeBounds[i]; - if ("java.lang.Object".equals(typeBounds[0].getQualifiedName())) //$NON-NLS-1$ - continue; - else if (containsTypeVariables(bound)) - result.add(bound.getErasure()); // try to achieve effect of "rename type variables" - else if (bound.isRawType()) - result.add(bound.getTypeDeclaration()); - else - result.add(bound); - } - return result; - } - - /** - * Checks whether a method with the given name and parameter types - * is a subsignature of the given method binding. - * - * @param method a method - * @param methodName method name to match - * @param parameters the parameter types of the method to find. If <code>null</code> is passed, only the name is matched and parameters are ignored. - * @return <code>true</code> iff the method - * m1 (with name <code>methodName</code> and method parameters <code>parameters</code>) - * is a subsignature of the method <code>m2</code>. Accessibility and return types are not taken into account. - */ - public static boolean isEqualMethod(IMethodBinding method, String methodName, String[] parameters) { - if (!method.getName().equals(methodName)) - return false; - - ITypeBinding[] methodParameters= method.getParameterTypes(); - if (methodParameters.length != parameters.length) - return false; - String first, second; - int index; - for (int i= 0; i < parameters.length; i++) { - first= parameters[i]; - index= first.indexOf('<'); - if (index > 0){ - int lastIndex= first.lastIndexOf('>'); - StringBuffer buf= new StringBuffer(); - buf.append(first.substring(0, index)); - if (lastIndex < first.length() - 1) - buf.append(first.substring(lastIndex + 1, first.length())); - first= buf.toString(); - } - second= methodParameters[i].getQualifiedName(); - if (!first.equals(second)) { - second= methodParameters[i].getErasure().getQualifiedName(); - if (!first.equals(second)) - return false; - } - } - return true; - } - - /** - * Finds a type binding for a given fully qualified type in the hierarchy of a type. - * Returns <code>null</code> if no type binding is found. - * @param hierarchyType the binding representing the hierarchy - * @param fullyQualifiedTypeName the fully qualified name to search for - * @return the type binding - */ - public static ITypeBinding findTypeInHierarchy(ITypeBinding hierarchyType, String fullyQualifiedTypeName) { - if (hierarchyType.isArray() || hierarchyType.isPrimitive()) { - return null; - } - if (fullyQualifiedTypeName.equals(hierarchyType.getTypeDeclaration().getQualifiedName())) { - return hierarchyType; - } - ITypeBinding superClass= hierarchyType.getSuperclass(); - if (superClass != null) { - ITypeBinding res= findTypeInHierarchy(superClass, fullyQualifiedTypeName); - if (res != null) { - return res; - } - } - ITypeBinding[] superInterfaces= hierarchyType.getInterfaces(); - for (int i= 0; i < superInterfaces.length; i++) { - ITypeBinding res= findTypeInHierarchy(superInterfaces[i], fullyQualifiedTypeName); - if (res != null) { - return res; - } - } - return null; - } - - /** - * Searches for a type binding for a given fully qualified type in the hierarchy of a type. - * Returns the immediate super type in whose supertype hierarchy the given type appears, or <code>null</code> if no type binding is found. - * @param hierarchyType the binding representing the hierarchy - * @param fullyQualifiedTypeName the fully qualified name to search for - * @return the type binding - */ - public static ITypeBinding findImmediateSuperTypeInHierarchy(ITypeBinding hierarchyType, String fullyQualifiedTypeName) { - if (hierarchyType.isArray() || hierarchyType.isPrimitive()) { - return null; - } - ITypeBinding superClass= hierarchyType.getSuperclass(); - if (superClass != null) { - ITypeBinding res= findTypeInHierarchy(superClass, fullyQualifiedTypeName); - if (res != null) { - return superClass; - } - } - ITypeBinding[] superInterfaces= hierarchyType.getInterfaces(); - for (int i= 0; i < superInterfaces.length; i++) { - ITypeBinding res= findTypeInHierarchy(superInterfaces[i], fullyQualifiedTypeName); - if (res != null) { - return superInterfaces[i]; - } - } - return null; - } - - /** - * Returns the binding of the variable written in an Assignment. - * @param assignment The assignment - * @return The binding or <code>null</code> if no bindings are available. - */ - public static IVariableBinding getAssignedVariable(Assignment assignment) { - Expression leftHand = assignment.getLeftHandSide(); - switch (leftHand.getNodeType()) { - case ASTNode.SIMPLE_NAME: - return (IVariableBinding) ((SimpleName) leftHand).resolveBinding(); - case ASTNode.QUALIFIED_NAME: - return (IVariableBinding) ((QualifiedName) leftHand).getName().resolveBinding(); - case ASTNode.FIELD_ACCESS: - return ((FieldAccess) leftHand).resolveFieldBinding(); - case ASTNode.SUPER_FIELD_ACCESS: - return ((SuperFieldAccess) leftHand).resolveFieldBinding(); - default: - return null; - } - } - - /** - * Returns <code>true</code> if the given type is a super type of a candidate. - * <code>true</code> is returned if the two type bindings are identical. - * - * <p><b>Warning:</b> With the addition of generics, this method is valid in less - * cases than before. Consider using {@link TypeRules#canAssign(ITypeBinding, ITypeBinding)} - * if you're dealing with types of variables. The classical notion of supertypes - * only makes sense if you really need to walk the type hierarchy but don't need to play - * the assignment rules.</p> - * - * @param possibleSuperType the type to inspect - * @param type the type whose super types are looked at - * @return <code>true</code> iff <code>possibleSuperType</code> is - * a super type of <code>type</code> or is equal to it - */ - public static boolean isSuperType(ITypeBinding possibleSuperType, ITypeBinding type) { - return isSuperType(possibleSuperType, type, true); - } - - /** - * Returns <code>true</code> if the given type is a super type of a candidate. - * <code>true</code> is returned if the two type bindings are identical (TODO) - * @param possibleSuperType the type to inspect - * @param type the type whose super types are looked at - * @param considerTypeArguments if <code>true</code>, consider type arguments of <code>type</code> - * @return <code>true</code> iff <code>possibleSuperType</code> is - * a super type of <code>type</code> or is equal to it - */ - public static boolean isSuperType(ITypeBinding possibleSuperType, ITypeBinding type, boolean considerTypeArguments) { - if (type.isArray() || type.isPrimitive()) { - return false; - } - if (! considerTypeArguments) { - type= type.getTypeDeclaration(); - } - if (Bindings.equals(type, possibleSuperType)) { - return true; - } - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - if (isSuperType(possibleSuperType, superClass, considerTypeArguments)) { - return true; - } - } - - if (possibleSuperType.isInterface()) { - ITypeBinding[] superInterfaces= type.getInterfaces(); - for (int i= 0; i < superInterfaces.length; i++) { - if (isSuperType(possibleSuperType, superInterfaces[i], considerTypeArguments)) { - return true; - } - } - } - return false; - } - - /** - * Finds the compilation unit where the type of the given <code>ITypeBinding</code> is defined, - * using the class path defined by the given Java project. Returns <code>null</code> - * if no compilation unit is found (e.g. type binding is from a binary type) - * @param typeBinding the type binding to search for - * @param project the project used as a scope - * @return the compilation unit containing the type - * @throws JavaModelException if an errors occurs in the Java model - */ - public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException { - IJavaElement type= typeBinding.getJavaElement(); - if (type instanceof IType) - return ((IType) type).getCompilationUnit(); - else - return null; - } - - /** - * Finds a method for the given <code>IMethodBinding</code>. Returns - * <code>null</code> if the type doesn't contain a corresponding method. - * @param method the method to find - * @param type the type to look in - * @return the corresponding IMethod or <code>null</code> - * @throws JavaModelException if an error occurs in the Java model - * @deprecated Use {@link #findMethodInHierarchy(ITypeBinding, String, String[])} or {@link JavaModelUtil} - */ - @Deprecated - public static IMethod findMethod(IMethodBinding method, IType type) throws JavaModelException { - method= method.getMethodDeclaration(); - - IMethod[] candidates= type.getMethods(); - for (int i= 0; i < candidates.length; i++) { - IMethod candidate= candidates[i]; - if (candidate.getElementName().equals(method.getName()) && sameParameters(method, candidate)) { - return candidate; - } - } - return null; - } - - //---- Helper methods to convert a method --------------------------------------------- - - private static boolean sameParameters(IMethodBinding method, IMethod candidate) throws JavaModelException { - ITypeBinding[] methodParamters= method.getParameterTypes(); - String[] candidateParameters= candidate.getParameterTypes(); - if (methodParamters.length != candidateParameters.length) - return false; - IType scope= candidate.getDeclaringType(); - for (int i= 0; i < methodParamters.length; i++) { - ITypeBinding methodParameter= methodParamters[i]; - String candidateParameter= candidateParameters[i]; - if (!sameParameter(methodParameter, candidateParameter, scope)) - return false; - } - return true; - } - - private static boolean sameParameter(ITypeBinding type, String candidate, IType scope) throws JavaModelException { - if (type.getDimensions() != Signature.getArrayCount(candidate)) - return false; - - // Normalizes types - if (type.isArray()) - type= type.getElementType(); - candidate= Signature.getElementType(candidate); - - if ((Signature.getTypeSignatureKind(candidate) == Signature.BASE_TYPE_SIGNATURE) != type.isPrimitive()) { - return false; - } - - if (type.isPrimitive() || type.isTypeVariable()) { - return type.getName().equals(Signature.toString(candidate)); - } else { - // normalize (quick hack until binding.getJavaElement works) - candidate= Signature.getTypeErasure(candidate); - type= type.getErasure(); - - if (candidate.charAt(Signature.getArrayCount(candidate)) == Signature.C_RESOLVED) { - return Signature.toString(candidate).equals(Bindings.getFullyQualifiedName(type)); - } else { - String[][] qualifiedCandidates= scope.resolveType(Signature.toString(candidate)); - if (qualifiedCandidates == null || qualifiedCandidates.length == 0) - return false; - String packageName= type.getPackage().isUnnamed() ? "" : type.getPackage().getName(); //$NON-NLS-1$ - String typeName= getTypeQualifiedName(type); - for (int i= 0; i < qualifiedCandidates.length; i++) { - String[] qualifiedCandidate= qualifiedCandidates[i]; - if ( qualifiedCandidate[0].equals(packageName) && - qualifiedCandidate[1].equals(typeName)) - return true; - } - } - } - return false; - } - - /** - * Normalizes a type binding received from an expression to a type binding that can be used inside a - * declaration signature, but <em>not</em> as type of a declaration (use {@link #normalizeForDeclarationUse(ITypeBinding, AST)} for that). - * <p> - * Anonymous types are normalized to the super class or interface. For - * null or void bindings, <code>null</code> is returned. - * </p> - * - * @param binding the binding to normalize - * @return the normalized binding, can be <code>null</code> - * - * @see #normalizeForDeclarationUse(ITypeBinding, AST) - */ - public static ITypeBinding normalizeTypeBinding(ITypeBinding binding) { - if (binding != null && !binding.isNullType() && !isVoidType(binding)) { - if (binding.isAnonymous()) { - ITypeBinding[] baseBindings= binding.getInterfaces(); - if (baseBindings.length > 0) { - return baseBindings[0]; - } - return binding.getSuperclass(); - } - if (binding.isCapture()) { - return binding.getWildcard(); - } - return binding; - } - return null; - } - - public static boolean isVoidType(ITypeBinding binding) { - return "void".equals(binding.getName()); //$NON-NLS-1$ - } - - /** - * Normalizes the binding so that it can be used as a type inside a declaration (e.g. variable - * declaration, method return type, parameter type, ...). - * For null bindings, java.lang.Object is returned. - * For void bindings, <code>null</code> is returned. - * - * @param binding binding to normalize - * @param ast current AST - * @return the normalized type to be used in declarations, or <code>null</code> - */ - public static ITypeBinding normalizeForDeclarationUse(ITypeBinding binding, AST ast) { - if (binding.isNullType()) - return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ - if (binding.isPrimitive()) - return binding; - binding= normalizeTypeBinding(binding); - if (binding == null) - return binding; - if (binding.isArray()) - return normalizeForDeclarationUse(binding.getComponentType(), ast).createArrayType(1); - if (!binding.isWildcardType()) - return binding; - ITypeBinding bound= binding.getBound(); - if (bound == null || !binding.isUpperbound()) { - ITypeBinding[] typeBounds= binding.getTypeBounds(); - if (typeBounds.length > 0) { - return typeBounds[0]; - } else { - return binding.getErasure(); - } - } else { - return bound; - } - } - - /** - * Returns the type binding of the node's enclosing type declaration. - * - * @param node an AST node - * @return the type binding of the node's parent type declaration, or <code>null</code> - */ - public static ITypeBinding getBindingOfParentType(ASTNode node) { - while (node != null) { - if (node instanceof AbstractTypeDeclaration) { - return ((AbstractTypeDeclaration) node).resolveBinding(); - } else if (node instanceof AnonymousClassDeclaration) { - return ((AnonymousClassDeclaration) node).resolveBinding(); - } - node= node.getParent(); - } - return null; - } - - /** - * Returns the type binding of the node's type context or null if the node is inside - * an annotation, type parameter, super type declaration, or Javadoc of a top level type. - * The result of this method is equal to the result of {@link #getBindingOfParentType(ASTNode)} for nodes in the type's body. - * - * @param node an AST node - * @return the type binding of the node's parent type context, or <code>null</code> - */ - public static ITypeBinding getBindingOfParentTypeContext(ASTNode node) { - StructuralPropertyDescriptor lastLocation= null; - - while (node != null) { - if (node instanceof AbstractTypeDeclaration) { - AbstractTypeDeclaration decl= (AbstractTypeDeclaration) node; - if (lastLocation == decl.getBodyDeclarationsProperty() - || lastLocation == decl.getJavadocProperty()) { - return decl.resolveBinding(); - } else if (decl instanceof EnumDeclaration && lastLocation == EnumDeclaration.ENUM_CONSTANTS_PROPERTY) { - return decl.resolveBinding(); - } - } else if (node instanceof AnonymousClassDeclaration) { - return ((AnonymousClassDeclaration) node).resolveBinding(); - } - lastLocation= node.getLocationInParent(); - node= node.getParent(); - } - return null; - } - - - public static String getRawName(ITypeBinding binding) { - String name= binding.getName(); - if (binding.isParameterizedType() || binding.isGenericType()) { - int idx= name.indexOf('<'); - if (idx != -1) { - return name.substring(0, idx); - } - } - return name; - } - - - public static String getRawQualifiedName(ITypeBinding binding) { - final String EMPTY= ""; //$NON-NLS-1$ - - if (binding.isAnonymous() || binding.isLocal()) { - return EMPTY; - } - - if (binding.isPrimitive() || binding.isNullType() || binding.isTypeVariable()) { - return binding.getName(); - } - - if (binding.isArray()) { - String elementTypeQualifiedName = getRawQualifiedName(binding.getElementType()); - if (elementTypeQualifiedName.length() != 0) { - StringBuffer stringBuffer= new StringBuffer(elementTypeQualifiedName); - stringBuffer.append('[').append(']'); - return stringBuffer.toString(); - } else { - return EMPTY; - } - } - if (binding.isMember()) { - String outerName= getRawQualifiedName(binding.getDeclaringClass()); - if (outerName.length() > 0) { - StringBuffer buffer= new StringBuffer(); - buffer.append(outerName); - buffer.append('.'); - buffer.append(getRawName(binding)); - return buffer.toString(); - } else { - return EMPTY; - } - - } else if (binding.isTopLevel()) { - IPackageBinding packageBinding= binding.getPackage(); - StringBuffer buffer= new StringBuffer(); - if (packageBinding != null && packageBinding.getName().length() > 0) { - buffer.append(packageBinding.getName()).append('.'); - } - buffer.append(getRawName(binding)); - return buffer.toString(); - } - return EMPTY; - } - - - /** - * Tests if the given node is a declaration, not a instance of a generic type, method or field. - * Declarations can be found in AST with CompilationUnit.findDeclaringNode - * @param binding binding to test - * @return returns <code>true</code> if the binding is a declaration binding - */ - public static boolean isDeclarationBinding(IBinding binding) { - switch (binding.getKind()) { - case IBinding.TYPE: - return ((ITypeBinding) binding).getTypeDeclaration() == binding; - case IBinding.VARIABLE: - return ((IVariableBinding) binding).getVariableDeclaration() == binding; - case IBinding.METHOD: - return ((IMethodBinding) binding).getMethodDeclaration() == binding; - } - return true; - } - - - public static IBinding getDeclaration(IBinding binding) { - switch (binding.getKind()) { - case IBinding.TYPE: - return ((ITypeBinding) binding).getTypeDeclaration(); - case IBinding.VARIABLE: - return ((IVariableBinding) binding).getVariableDeclaration(); - case IBinding.METHOD: - return ((IMethodBinding) binding).getMethodDeclaration(); - } - return binding; - } - - - /** - * @param candidates the candidates - * @param overridable the overriding method - * @return returns <code>true></code> if the overriding method overrides a candidate - * @deprecated Need to review: Use {@link #isSubsignature(IMethodBinding, IMethodBinding)} if the two bindings - * are in the same hierarchy (directly overrides each other), or {@link #findMethodInHierarchy(ITypeBinding, String, ITypeBinding[])} - * else. - */ - @Deprecated - public static boolean containsSignatureEquivalentConstructor(IMethodBinding[] candidates, IMethodBinding overridable) { - for (int index= 0; index < candidates.length; index++) { - if (isSignatureEquivalentConstructor(candidates[index], overridable)) - return true; - } - return false; - } - - private static boolean isSignatureEquivalentConstructor(IMethodBinding overridden, IMethodBinding overridable) { - - if (!overridden.isConstructor() || !overridable.isConstructor()) - return false; - - if (overridden.isDefaultConstructor()) - return false; - - return areSubTypeCompatible(overridden, overridable); - } - - /** - * @param overridden the overridden method - * @param overridable the overriding method - * @return returns <code>true</code> if the overriding method overrrides the overridden - * @deprecated Need to review: Use {@link #isSubsignature(IMethodBinding, IMethodBinding)} if the two bindings - * are in the same hierarchy (directly overrides each other), or {@link #findMethodInHierarchy(ITypeBinding, String, ITypeBinding[])} - * else. - */ - @Deprecated - public static boolean areOverriddenMethods(IMethodBinding overridden, IMethodBinding overridable) { - - if (!overridden.getName().equals(overridable.getName())) - return false; - - return areSubTypeCompatible(overridden, overridable); - } - - private static boolean areSubTypeCompatible(IMethodBinding overridden, IMethodBinding overridable) { - - if (overridden.getParameterTypes().length != overridable.getParameterTypes().length) - return false; - - ITypeBinding overriddenReturn= overridden.getReturnType(); - ITypeBinding overridableReturn= overridable.getReturnType(); - if (overriddenReturn == null || overridableReturn == null) - return false; - - if (!overriddenReturn.getErasure().isSubTypeCompatible(overridableReturn.getErasure())) - return false; - - ITypeBinding[] overriddenTypes= overridden.getParameterTypes(); - ITypeBinding[] overridableTypes= overridable.getParameterTypes(); - Assert.isTrue(overriddenTypes.length == overridableTypes.length); - for (int index= 0; index < overriddenTypes.length; index++) { - final ITypeBinding overridableErasure= overridableTypes[index].getErasure(); - final ITypeBinding overriddenErasure= overriddenTypes[index].getErasure(); - if (!overridableErasure.isSubTypeCompatible(overriddenErasure) || !overridableErasure.getKey().equals(overriddenErasure.getKey())) - return false; - } - ITypeBinding[] overriddenExceptions= overridden.getExceptionTypes(); - ITypeBinding[] overridableExceptions= overridable.getExceptionTypes(); - boolean checked= false; - for (int index= 0; index < overriddenExceptions.length; index++) { - checked= false; - for (int offset= 0; offset < overridableExceptions.length; offset++) { - if (overriddenExceptions[index].isSubTypeCompatible(overridableExceptions[offset])) - checked= true; - } - if (!checked) - return false; - } - return true; - } - - /** - * Returns the boxed type binding according to JLS3 5.1.7, or the original binding if - * the given type is not a primitive type. - * - * @param type a type binding - * @param ast an AST to resolve the boxed type - * @return the boxed type, or the original type if no boxed type found - */ - public static ITypeBinding getBoxedTypeBinding(ITypeBinding type, AST ast) { - if (!type.isPrimitive()) - return type; - String boxedTypeName= getBoxedTypeName(type.getName()); - if (boxedTypeName == null) - return type; - ITypeBinding boxed= ast.resolveWellKnownType(boxedTypeName); - if (boxed == null) - return type; - return boxed; - } - - private static String getBoxedTypeName(String primitiveName) { - if ("long".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Long"; //$NON-NLS-1$ - - else if ("int".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Integer"; //$NON-NLS-1$ - - else if ("short".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Short"; //$NON-NLS-1$ - - else if ("char".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Character"; //$NON-NLS-1$ - - else if ("byte".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Byte"; //$NON-NLS-1$ - - else if ("boolean".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Boolean"; //$NON-NLS-1$ - - else if ("float".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Float"; //$NON-NLS-1$ - - else if ("double".equals(primitiveName)) //$NON-NLS-1$ - return "java.lang.Double"; //$NON-NLS-1$ - - else - return null; - } - - /** - * Returns the unboxed type binding according to JLS3 5.1.7, or the original binding if - * the given type is not a boxed type. - * - * @param type a type binding - * @param ast an AST to resolve the unboxed type - * @return the unboxed type, or the original type if no unboxed type found - */ - public static ITypeBinding getUnboxedTypeBinding(ITypeBinding type, AST ast) { - if (!type.isClass()) - return type; - String unboxedTypeName= getUnboxedTypeName(type.getQualifiedName()); - if (unboxedTypeName == null) - return type; - ITypeBinding unboxed= ast.resolveWellKnownType(unboxedTypeName); - if (unboxed == null) - return type; - return unboxed; - } - - private static String getUnboxedTypeName(String boxedName) { - if ("java.lang.Long".equals(boxedName)) //$NON-NLS-1$ - return "long"; //$NON-NLS-1$ - - else if ("java.lang.Integer".equals(boxedName)) //$NON-NLS-1$ - return "int"; //$NON-NLS-1$ - - else if ("java.lang.Short".equals(boxedName)) //$NON-NLS-1$ - return "short"; //$NON-NLS-1$ - - else if ("java.lang.Character".equals(boxedName)) //$NON-NLS-1$ - return "char"; //$NON-NLS-1$ - - else if ("java.lang.Byte".equals(boxedName)) //$NON-NLS-1$ - return "byte"; //$NON-NLS-1$ - - else if ("java.lang.Boolean".equals(boxedName)) //$NON-NLS-1$ - return "boolean"; //$NON-NLS-1$ - - else if ("java.lang.Float".equals(boxedName)) //$NON-NLS-1$ - return "float"; //$NON-NLS-1$ - - else if ("java.lang.Double".equals(boxedName)) //$NON-NLS-1$ - return "double"; //$NON-NLS-1$ - - else - return null; - } - - /** - * Resolve the binding (<em>not</em> the type binding) for the expression or a nested expression - * (e.g. nested in parentheses, cast, ...). - * - * @param expression an expression node - * @param goIntoCast iff <code>true</code>, go into a CastExpression's expression to resolve - * @return the expression binding, or <code>null</code> if the expression has no binding or the - * binding could not be resolved - * - * @see StubUtility#getVariableNameSuggestions(int, IJavaProject, ITypeBinding, Expression, java.util.Collection) - * @since 3.5 - */ - public static IBinding resolveExpressionBinding(Expression expression, boolean goIntoCast) { - //TODO: search for callers of resolve*Binding() methods and replace with call to this method - - // similar to StubUtility#getVariableNameSuggestions(int, IJavaProject, ITypeBinding, Expression, Collection) - switch (expression.getNodeType()) { - case ASTNode.SIMPLE_NAME: - case ASTNode.QUALIFIED_NAME: - return ((Name) expression).resolveBinding(); - - case ASTNode.FIELD_ACCESS: - return ((FieldAccess) expression).resolveFieldBinding(); - case ASTNode.SUPER_FIELD_ACCESS: - return ((SuperFieldAccess) expression).resolveFieldBinding(); - - case ASTNode.METHOD_INVOCATION: - return ((MethodInvocation) expression).resolveMethodBinding(); - case ASTNode.SUPER_METHOD_INVOCATION: - return ((SuperMethodInvocation) expression).resolveMethodBinding(); - case ASTNode.CLASS_INSTANCE_CREATION: - return ((ClassInstanceCreation) expression).resolveConstructorBinding(); - - case ASTNode.MARKER_ANNOTATION: - case ASTNode.SINGLE_MEMBER_ANNOTATION: - case ASTNode.NORMAL_ANNOTATION: - return ((Annotation) expression).resolveAnnotationBinding(); - - case ASTNode.ARRAY_ACCESS: - return resolveExpressionBinding(((ArrayAccess) expression).getArray(), goIntoCast); - case ASTNode.CAST_EXPRESSION: - if (goIntoCast) { - return resolveExpressionBinding(((CastExpression) expression).getExpression(), true); - } else { - return null; - } - case ASTNode.PARENTHESIZED_EXPRESSION: - return resolveExpressionBinding(((ParenthesizedExpression) expression).getExpression(), goIntoCast); - case ASTNode.PREFIX_EXPRESSION: - return resolveExpressionBinding(((PrefixExpression) expression).getOperand(), goIntoCast); - case ASTNode.POSTFIX_EXPRESSION: - return resolveExpressionBinding(((PostfixExpression) expression).getOperand(), goIntoCast); - default: - return null; - } - } - - public static boolean isNonNullAnnotation(ITypeBinding annotationType, IJavaProject project) { - String qualifiedName= annotationType.getQualifiedName(); - return qualifiedName.equals(project.getOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, true)); - } - - public static boolean isAnyNullAnnotation(ITypeBinding annotationType, IJavaProject project) { - String qualifiedName= annotationType.getQualifiedName(); - return qualifiedName.equals(project.getOption(JavaCore.COMPILER_NONNULL_ANNOTATION_NAME, true)) - || qualifiedName.equals(project.getOption(JavaCore.COMPILER_NULLABLE_ANNOTATION_NAME, true)); - } - - /** - * Answer the annotation binding representing a nullness default - * effective at the point denoted by 'contextBinding'. - * @param contextBinding method binding or type binding denoting the location of interest - * @param javaProject the containing java project, consulted for the actual name of - * the annotation used for nullness defaults (default: <code>@NonNullByDefault</code>). - * @return binding for the effective nullness default annotation - * or null if no nullness default is effective at the context location. - */ - public static IAnnotationBinding findNullnessDefault(IBinding contextBinding, IJavaProject javaProject) { - if (JavaCore.ENABLED.equals(javaProject.getOption(JavaCore.COMPILER_ANNOTATION_NULL_ANALYSIS, true))) { - String annotationName= javaProject.getOption(JavaCore.COMPILER_NONNULL_BY_DEFAULT_ANNOTATION_NAME, true); - while (contextBinding != null) { - for (IAnnotationBinding annotation : contextBinding.getAnnotations()) { - ITypeBinding annotationType= annotation.getAnnotationType(); - if (annotationType != null && annotationType.getQualifiedName().equals(annotationName)) - return annotation; - } - // travel out: - switch (contextBinding.getKind()) { - case IBinding.METHOD: - IMethodBinding methodBinding= (IMethodBinding) contextBinding; - contextBinding= methodBinding.getDeclaringMember(); - if (contextBinding == null) - contextBinding= methodBinding.getDeclaringClass(); - break; - case IBinding.VARIABLE: - IVariableBinding variableBinding= (IVariableBinding) contextBinding; - contextBinding= variableBinding.getDeclaringMethod(); - if (contextBinding == null) - contextBinding= variableBinding.getDeclaringClass(); - break; - case IBinding.TYPE: - ITypeBinding currentClass= (ITypeBinding) contextBinding; - contextBinding= currentClass.getDeclaringMember(); - if (contextBinding == null) { - contextBinding= currentClass.getDeclaringMethod(); - if (contextBinding == null) { - contextBinding= currentClass.getDeclaringClass(); - if (contextBinding == null) - contextBinding= currentClass.getPackage(); - } - } - break; - default: - contextBinding= null; - break; - } - } - } - return null; - } - - /** - * Returns the n-th component type of the given type, or <code>null</code> if - * the type binding is not an array type or has not that many dimensions. - * - * @param arrayType an array type binding - * @param n number of dimensions to cut - * @return arrayType with n dimensions removed, or <code>null</code> - * @since 3.10 - */ - public static ITypeBinding getComponentType(ITypeBinding arrayType, int n) { - ITypeBinding type= arrayType; - while (n > 0 && type != null) { - type= type.getComponentType(); - n--; - } - return type; - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/BodyDeclarationRewrite.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/BodyDeclarationRewrite.java index 12dc84f83a..c7a63058f7 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/BodyDeclarationRewrite.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/BodyDeclarationRewrite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -17,11 +17,15 @@ import org.eclipse.text.edits.TextEditGroup; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; +import org.eclipse.jdt.core.dom.MethodDeclaration; +import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; +import org.eclipse.jdt.internal.ui.JavaPlugin; +import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache; /** * Rewrite helper for body declarations. @@ -46,7 +50,84 @@ public class BodyDeclarationRewrite { public void insert(BodyDeclaration decl, TextEditGroup description) { List<BodyDeclaration> container= ASTNodes.getBodyDeclarations(fTypeNode); - int index= ASTNodes.getInsertionIndex(decl, container); + int index= getInsertionIndex(decl, container); fListRewrite.insertAt(decl, index, description); } + + /** + * Computes the insertion index to be used to add the given member to the + * the list <code>container</code>. + * @param member the member to add + * @param container a list containing objects of type <code>BodyDeclaration</code> + * @return the insertion index to be used + */ + public static int getInsertionIndex(BodyDeclaration member, List<? extends BodyDeclaration> container) { + int containerSize= container.size(); + + MembersOrderPreferenceCache orderStore= JavaPlugin.getDefault().getMemberOrderPreferenceCache(); + + int orderIndex= getOrderPreference(member, orderStore); + + int insertPos= containerSize; + int insertPosOrderIndex= -1; + + for (int i= containerSize - 1; i >= 0; i--) { + int currOrderIndex= getOrderPreference(container.get(i), orderStore); + if (orderIndex == currOrderIndex) { + if (insertPosOrderIndex != orderIndex) { // no perfect match yet + insertPos= i + 1; // after a same kind + insertPosOrderIndex= orderIndex; // perfect match + } + } else if (insertPosOrderIndex != orderIndex) { // not yet a perfect match + if (currOrderIndex < orderIndex) { // we are bigger + if (insertPosOrderIndex == -1) { + insertPos= i + 1; // after + insertPosOrderIndex= currOrderIndex; + } + } else { + insertPos= i; // before + insertPosOrderIndex= currOrderIndex; + } + } + } + return insertPos; + } + + private static int getOrderPreference(BodyDeclaration member, MembersOrderPreferenceCache store) { + int memberType= member.getNodeType(); + int modifiers= member.getModifiers(); + + switch (memberType) { + case ASTNode.TYPE_DECLARATION: + case ASTNode.ENUM_DECLARATION : + case ASTNode.ANNOTATION_TYPE_DECLARATION : + return store.getCategoryIndex(MembersOrderPreferenceCache.TYPE_INDEX) * 2; + case ASTNode.FIELD_DECLARATION: + if (Modifier.isStatic(modifiers)) { + int index= store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX) * 2; + if (Modifier.isFinal(modifiers)) { + return index; // first final static, then static + } + return index + 1; + } + return store.getCategoryIndex(MembersOrderPreferenceCache.FIELDS_INDEX) * 2; + case ASTNode.INITIALIZER: + if (Modifier.isStatic(modifiers)) { + return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_INIT_INDEX) * 2; + } + return store.getCategoryIndex(MembersOrderPreferenceCache.INIT_INDEX) * 2; + case ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION: + return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; + case ASTNode.METHOD_DECLARATION: + if (Modifier.isStatic(modifiers)) { + return store.getCategoryIndex(MembersOrderPreferenceCache.STATIC_METHODS_INDEX) * 2; + } + if (((MethodDeclaration) member).isConstructor()) { + return store.getCategoryIndex(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX) * 2; + } + return store.getCategoryIndex(MembersOrderPreferenceCache.METHOD_INDEX) * 2; + default: + return 100; + } + } } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java deleted file mode 100644 index dd3d032d4e..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/GenericVisitor.java +++ /dev/null @@ -1,901 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTVisitor; -import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; -import org.eclipse.jdt.core.dom.AnnotationTypeMemberDeclaration; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.ArrayAccess; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ArrayType; -import org.eclipse.jdt.core.dom.AssertStatement; -import org.eclipse.jdt.core.dom.Assignment; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BlockComment; -import org.eclipse.jdt.core.dom.BooleanLiteral; -import org.eclipse.jdt.core.dom.BreakStatement; -import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CatchClause; -import org.eclipse.jdt.core.dom.CharacterLiteral; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.ConditionalExpression; -import org.eclipse.jdt.core.dom.ConstructorInvocation; -import org.eclipse.jdt.core.dom.ContinueStatement; -import org.eclipse.jdt.core.dom.CreationReference; -import org.eclipse.jdt.core.dom.Dimension; -import org.eclipse.jdt.core.dom.DoStatement; -import org.eclipse.jdt.core.dom.EmptyStatement; -import org.eclipse.jdt.core.dom.EnhancedForStatement; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.ExpressionMethodReference; -import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IfStatement; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.InfixExpression; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.InstanceofExpression; -import org.eclipse.jdt.core.dom.IntersectionType; -import org.eclipse.jdt.core.dom.Javadoc; -import org.eclipse.jdt.core.dom.LabeledStatement; -import org.eclipse.jdt.core.dom.LambdaExpression; -import org.eclipse.jdt.core.dom.LineComment; -import org.eclipse.jdt.core.dom.MarkerAnnotation; -import org.eclipse.jdt.core.dom.MemberRef; -import org.eclipse.jdt.core.dom.MemberValuePair; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.MethodRef; -import org.eclipse.jdt.core.dom.MethodRefParameter; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.NameQualifiedType; -import org.eclipse.jdt.core.dom.NormalAnnotation; -import org.eclipse.jdt.core.dom.NullLiteral; -import org.eclipse.jdt.core.dom.NumberLiteral; -import org.eclipse.jdt.core.dom.PackageDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; -import org.eclipse.jdt.core.dom.ParenthesizedExpression; -import org.eclipse.jdt.core.dom.PostfixExpression; -import org.eclipse.jdt.core.dom.PrefixExpression; -import org.eclipse.jdt.core.dom.PrimitiveType; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.QualifiedType; -import org.eclipse.jdt.core.dom.ReturnStatement; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.SimpleType; -import org.eclipse.jdt.core.dom.SingleMemberAnnotation; -import org.eclipse.jdt.core.dom.SingleVariableDeclaration; -import org.eclipse.jdt.core.dom.StringLiteral; -import org.eclipse.jdt.core.dom.SuperConstructorInvocation; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SuperMethodReference; -import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.SynchronizedStatement; -import org.eclipse.jdt.core.dom.TagElement; -import org.eclipse.jdt.core.dom.TextElement; -import org.eclipse.jdt.core.dom.ThisExpression; -import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.TryStatement; -import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.TypeDeclarationStatement; -import org.eclipse.jdt.core.dom.TypeLiteral; -import org.eclipse.jdt.core.dom.TypeMethodReference; -import org.eclipse.jdt.core.dom.TypeParameter; -import org.eclipse.jdt.core.dom.UnionType; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationFragment; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; -import org.eclipse.jdt.core.dom.WhileStatement; -import org.eclipse.jdt.core.dom.WildcardType; - -import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; - -/** - * ASTVisitor that forwards all <code>visit(*)</code> calls to {@link #visitNode(ASTNode)}. - * <p> - * Note: New code should better use {@link ASTVisitor#preVisit2(ASTNode)}. - * </p> - * - * @see JDTUIHelperClasses - */ -public class GenericVisitor extends ASTVisitor { - - public GenericVisitor() { - super(); - } - - /** - * @param visitJavadocTags <code>true</code> if doc comment tags are - * to be visited by default, and <code>false</code> otherwise - * @see Javadoc#tags() - * @see #visit(Javadoc) - * @since 3.0 - */ - public GenericVisitor(boolean visitJavadocTags) { - super(visitJavadocTags); - } - - //---- Hooks for subclasses ------------------------------------------------- - - /** - * Visits the given type-specific AST node. - * - * @param node the AST note to visit - * @return <code>true</code> if the children of this node should be visited, and - * <code>false</code> if the children of this node should be skipped - */ - protected boolean visitNode(ASTNode node) { - return true; - } - - /** - * Visits the given type-specific AST node. - * - * @param node the AST note to visit - */ - protected void endVisitNode(ASTNode node) { - // do nothing - } - - @Override - public void endVisit(AnnotationTypeDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(AnnotationTypeMemberDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(AnonymousClassDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(ArrayAccess node) { - endVisitNode(node); - } - @Override - public void endVisit(ArrayCreation node) { - endVisitNode(node); - } - @Override - public void endVisit(ArrayInitializer node) { - endVisitNode(node); - } - @Override - public void endVisit(ArrayType node) { - endVisitNode(node); - } - @Override - public void endVisit(AssertStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(Assignment node) { - endVisitNode(node); - } - @Override - public void endVisit(Block node) { - endVisitNode(node); - } - @Override - public void endVisit(BlockComment node) { - endVisitNode(node); - } - @Override - public void endVisit(BooleanLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(BreakStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(CastExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(CatchClause node) { - endVisitNode(node); - } - @Override - public void endVisit(CharacterLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(ClassInstanceCreation node) { - endVisitNode(node); - } - @Override - public void endVisit(CompilationUnit node) { - endVisitNode(node); - } - @Override - public void endVisit(ConditionalExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(ConstructorInvocation node) { - endVisitNode(node); - } - @Override - public void endVisit(ContinueStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(CreationReference node) { - endVisitNode(node); - } - @Override - public void endVisit(Dimension node) { - endVisitNode(node); - } - @Override - public void endVisit(DoStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(EmptyStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(EnhancedForStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(EnumConstantDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(EnumDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(ExpressionMethodReference node) { - endVisitNode(node); - } - @Override - public void endVisit(ExpressionStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(FieldAccess node) { - endVisitNode(node); - } - @Override - public void endVisit(FieldDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(ForStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(IfStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(ImportDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(InfixExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(Initializer node) { - endVisitNode(node); - } - @Override - public void endVisit(InstanceofExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(IntersectionType node) { - endVisitNode(node); - } - @Override - public void endVisit(Javadoc node) { - endVisitNode(node); - } - @Override - public void endVisit(LabeledStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(LambdaExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(LineComment node) { - endVisitNode(node); - } - @Override - public void endVisit(MarkerAnnotation node) { - endVisitNode(node); - } - @Override - public void endVisit(MemberRef node) { - endVisitNode(node); - } - @Override - public void endVisit(MemberValuePair node) { - endVisitNode(node); - } - @Override - public void endVisit(MethodDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(MethodInvocation node) { - endVisitNode(node); - } - @Override - public void endVisit(MethodRef node) { - endVisitNode(node); - } - @Override - public void endVisit(MethodRefParameter node) { - endVisitNode(node); - } - @Override - public void endVisit(Modifier node) { - endVisitNode(node); - } - @Override - public void endVisit(NameQualifiedType node) { - endVisitNode(node); - } - - @Override - public void endVisit(NormalAnnotation node) { - endVisitNode(node); - } - @Override - public void endVisit(NullLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(NumberLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(PackageDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(ParameterizedType node) { - endVisitNode(node); - } - @Override - public void endVisit(ParenthesizedExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(PostfixExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(PrefixExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(PrimitiveType node) { - endVisitNode(node); - } - @Override - public void endVisit(QualifiedName node) { - endVisitNode(node); - } - @Override - public void endVisit(QualifiedType node) { - endVisitNode(node); - } - @Override - public void endVisit(ReturnStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(SimpleName node) { - endVisitNode(node); - } - @Override - public void endVisit(SimpleType node) { - endVisitNode(node); - } - @Override - public void endVisit(SingleMemberAnnotation node) { - endVisitNode(node); - } - @Override - public void endVisit(SingleVariableDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(StringLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(SuperConstructorInvocation node) { - endVisitNode(node); - } - @Override - public void endVisit(SuperFieldAccess node) { - endVisitNode(node); - } - @Override - public void endVisit(SuperMethodInvocation node) { - endVisitNode(node); - } - @Override - public void endVisit(SuperMethodReference node) { - endVisitNode(node); - } - @Override - public void endVisit(SwitchCase node) { - endVisitNode(node); - } - @Override - public void endVisit(SwitchStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(SynchronizedStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(TagElement node) { - endVisitNode(node); - } - @Override - public void endVisit(TextElement node) { - endVisitNode(node); - } - @Override - public void endVisit(ThisExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(ThrowStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(TryStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(TypeDeclaration node) { - endVisitNode(node); - } - @Override - public void endVisit(TypeDeclarationStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(TypeLiteral node) { - endVisitNode(node); - } - @Override - public void endVisit(TypeMethodReference node) { - endVisitNode(node); - } - @Override - public void endVisit(TypeParameter node) { - endVisitNode(node); - } - @Override - public void endVisit(UnionType node) { - endVisitNode(node); - } - @Override - public void endVisit(VariableDeclarationExpression node) { - endVisitNode(node); - } - @Override - public void endVisit(VariableDeclarationFragment node) { - endVisitNode(node); - } - @Override - public void endVisit(VariableDeclarationStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(WhileStatement node) { - endVisitNode(node); - } - @Override - public void endVisit(WildcardType node) { - endVisitNode(node); - } - - @Override - public boolean visit(AnnotationTypeDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(AnnotationTypeMemberDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(AnonymousClassDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(ArrayAccess node) { - return visitNode(node); - } - @Override - public boolean visit(ArrayCreation node) { - return visitNode(node); - } - @Override - public boolean visit(ArrayInitializer node) { - return visitNode(node); - } - @Override - public boolean visit(ArrayType node) { - return visitNode(node); - } - @Override - public boolean visit(AssertStatement node) { - return visitNode(node); - } - @Override - public boolean visit(Assignment node) { - return visitNode(node); - } - @Override - public boolean visit(Block node) { - return visitNode(node); - } - @Override - public boolean visit(BlockComment node) { - return visitNode(node); - } - @Override - public boolean visit(BooleanLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(BreakStatement node) { - return visitNode(node); - } - @Override - public boolean visit(CastExpression node) { - return visitNode(node); - } - @Override - public boolean visit(CatchClause node) { - return visitNode(node); - } - @Override - public boolean visit(CharacterLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(ClassInstanceCreation node) { - return visitNode(node); - } - @Override - public boolean visit(CompilationUnit node) { - return visitNode(node); - } - @Override - public boolean visit(ConditionalExpression node) { - return visitNode(node); - } - @Override - public boolean visit(ConstructorInvocation node) { - return visitNode(node); - } - @Override - public boolean visit(ContinueStatement node) { - return visitNode(node); - } - @Override - public boolean visit(CreationReference node) { - return visitNode(node); - } - @Override - public boolean visit(Dimension node) { - return visitNode(node); - } - @Override - public boolean visit(DoStatement node) { - return visitNode(node); - } - @Override - public boolean visit(EmptyStatement node) { - return visitNode(node); - } - @Override - public boolean visit(EnhancedForStatement node) { - return visitNode(node); - } - @Override - public boolean visit(EnumConstantDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(EnumDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(ExpressionMethodReference node) { - return visitNode(node); - } - @Override - public boolean visit(ExpressionStatement node) { - return visitNode(node); - } - @Override - public boolean visit(FieldAccess node) { - return visitNode(node); - } - @Override - public boolean visit(FieldDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(ForStatement node) { - return visitNode(node); - } - @Override - public boolean visit(IfStatement node) { - return visitNode(node); - } - @Override - public boolean visit(ImportDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(InfixExpression node) { - return visitNode(node); - } - @Override - public boolean visit(Initializer node) { - return visitNode(node); - } - @Override - public boolean visit(InstanceofExpression node) { - return visitNode(node); - } - @Override - public boolean visit(IntersectionType node) { - return visitNode(node); - } - @Override - public boolean visit(Javadoc node) { - if (super.visit(node)) - return visitNode(node); - else - return false; - } - @Override - public boolean visit(LabeledStatement node) { - return visitNode(node); - } - @Override - public boolean visit(LambdaExpression node) { - return visitNode(node); - } - @Override - public boolean visit(LineComment node) { - return visitNode(node); - } - @Override - public boolean visit(MarkerAnnotation node) { - return visitNode(node); - } - @Override - public boolean visit(MemberRef node) { - return visitNode(node); - } - @Override - public boolean visit(MemberValuePair node) { - return visitNode(node); - } - @Override - public boolean visit(MethodDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(MethodInvocation node) { - return visitNode(node); - } - @Override - public boolean visit(MethodRef node) { - return visitNode(node); - } - @Override - public boolean visit(MethodRefParameter node) { - return visitNode(node); - } - @Override - public boolean visit(Modifier node) { - return visitNode(node); - } - @Override - public boolean visit(NameQualifiedType node) { - return visitNode(node); - } - - @Override - public boolean visit(NormalAnnotation node) { - return visitNode(node); - } - @Override - public boolean visit(NullLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(NumberLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(PackageDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(ParameterizedType node) { - return visitNode(node); - } - @Override - public boolean visit(ParenthesizedExpression node) { - return visitNode(node); - } - @Override - public boolean visit(PostfixExpression node) { - return visitNode(node); - } - @Override - public boolean visit(PrefixExpression node) { - return visitNode(node); - } - @Override - public boolean visit(PrimitiveType node) { - return visitNode(node); - } - @Override - public boolean visit(QualifiedName node) { - return visitNode(node); - } - @Override - public boolean visit(QualifiedType node) { - return visitNode(node); - } - @Override - public boolean visit(ReturnStatement node) { - return visitNode(node); - } - @Override - public boolean visit(SimpleName node) { - return visitNode(node); - } - @Override - public boolean visit(SimpleType node) { - return visitNode(node); - } - @Override - public boolean visit(SingleMemberAnnotation node) { - return visitNode(node); - } - @Override - public boolean visit(SingleVariableDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(StringLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(SuperConstructorInvocation node) { - return visitNode(node); - } - @Override - public boolean visit(SuperFieldAccess node) { - return visitNode(node); - } - @Override - public boolean visit(SuperMethodInvocation node) { - return visitNode(node); - } - - - @Override - public boolean visit(SuperMethodReference node) { - return visitNode(node); - } - @Override - public boolean visit(SwitchCase node) { - return visitNode(node); - } - @Override - public boolean visit(SwitchStatement node) { - return visitNode(node); - } - @Override - public boolean visit(SynchronizedStatement node) { - return visitNode(node); - } - @Override - public boolean visit(TagElement node) { - return visitNode(node); - } - @Override - public boolean visit(TextElement node) { - return visitNode(node); - } - @Override - public boolean visit(ThisExpression node) { - return visitNode(node); - } - @Override - public boolean visit(ThrowStatement node) { - return visitNode(node); - } - @Override - public boolean visit(TryStatement node) { - return visitNode(node); - } - @Override - public boolean visit(TypeDeclaration node) { - return visitNode(node); - } - @Override - public boolean visit(TypeDeclarationStatement node) { - return visitNode(node); - } - @Override - public boolean visit(TypeLiteral node) { - return visitNode(node); - } - @Override - public boolean visit(TypeMethodReference node) { - return visitNode(node); - } - @Override - public boolean visit(TypeParameter node) { - return visitNode(node); - } - @Override - public boolean visit(UnionType node) { - return visitNode(node); - } - @Override - public boolean visit(VariableDeclarationExpression node) { - return visitNode(node); - } - @Override - public boolean visit(VariableDeclarationFragment node) { - return visitNode(node); - } - @Override - public boolean visit(VariableDeclarationStatement node) { - return visitNode(node); - } - @Override - public boolean visit(WhileStatement node) { - return visitNode(node); - } - @Override - public boolean visit(WildcardType node) { - return visitNode(node); - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java deleted file mode 100644 index d332bab084..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/HierarchicalASTVisitor.java +++ /dev/null @@ -1,1141 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import org.eclipse.jdt.core.dom.*; - -import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; - -/** - * <p> - * This class provides a convenient behaviour-only extension mechanism for the ASTNode hierarchy. If - * you feel like you would like to add a method to the ASTNode hierarchy (or a subtree of the - * hierarchy), and you want to have different implementations of it at different points in the - * hierarchy, simply create a HierarchicalASTVisitor representing the new method and all its - * implementations, locating each implementation within the right visit(XX) method. If you wanted to - * add a method implementation to abstract class Foo, an ASTNode descendant, put your implementation - * in visit(Foo). This class will provide appropriate dispatch, just as if the method - * implementations had been added to the ASTNode hierarchy. - * </p> - * - * <p> - * <b>Details:<b> - * </p> - * - * <p> - * This class has a visit(XX node) method for every class (concrete or abstract) XX in the ASTNode - * hierarchy. In this class' default implementations of these methods, the method corresponding to a - * given ASTNode descendant class will call (and return the return value of) the visit(YY) method - * for it's superclass YY, with the exception of the visit(ASTNode) method which simply returns - * true, since ASTNode doesn't have a superclass that is within the ASTNode hierarchy. - * </p> - * - * <p> - * Because of this organization, when visit(XX) methods are overridden in a subclass, and the - * visitor is applied to a node, only the most specialized overridden method implementation for the - * node's type will be called, unless this most specialized method calls other visit methods (this - * is discouraged) or, (preferably) calls super.visit(XX node), (the reference type of the parameter - * must be XX) which will invoke this class' implementation of the method, which will, in turn, - * invoke the visit(YY) method corresponding to the superclass, YY. - * </p> - * - * <p> - * Thus, the dispatching behaviour achieved when HierarchicalASTVisitors' visit(XX) methods, - * corresponding to a particular concrete or abstract ASTNode descendant class, are overridden is - * exactly analogous to the dispatching behaviour obtained when method implementations are added to - * the same ASTNode descendant classes. - * </p> - * - * @see JDTUIHelperClasses - */ -/* - * IMPORTANT NOTE: - * - * The structure and behaviour of this class is - * verified reflectively by - * org.eclipse.jdt.ui.tests.core.HierarchicalASTVisitorTest - * - */ -public abstract class HierarchicalASTVisitor extends ASTVisitor { -//TODO: check callers for handling of comments - -//---- Begin ASTNode Hierarchy ------------------------------------- - - /** - * Visits the given AST node. - * <p> - * The default implementation does nothing and return true. Subclasses may reimplement. - * </p> - * - * @param node the node to visit - * @return <code>true</code> if the children of this node should be visited, and - * <code>false</code> if the children of this node should be skipped - */ - public boolean visit(ASTNode node) { - return true; - } - - /** - * End of visit the given AST node. - * <p> - * The default implementation does nothing. Subclasses may reimplement. - * </p> - * - * @param node the node to visit - */ - public void endVisit(ASTNode node) { - // do nothing - } - - @Override - public boolean visit(AnonymousClassDeclaration node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(AnonymousClassDeclaration node) { - endVisit((ASTNode)node); - } - -//---- Begin BodyDeclaration Hierarchy --------------------------- - public boolean visit(BodyDeclaration node) { - return visit((ASTNode)node); - } - - public void endVisit(BodyDeclaration node) { - endVisit((ASTNode)node); - } - - //---- Begin AbstractTypeDeclaration Hierarchy --------------------------- - public boolean visit(AbstractTypeDeclaration node) { - return visit((BodyDeclaration)node); - } - - public void endVisit(AbstractTypeDeclaration node) { - endVisit((BodyDeclaration)node); - } - - @Override - public boolean visit(AnnotationTypeDeclaration node) { - return visit((AbstractTypeDeclaration)node); - } - - @Override - public void endVisit(AnnotationTypeDeclaration node) { - endVisit((AbstractTypeDeclaration)node); - } - - @Override - public boolean visit(EnumDeclaration node) { - return visit((AbstractTypeDeclaration)node); - } - - @Override - public void endVisit(EnumDeclaration node) { - endVisit((AbstractTypeDeclaration)node); - } - - @Override - public boolean visit(TypeDeclaration node) { - return visit((AbstractTypeDeclaration)node); - } - - @Override - public void endVisit(TypeDeclaration node) { - endVisit((AbstractTypeDeclaration)node); - } - - //---- End AbstractTypeDeclaration Hierarchy --------------------------- - - @Override - public boolean visit(AnnotationTypeMemberDeclaration node) { - return visit((BodyDeclaration)node); - } - - @Override - public void endVisit(AnnotationTypeMemberDeclaration node) { - endVisit((BodyDeclaration)node); - } - - @Override - public boolean visit(EnumConstantDeclaration node) { - return visit((BodyDeclaration)node); - } - - @Override - public void endVisit(EnumConstantDeclaration node) { - endVisit((BodyDeclaration)node); - } - - @Override - public boolean visit(FieldDeclaration node) { - return visit((BodyDeclaration)node); - } - - @Override - public void endVisit(FieldDeclaration node) { - endVisit((BodyDeclaration)node); - } - - @Override - public boolean visit(Initializer node) { - return visit((BodyDeclaration)node); - } - - @Override - public void endVisit(Initializer node) { - endVisit((BodyDeclaration)node); - } - - @Override - public boolean visit(MethodDeclaration node) { - return visit((BodyDeclaration)node); - } - - @Override - public void endVisit(MethodDeclaration node) { - endVisit((BodyDeclaration)node); - } - -//---- End BodyDeclaration Hierarchy ----------------------------- - - @Override - public boolean visit(CatchClause node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(CatchClause node) { - endVisit((ASTNode)node); - } - -//---- Begin Comment Hierarchy ---------------------------------- - public boolean visit(Comment node) { - return visit((ASTNode)node); - } - - public void endVisit(Comment node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(BlockComment node) { - return visit((Comment)node); - } - - @Override - public void endVisit(BlockComment node) { - endVisit((Comment)node); - } - - @Override - public boolean visit(Javadoc node) { - return visit((Comment)node); - } - - @Override - public void endVisit(Javadoc node) { - endVisit((Comment)node); - } - - @Override - public boolean visit(LineComment node) { - return visit((Comment)node); - } - - @Override - public void endVisit(LineComment node) { - endVisit((Comment)node); - } - -//---- End Comment Hierarchy ----------------------------- - - @Override - public boolean visit(CompilationUnit node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(CompilationUnit node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(Dimension node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(Dimension node) { - endVisit((ASTNode)node); - } - -//---- Begin Expression Hierarchy ---------------------------------- - public boolean visit(Expression node) { - return visit((ASTNode)node); - } - - public void endVisit(Expression node) { - endVisit((ASTNode)node); - } - - //---- Begin Annotation Hierarchy ---------------------------------- - public boolean visit(Annotation node) { - return visit((Expression)node); - } - - public void endVisit(Annotation node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(MarkerAnnotation node) { - return visit((Annotation)node); - } - - @Override - public void endVisit(MarkerAnnotation node) { - endVisit((Annotation)node); - } - - @Override - public boolean visit(NormalAnnotation node) { - return visit((Annotation)node); - } - - @Override - public void endVisit(NormalAnnotation node) { - endVisit((Annotation)node); - } - - @Override - public boolean visit(SingleMemberAnnotation node) { - return visit((Annotation)node); - } - - @Override - public void endVisit(SingleMemberAnnotation node) { - endVisit((Annotation)node); - } - - //---- End Annotation Hierarchy ----------------------------- - - @Override - public boolean visit(ArrayAccess node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ArrayAccess node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ArrayCreation node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ArrayCreation node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ArrayInitializer node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ArrayInitializer node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(Assignment node) { - return visit((Expression)node); - } - - @Override - public void endVisit(Assignment node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(BooleanLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(BooleanLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(CastExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(CastExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(CharacterLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(CharacterLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ClassInstanceCreation node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ClassInstanceCreation node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ConditionalExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ConditionalExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(FieldAccess node) { - return visit((Expression)node); - } - - @Override - public void endVisit(FieldAccess node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(InfixExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(InfixExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(InstanceofExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(InstanceofExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(LambdaExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(LambdaExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(MethodInvocation node) { - return visit((Expression)node); - } - - @Override - public void endVisit(MethodInvocation node) { - endVisit((Expression)node); - } - - //---- Begin MethodReference Hierarchy ---------------------------------- - public boolean visit(MethodReference node) { - return visit((Expression)node); - } - - public void endVisit(MethodReference node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(CreationReference node) { - return visit((MethodReference)node); - } - - @Override - public void endVisit(CreationReference node) { - endVisit((MethodReference)node); - } - - @Override - public boolean visit(ExpressionMethodReference node) { - return visit((MethodReference)node); - } - - @Override - public void endVisit(ExpressionMethodReference node) { - endVisit((MethodReference)node); - } - - @Override - public boolean visit(SuperMethodReference node) { - return visit((MethodReference)node); - } - - @Override - public void endVisit(SuperMethodReference node) { - endVisit((MethodReference)node); - } - - @Override - public boolean visit(TypeMethodReference node) { - return visit((MethodReference)node); - } - - @Override - public void endVisit(TypeMethodReference node) { - endVisit((MethodReference)node); - } - - //---- End MethodReference Hierarchy ------------------------------------ - - //---- Begin Name Hierarchy ---------------------------------- - public boolean visit(Name node) { - return visit((Expression)node); - } - - public void endVisit(Name node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(QualifiedName node) { - return visit((Name)node); - } - - @Override - public void endVisit(QualifiedName node) { - endVisit((Name)node); - } - - @Override - public boolean visit(SimpleName node) { - return visit((Name)node); - } - - @Override - public void endVisit(SimpleName node) { - endVisit((Name)node); - } - - //---- End Name Hierarchy ------------------------------------ - - @Override - public boolean visit(NullLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(NullLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(NumberLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(NumberLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ParenthesizedExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ParenthesizedExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(PostfixExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(PostfixExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(PrefixExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(PrefixExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(StringLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(StringLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(SuperFieldAccess node) { - return visit((Expression)node); - } - - @Override - public void endVisit(SuperFieldAccess node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(SuperMethodInvocation node) { - return visit((Expression)node); - } - - @Override - public void endVisit(SuperMethodInvocation node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(ThisExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(ThisExpression node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(TypeLiteral node) { - return visit((Expression)node); - } - - @Override - public void endVisit(TypeLiteral node) { - endVisit((Expression)node); - } - - @Override - public boolean visit(VariableDeclarationExpression node) { - return visit((Expression)node); - } - - @Override - public void endVisit(VariableDeclarationExpression node) { - endVisit((Expression)node); - } - - //---- End Expression Hierarchy ---------------------------------- - - @Override - public boolean visit(ImportDeclaration node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(ImportDeclaration node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(MemberRef node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(MemberRef node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(MemberValuePair node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(MemberValuePair node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(MethodRef node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(MethodRef node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(MethodRefParameter node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(MethodRefParameter node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(Modifier node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(Modifier node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(PackageDeclaration node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(PackageDeclaration node) { - endVisit((ASTNode)node); - } - -//---- Begin Statement Hierarchy --------------------------------- - public boolean visit(Statement node) { - return visit((ASTNode)node); - } - - public void endVisit(Statement node) { - endVisit((ASTNode)node); - } - - - @Override - public boolean visit(AssertStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(AssertStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(Block node) { - return visit((Statement)node); - } - - @Override - public void endVisit(Block node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(BreakStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(BreakStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ConstructorInvocation node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ConstructorInvocation node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ContinueStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ContinueStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(DoStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(DoStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(EmptyStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(EmptyStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(EnhancedForStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(EnhancedForStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ExpressionStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ExpressionStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ForStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ForStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(IfStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(IfStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(LabeledStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(LabeledStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ReturnStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ReturnStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(SuperConstructorInvocation node) { - return visit((Statement)node); - } - - @Override - public void endVisit(SuperConstructorInvocation node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(SwitchCase node) { - return visit((Statement)node); - } - - @Override - public void endVisit(SwitchCase node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(SwitchStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(SwitchStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(SynchronizedStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(SynchronizedStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(ThrowStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(ThrowStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(TryStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(TryStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(TypeDeclarationStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(TypeDeclarationStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(VariableDeclarationStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(VariableDeclarationStatement node) { - endVisit((Statement)node); - } - - @Override - public boolean visit(WhileStatement node) { - return visit((Statement)node); - } - - @Override - public void endVisit(WhileStatement node) { - endVisit((Statement)node); - } - -//---- End Statement Hierarchy ---------------------------------- - - @Override - public boolean visit(TagElement node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(TagElement node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(TextElement node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(TextElement node) { - endVisit((ASTNode)node); - } - - -//---- Begin Type Hierarchy -------------------------------------- - public boolean visit(Type node) { - return visit((ASTNode)node); - } - - public void endVisit(Type node) { - endVisit((ASTNode)node); - } - -//---- Begin Annotatable Type Hierarchy -------------------------------------- - public boolean visit(AnnotatableType node) { - return visit((Type)node); - } - - public void endVisit(AnnotatableType node) { - endVisit((Type)node); - } - - @Override - public boolean visit(NameQualifiedType node) { - return visit((AnnotatableType)node); - } - - @Override - public void endVisit(NameQualifiedType node) { - endVisit((AnnotatableType)node); - } - - @Override - public boolean visit(PrimitiveType node) { - return visit((AnnotatableType)node); - } - - @Override - public void endVisit(PrimitiveType node) { - endVisit((AnnotatableType)node); - } - - @Override - public boolean visit(QualifiedType node) { - return visit((AnnotatableType)node); - } - - @Override - public void endVisit(QualifiedType node) { - endVisit((AnnotatableType)node); - } - - @Override - public boolean visit(SimpleType node) { - return visit((AnnotatableType)node); - } - - @Override - public void endVisit(SimpleType node) { - endVisit((AnnotatableType)node); - } - - @Override - public boolean visit(WildcardType node) { - return visit((AnnotatableType)node); - } - - @Override - public void endVisit(WildcardType node) { - endVisit((AnnotatableType)node); - } -//---- End Annotatable Type Hierarchy -------------------------------------- - - @Override - public boolean visit(ArrayType node) { - return visit((Type)node); - } - - @Override - public void endVisit(ArrayType node) { - endVisit((Type)node); - } - - @Override - public boolean visit(IntersectionType node) { - return visit((Type)node); - } - - @Override - public void endVisit(IntersectionType node) { - endVisit((Type)node); - } - - @Override - public boolean visit(ParameterizedType node) { - return visit((Type)node); - } - - @Override - public void endVisit(ParameterizedType node) { - endVisit((Type)node); - } - - @Override - public boolean visit(UnionType node) { - return visit((Type)node); - } - - @Override - public void endVisit(UnionType node) { - endVisit((Type)node); - } - -//---- End Type Hierarchy ---------------------------------------- - - @Override - public boolean visit(TypeParameter node) { - return visit((ASTNode)node); - } - - @Override - public void endVisit(TypeParameter node) { - endVisit((ASTNode)node); - } - - -//---- Begin VariableDeclaration Hierarchy --------------------------- - public boolean visit(VariableDeclaration node) { - return visit((ASTNode)node); - } - - public void endVisit(VariableDeclaration node) { - endVisit((ASTNode)node); - } - - @Override - public boolean visit(SingleVariableDeclaration node) { - return visit((VariableDeclaration)node); - } - - @Override - public void endVisit(SingleVariableDeclaration node) { - endVisit((VariableDeclaration)node); - } - - @Override - public boolean visit(VariableDeclarationFragment node) { - return visit((VariableDeclaration)node); - } - - @Override - public void endVisit(VariableDeclarationFragment node) { - endVisit((VariableDeclaration)node); - } - -//---- End VariableDeclaration Hierarchy ----------------------------- -//---- End ASTNode Hierarchy ----------------------------------------- -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java deleted file mode 100644 index 3210f9f69a..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/ScopeAnalyzer.java +++ /dev/null @@ -1,869 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; - -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; -import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.CatchClause; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.CompilationUnit; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.FieldAccess; -import org.eclipse.jdt.core.dom.FieldDeclaration; -import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IBinding; -import org.eclipse.jdt.core.dom.IMethodBinding; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.IVariableBinding; -import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.MethodDeclaration; -import org.eclipse.jdt.core.dom.MethodInvocation; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.QualifiedName; -import org.eclipse.jdt.core.dom.SimpleName; -import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.dom.SuperFieldAccess; -import org.eclipse.jdt.core.dom.SuperMethodInvocation; -import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchStatement; -import org.eclipse.jdt.core.dom.Type; -import org.eclipse.jdt.core.dom.TypeDeclarationStatement; -import org.eclipse.jdt.core.dom.TypeParameter; -import org.eclipse.jdt.core.dom.VariableDeclaration; -import org.eclipse.jdt.core.dom.VariableDeclarationExpression; -import org.eclipse.jdt.core.dom.VariableDeclarationStatement; - -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; - -/** - * Evaluates all fields, methods and types available (declared) at a given offset - * in a compilation unit (Code assist that returns IBindings) - */ -public class ScopeAnalyzer { - - private static final IBinding[] NO_BINDING= new IBinding[0]; - - /** - * Flag to specify that method should be reported. - */ - public static final int METHODS= 1; - - /** - * Flag to specify that variables should be reported. - */ - public static final int VARIABLES= 2; - - /** - * Flag to specify that types should be reported. - */ - public static final int TYPES= 4; - - /** - * Flag to specify that only visible elements should be added. - */ - public static final int CHECK_VISIBILITY= 16; - - private static interface IBindingRequestor { - boolean acceptBinding(IBinding binding); - } - - private static class DefaultBindingRequestor implements IBindingRequestor { - - private final List<IBinding> fResult; - private final HashSet<String> fNamesAdded; - private final int fFlags; - private final ITypeBinding fParentTypeBinding; - - public DefaultBindingRequestor(ITypeBinding parentTypeBinding, int flags) { - fParentTypeBinding= parentTypeBinding; - fFlags= flags; - fResult= new ArrayList<>(); - fNamesAdded= new HashSet<>(); - } - - public DefaultBindingRequestor() { - this(null, 0); - } - - @Override - public boolean acceptBinding(IBinding binding) { - if (binding == null) - return false; - - String signature= getSignature(binding); - if (signature != null && fNamesAdded.add(signature)) { // avoid duplicated results from inheritance - fResult.add(binding); - } - return false; - } - - public List<IBinding> getResult() { - if (hasFlag(CHECK_VISIBILITY, fFlags)) { - for (int i= fResult.size() - 1; i >= 0; i--) { - IBinding binding= fResult.get(i); - if (!isVisible(binding, fParentTypeBinding)) { - fResult.remove(i); - } - } - } - return fResult; - } - - } - - private final HashSet<ITypeBinding> fTypesVisited; - - private final CompilationUnit fRoot; - - public ScopeAnalyzer(CompilationUnit root) { - fTypesVisited= new HashSet<>(); - fRoot= root; - } - - private void clearLists() { - fTypesVisited.clear(); - } - - private static String getSignature(IBinding binding) { - if (binding != null) { - switch (binding.getKind()) { - case IBinding.METHOD: - StringBuffer buf= new StringBuffer(); - buf.append('M'); - buf.append(binding.getName()).append('('); - ITypeBinding[] parameters= ((IMethodBinding) binding).getParameterTypes(); - for (int i= 0; i < parameters.length; i++) { - if (i > 0) { - buf.append(','); - } - ITypeBinding paramType= parameters[i].getErasure(); - buf.append(paramType.getQualifiedName()); - } - buf.append(')'); - return buf.toString(); - case IBinding.VARIABLE: - return 'V' + binding.getName(); - case IBinding.TYPE: - return 'T' + binding.getName(); - } - } - return null; - } - - static final boolean hasFlag(int property, int flags) { - return (flags & property) != 0; - } - - /** - * Collects all elements available in a type and its hierarchy - * @param binding The type binding - * @param flags Flags defining the elements to report - * @param requestor the requestor to which all results are reported - * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required - */ - private boolean addInherited(ITypeBinding binding, int flags, IBindingRequestor requestor) { - return addInherited(binding, false, flags, requestor); - } - - private boolean addInherited(ITypeBinding binding, boolean isSuperInterfaceBinding, int flags, IBindingRequestor requestor) { - if (!fTypesVisited.add(binding)) { - return false; - } - if (hasFlag(VARIABLES, flags)) { - IVariableBinding[] variableBindings= binding.getDeclaredFields(); - for (int i= 0; i < variableBindings.length; i++) { - if (requestor.acceptBinding(variableBindings[i])) - return true; - } - } - - if (hasFlag(METHODS, flags)) { - IMethodBinding[] methodBindings= binding.getDeclaredMethods(); - for (int i= 0; i < methodBindings.length; i++) { - IMethodBinding curr= methodBindings[i]; - if (isSuperInterfaceBinding && Modifier.isStatic(curr.getModifiers())) { - continue; - } - if (!curr.isSynthetic() && !curr.isConstructor()) { - if (requestor.acceptBinding(curr)) - return true; - } - } - } - - if (hasFlag(TYPES, flags)) { - ITypeBinding[] typeBindings= binding.getDeclaredTypes(); - for (int i= 0; i < typeBindings.length; i++) { - ITypeBinding curr= typeBindings[i]; - if (requestor.acceptBinding(curr)) - return true; - } - } - - - ITypeBinding superClass= binding.getSuperclass(); - if (superClass != null) { - if (addInherited(superClass, flags, requestor)) // recursive - return true; - } else if (binding.isArray()) { - if (addInherited(fRoot.getAST().resolveWellKnownType("java.lang.Object"), flags, requestor)) //$NON-NLS-1$ - return true; - } - - ITypeBinding[] interfaces= binding.getInterfaces(); // includes looking for methods: abstract, unimplemented methods - for (int i= 0; i < interfaces.length; i++) { - if (addInherited(interfaces[i], true, flags, requestor)) // recursive - return true; - } - return false; - } - - - /** - * Collects all elements available in a type: its hierarchy and its outer scopes. - * @param binding The type binding - * @param flags Flags defining the elements to report - * @param requestor the requestor to which all results are reported - * @return return <code>true</code> if the requestor has reported the binding as found and no further results are required - */ - private boolean addTypeDeclarations(ITypeBinding binding, int flags, IBindingRequestor requestor) { - if (hasFlag(TYPES, flags) && !binding.isAnonymous()) { - if (requestor.acceptBinding(binding)) - return true; - - ITypeBinding[] typeParameters= binding.getTypeParameters(); - for (int i= 0; i < typeParameters.length; i++) { - if (requestor.acceptBinding(typeParameters[i])) - return true; - } - } - - addInherited(binding, flags, requestor); // add inherited - - if (binding.isLocal()) { - addOuterDeclarationsForLocalType(binding, flags, requestor); - } else { - ITypeBinding declaringClass= binding.getDeclaringClass(); - if (declaringClass != null) { - if (addTypeDeclarations(declaringClass, flags, requestor)) // Recursively add inherited - return true; - } else if (hasFlag(TYPES, flags)) { - if (fRoot.findDeclaringNode(binding) != null) { - List<AbstractTypeDeclaration> types= fRoot.types(); - for (int i= 0; i < types.size(); i++) { - if (requestor.acceptBinding(types.get(i).resolveBinding())) - return true; - } - } - } - } - return false; - } - - private boolean addOuterDeclarationsForLocalType(ITypeBinding localBinding, int flags, IBindingRequestor requestor) { - ASTNode node= fRoot.findDeclaringNode(localBinding); - if (node == null) { - return false; - } - - if (node instanceof AbstractTypeDeclaration || node instanceof AnonymousClassDeclaration) { - if (addLocalDeclarations(node.getParent(), flags, requestor)) - return true; - - ITypeBinding parentTypeBinding= Bindings.getBindingOfParentType(node.getParent()); - if (parentTypeBinding != null) { - if (addTypeDeclarations(parentTypeBinding, flags, requestor)) - return true; - } - - } - return false; - } - - private static ITypeBinding getBinding(Expression node) { - if (node != null) { - return node.resolveTypeBinding(); - } - return null; - } - - private static ITypeBinding getQualifier(SimpleName selector) { - ASTNode parent= selector.getParent(); - switch (parent.getNodeType()) { - case ASTNode.METHOD_INVOCATION: - MethodInvocation decl= (MethodInvocation) parent; - if (selector == decl.getName()) { - return getBinding(decl.getExpression()); - } - return null; - case ASTNode.QUALIFIED_NAME: - QualifiedName qualifiedName= (QualifiedName) parent; - if (selector == qualifiedName.getName()) { - return getBinding(qualifiedName.getQualifier()); - } - return null; - case ASTNode.FIELD_ACCESS: - FieldAccess fieldAccess= (FieldAccess) parent; - if (selector == fieldAccess.getName()) { - return getBinding(fieldAccess.getExpression()); - } - return null; - case ASTNode.SUPER_FIELD_ACCESS: - SuperFieldAccess superFieldAccess= (SuperFieldAccess) parent; - if (selector == superFieldAccess.getName()) { - ITypeBinding curr= Bindings.getBindingOfParentType(parent); - return curr.getSuperclass(); - } - return null; - case ASTNode.SUPER_METHOD_INVOCATION: { - SuperMethodInvocation superInv= (SuperMethodInvocation) parent; - if (selector == superInv.getName()) { - ITypeBinding curr= Bindings.getBindingOfParentType(parent); - return curr.getSuperclass(); - } - return null; - } - default: - if (parent instanceof Type) { - // bug 67644: in 'a.new X()', all member types of A are visible as location of X. - ASTNode normalizedNode= ASTNodes.getNormalizedNode(parent); - if (normalizedNode.getLocationInParent() == ClassInstanceCreation.TYPE_PROPERTY) { - ClassInstanceCreation creation= (ClassInstanceCreation) normalizedNode.getParent(); - return getBinding(creation.getExpression()); - } - } - return null; - } - } - - public IBinding[] getDeclarationsInScope(SimpleName selector, int flags) { - try { - // special case for switch on enum - if (selector.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { - ITypeBinding binding= ((SwitchStatement) selector.getParent().getParent()).getExpression().resolveTypeBinding(); - if (binding != null && binding.isEnum()) { - return getEnumContants(binding); - } - } - - ITypeBinding parentTypeBinding= Bindings.getBindingOfParentType(selector); - if (parentTypeBinding != null) { - ITypeBinding binding= getQualifier(selector); - DefaultBindingRequestor requestor= new DefaultBindingRequestor(parentTypeBinding, flags); - if (binding == null) { - addLocalDeclarations(selector, flags, requestor); - addTypeDeclarations(parentTypeBinding, flags, requestor); - } else { - addInherited(binding, flags, requestor); - } - - List<IBinding> result= requestor.getResult(); - return result.toArray(new IBinding[result.size()]); - } - return NO_BINDING; - } finally { - clearLists(); - } - } - - private static class SearchRequestor implements IBindingRequestor { - - private final int fFlags; - private final ITypeBinding fParentTypeBinding; - private final IBinding fToSearch; - private boolean fFound; - private boolean fIsVisible; - - public SearchRequestor(IBinding toSearch, ITypeBinding parentTypeBinding, int flag) { - fFlags= flag; - fToSearch= toSearch; - fParentTypeBinding= parentTypeBinding; - fFound= false; - fIsVisible= true; - } - - @Override - public boolean acceptBinding(IBinding binding) { - if (fFound) - return true; - - if (binding == null) - return false; - - if (fToSearch.getKind() != binding.getKind()) { - return false; - } - - boolean checkVisibility= hasFlag(CHECK_VISIBILITY, fFlags); - if (binding == fToSearch) { - fFound= true; - } else { - IBinding bindingDeclaration= Bindings.getDeclaration(binding); - if (bindingDeclaration == fToSearch) { - fFound= true; - } else if (bindingDeclaration.getName().equals(fToSearch.getName())) { - String signature= getSignature(bindingDeclaration); - if (signature != null && signature.equals(getSignature(fToSearch))) { - if (checkVisibility) { - fIsVisible= false; - } - return true; // found element that hides the binding to find - } - } - } - - if (fFound && checkVisibility) { - fIsVisible= ScopeAnalyzer.isVisible(binding, fParentTypeBinding); - } - return fFound; - } - - public boolean found() { - return fFound; - } - - public boolean isVisible() { - return fIsVisible; - } - } - - public boolean isDeclaredInScope(IBinding declaration, SimpleName selector, int flags) { - try { - // special case for switch on enum - if (selector.getLocationInParent() == SwitchCase.EXPRESSION_PROPERTY) { - ITypeBinding binding= ((SwitchStatement) selector.getParent().getParent()).getExpression().resolveTypeBinding(); - if (binding != null && binding.isEnum()) { - return hasEnumContants(declaration, binding.getTypeDeclaration()); - } - } - - ITypeBinding parentTypeBinding= Bindings.getBindingOfParentTypeContext(selector); - if (parentTypeBinding != null) { - ITypeBinding binding= getQualifier(selector); - SearchRequestor requestor= new SearchRequestor(declaration, parentTypeBinding, flags); - if (binding == null) { - addLocalDeclarations(selector, flags, requestor); - if (requestor.found()) - return requestor.isVisible(); - addTypeDeclarations(parentTypeBinding, flags, requestor); - if (requestor.found()) - return requestor.isVisible(); - } else { - addInherited(binding, flags, requestor); - if (requestor.found()) - return requestor.isVisible(); - } - } - return false; - } finally { - clearLists(); - } - } - - private IVariableBinding[] getEnumContants(ITypeBinding binding) { - IVariableBinding[] declaredFields= binding.getDeclaredFields(); - ArrayList<IVariableBinding> res= new ArrayList<>(declaredFields.length); - for (int i= 0; i < declaredFields.length; i++) { - IVariableBinding curr= declaredFields[i]; - if (curr.isEnumConstant()) { - res.add(curr); - } - } - return res.toArray(new IVariableBinding[res.size()]); - } - - private boolean hasEnumContants(IBinding declaration, ITypeBinding binding) { - IVariableBinding[] declaredFields= binding.getDeclaredFields(); - for (int i= 0; i < declaredFields.length; i++) { - IVariableBinding curr= declaredFields[i]; - if (curr == declaration) - return true; - } - return false; - } - - public IBinding[] getDeclarationsInScope(int offset, int flags) { - org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0); - ASTNode node= finder.getCoveringNode(); - if (node == null) { - return NO_BINDING; - } - - if (node instanceof SimpleName) { - return getDeclarationsInScope((SimpleName) node, flags); - } - - try { - ITypeBinding binding= Bindings.getBindingOfParentType(node); - DefaultBindingRequestor requestor= new DefaultBindingRequestor(binding, flags); - addLocalDeclarations(node, offset, flags, requestor); - if (binding != null) { - addTypeDeclarations(binding, flags, requestor); - } - List<IBinding> result= requestor.getResult(); - return result.toArray(new IBinding[result.size()]); - } finally { - clearLists(); - } - } - - private static ITypeBinding getDeclaringType(IBinding binding) { - switch (binding.getKind()) { - case IBinding.VARIABLE: - return ((IVariableBinding) binding).getDeclaringClass(); - case IBinding.METHOD: - return ((IMethodBinding) binding).getDeclaringClass(); - case IBinding.TYPE: - ITypeBinding typeBinding= (ITypeBinding) binding; - if (typeBinding.getDeclaringClass() != null) { - return typeBinding; - } - return typeBinding; - } - return null; - } - - /** - * Evaluates if the declaration is visible in a certain context. - * @param binding The binding of the declaration to examine - * @param context The context to test in - * @return Returns - */ - public static boolean isVisible(IBinding binding, ITypeBinding context) { - if (binding.getKind() == IBinding.VARIABLE && !((IVariableBinding) binding).isField()) { - return true; // all local variables found are visible - } - ITypeBinding declaring= getDeclaringType(binding); - if (declaring == null) { - return false; - } - - declaring= declaring.getTypeDeclaration(); - - int modifiers= binding.getModifiers(); - if (Modifier.isPublic(modifiers) || declaring.isInterface()) { - return true; - } else if (Modifier.isProtected(modifiers) || !Modifier.isPrivate(modifiers)) { - if (declaring.getPackage() == context.getPackage()) { - return true; - } - return isTypeInScope(declaring, context, Modifier.isProtected(modifiers)); - } - // private visibility - return isTypeInScope(declaring, context, false); - } - - private static boolean isTypeInScope(ITypeBinding declaring, ITypeBinding context, boolean includeHierarchy) { - ITypeBinding curr= context.getTypeDeclaration(); - while (curr != null && curr != declaring) { - if (includeHierarchy && isInSuperTypeHierarchy(declaring, curr)) { - return true; - } - curr= curr.getDeclaringClass(); - } - return curr == declaring; - } - - /* - * This method is different from Binding.isSuperType as type declarations are compared - */ - private static boolean isInSuperTypeHierarchy(ITypeBinding possibleSuperTypeDecl, ITypeBinding type) { - if (type == possibleSuperTypeDecl) { - return true; - } - ITypeBinding superClass= type.getSuperclass(); - if (superClass != null) { - if (isInSuperTypeHierarchy(possibleSuperTypeDecl, superClass.getTypeDeclaration())) { - return true; - } - } - if (possibleSuperTypeDecl.isInterface()) { - ITypeBinding[] superInterfaces= type.getInterfaces(); - for (int i= 0; i < superInterfaces.length; i++) { - if (isInSuperTypeHierarchy(possibleSuperTypeDecl, superInterfaces[i].getTypeDeclaration())) { - return true; - } - } - } - return false; - } - - - public IBinding[] getDeclarationsAfter(int offset, int flags) { - try { - org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0); - ASTNode node= finder.getCoveringNode(); - if (node == null) { - return null; - } - - ASTNode declaration= ASTResolving.findParentStatement(node); - while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) { - declaration= declaration.getParent(); - } - - if (declaration instanceof Block) { - DefaultBindingRequestor requestor= new DefaultBindingRequestor(); - DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor); - declaration.accept(visitor); - List<IBinding> result= requestor.getResult(); - return result.toArray(new IBinding[result.size()]); - } - return NO_BINDING; - } finally { - clearLists(); - } - } - - - private class ScopeAnalyzerVisitor extends HierarchicalASTVisitor { - - private final int fPosition; - private final int fFlags; - private final IBindingRequestor fRequestor; - private boolean fBreak; - - public ScopeAnalyzerVisitor(int position, int flags, IBindingRequestor requestor) { - fPosition= position; - fFlags= flags; - fRequestor= requestor; - fBreak= false; - } - - private boolean isInside(ASTNode node) { - int start= node.getStartPosition(); - int end= start + node.getLength(); - - return start <= fPosition && fPosition < end; - } - - @Override - public boolean visit(MethodDeclaration node) { - if (isInside(node)) { - Block body= node.getBody(); - if (body != null) { - body.accept(this); - } - visitBackwards(node.parameters()); - visitBackwards(node.typeParameters()); - } - return false; - } - - - @Override - public boolean visit(TypeParameter node) { - if (hasFlag(TYPES, fFlags) && node.getStartPosition() < fPosition) { - fBreak= fRequestor.acceptBinding(node.getName().resolveBinding()); - } - return !fBreak; - } - - @Override - public boolean visit(SwitchCase node) { - // switch on enum allows to use enum constants without qualification - if (hasFlag(VARIABLES, fFlags) && !node.isDefault() && isInside(node.getExpression())) { - SwitchStatement switchStatement= (SwitchStatement) node.getParent(); - ITypeBinding binding= switchStatement.getExpression().resolveTypeBinding(); - if (binding != null && binding.isEnum()) { - IVariableBinding[] declaredFields= binding.getDeclaredFields(); - for (int i= 0; i < declaredFields.length; i++) { - IVariableBinding curr= declaredFields[i]; - if (curr.isEnumConstant()) { - fBreak= fRequestor.acceptBinding(curr); - if (fBreak) - return false; - } - } - } - } - return false; - } - - @Override - public boolean visit(Initializer node) { - return !fBreak && isInside(node); - } - - @Override - public boolean visit(FieldDeclaration node) { - return !fBreak && isInside(node); - } - - @Override - public boolean visit(Expression node) { - return !fBreak && isInside(node); - } - - @Override - public boolean visit(Statement node) { - return !fBreak && isInside(node); - } - - @Override - public boolean visit(ASTNode node) { - return false; - } - - @Override - public boolean visit(Block node) { - if (isInside(node)) { - visitBackwards(node.statements()); - } - return false; - } - - @Override - public boolean visit(VariableDeclaration node) { - if (hasFlag(VARIABLES, fFlags) && node.getStartPosition() < fPosition) { - fBreak= fRequestor.acceptBinding(node.resolveBinding()); - } - return !fBreak; - } - - @Override - public boolean visit(VariableDeclarationStatement node) { - visitBackwards(node.fragments()); - return false; - } - - @Override - public boolean visit(VariableDeclarationExpression node) { - visitBackwards(node.fragments()); - return false; - } - - @Override - public boolean visit(CatchClause node) { - if (isInside(node)) { - node.getBody().accept(this); - node.getException().accept(this); - } - return false; - } - - @Override - public boolean visit(ForStatement node) { - if (isInside(node)) { - node.getBody().accept(this); - visitBackwards(node.initializers()); - } - return false; - } - - @Override - public boolean visit(TypeDeclarationStatement node) { - if (hasFlag(TYPES, fFlags) && node.getStartPosition() + node.getLength() < fPosition) { - fBreak= fRequestor.acceptBinding(node.resolveBinding()); - return false; - } - return !fBreak && isInside(node); - } - - private void visitBackwards(List<? extends ASTNode> list) { - if (fBreak) - return; - - for (int i= list.size() - 1; i >= 0; i--) { - ASTNode curr= list.get(i); - if (curr.getStartPosition() < fPosition) { - curr.accept(this); - } - } - } - } - - private class DeclarationsAfterVisitor extends HierarchicalASTVisitor { - private final int fPosition; - private final int fFlags; - private final IBindingRequestor fRequestor; - private boolean fBreak; - - public DeclarationsAfterVisitor(int position, int flags, IBindingRequestor requestor) { - fPosition= position; - fFlags= flags; - fRequestor= requestor; - fBreak= false; - } - - @Override - public boolean visit(ASTNode node) { - return !fBreak; - } - - @Override - public boolean visit(VariableDeclaration node) { - if (hasFlag(VARIABLES, fFlags) && fPosition < node.getStartPosition()) { - fBreak= fRequestor.acceptBinding(node.resolveBinding()); - } - return false; - } - - @Override - public boolean visit(AnonymousClassDeclaration node) { - return false; - } - - @Override - public boolean visit(TypeDeclarationStatement node) { - if (hasFlag(TYPES, fFlags) && fPosition < node.getStartPosition()) { - fBreak= fRequestor.acceptBinding(node.resolveBinding()); - } - return false; - } - } - - private boolean addLocalDeclarations(ASTNode node, int flags, IBindingRequestor requestor) { - return addLocalDeclarations(node, node.getStartPosition(), flags, requestor); - } - - - private boolean addLocalDeclarations(ASTNode node, int offset, int flags, IBindingRequestor requestor) { - if (hasFlag(VARIABLES, flags) || hasFlag(TYPES, flags)) { - BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(node); - if (declaration instanceof MethodDeclaration || declaration instanceof Initializer || declaration instanceof FieldDeclaration) { - ScopeAnalyzerVisitor visitor= new ScopeAnalyzerVisitor(offset, flags, requestor); - declaration.accept(visitor); - return visitor.fBreak; - } - } - return false; - } - - public Collection<String> getUsedVariableNames(int offset, int length) { - HashSet<String> result= new HashSet<>(); - IBinding[] bindingsBefore= getDeclarationsInScope(offset, VARIABLES); - for (int i= 0; i < bindingsBefore.length; i++) { - result.add(bindingsBefore[i].getName()); - } - IBinding[] bindingsAfter= getDeclarationsAfter(offset + length, VARIABLES); - for (int i= 0; i < bindingsAfter.length; i++) { - result.add(bindingsAfter[i].getName()); - } - List<ImportDeclaration> imports= fRoot.imports(); - for (int i= 0; i < imports.size(); i++) { - ImportDeclaration decl= imports.get(i); - if (decl.isStatic() && !decl.isOnDemand()) { - result.add(ASTNodes.getSimpleNameIdentifier(decl.getName())); - } - } - return result; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TokenScanner.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TokenScanner.java deleted file mode 100644 index 317e1f91d1..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TokenScanner.java +++ /dev/null @@ -1,454 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IStatus; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.IDocument; -import org.eclipse.jface.text.IRegion; - -import org.eclipse.jdt.core.IBuffer; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.ITypeRoot; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.ToolFactory; -import org.eclipse.jdt.core.compiler.IScanner; -import org.eclipse.jdt.core.compiler.ITerminalSymbols; -import org.eclipse.jdt.core.compiler.InvalidInputException; - -import org.eclipse.jdt.internal.ui.JavaUIStatus; - -/** - * Wraps a scanner and offers convenient methods for finding tokens - */ -public class TokenScanner { - - public static final int END_OF_FILE= 20001; - public static final int LEXICAL_ERROR= 20002; - public static final int DOCUMENT_ERROR= 20003; - - private IScanner fScanner; - private IDocument fDocument; - private int fEndPosition; - - /** - * Creates a TokenScanner - * @param scanner The scanner to be wrapped. The scanner has to support line information - * if the comment position methods are used. - */ - public TokenScanner(IScanner scanner) { - this(scanner, null); - } - - /** - * Creates a TokenScanner - * @param scanner The scanner to be wrapped - * @param document The document used for line information if specified - */ - public TokenScanner(IScanner scanner, IDocument document) { - fScanner= scanner; - fEndPosition= fScanner.getSource().length - 1; - fDocument= document; - } - - /** - * Creates a TokenScanner - * @param document The textbuffer to create the scanner on - * @param project the current Java project - */ - public TokenScanner(IDocument document, IJavaProject project) { - String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true); - String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true); - fScanner= ToolFactory.createScanner(true, false, false, sourceLevel, complianceLevel); // no line info required - fScanner.setSource(document.get().toCharArray()); - fDocument= document; - fEndPosition= fScanner.getSource().length - 1; - } - - /** - * Creates a TokenScanner - * @param typeRoot The type root to scan on - * @throws CoreException thrown if the buffer cannot be accessed - */ - public TokenScanner(ITypeRoot typeRoot) throws CoreException { - IJavaProject project= typeRoot.getJavaProject(); - IBuffer buffer= typeRoot.getBuffer(); - if (buffer == null) { - throw new CoreException(createError(DOCUMENT_ERROR, "Element has no source", null)); //$NON-NLS-1$ - } - String sourceLevel= project.getOption(JavaCore.COMPILER_SOURCE, true); - String complianceLevel= project.getOption(JavaCore.COMPILER_COMPLIANCE, true); - fScanner= ToolFactory.createScanner(true, false, true, sourceLevel, complianceLevel); // line info required - - fScanner.setSource(buffer.getCharacters()); - fDocument= null; // use scanner for line information - fEndPosition= fScanner.getSource().length - 1; - } - - /** - * Returns the wrapped scanner - * @return IScanner - */ - public IScanner getScanner() { - return fScanner; - } - - /** - * Sets the scanner offset to the given offset. - * @param offset The offset to set - */ - public void setOffset(int offset) { - fScanner.resetTo(offset, fEndPosition); - } - - /** - * @return Returns the offset after the current token - */ - public int getCurrentEndOffset() { - return fScanner.getCurrentTokenEndPosition() + 1; - } - - /** - * @return Returns the start offset of the current token - */ - public int getCurrentStartOffset() { - return fScanner.getCurrentTokenStartPosition(); - } - - /** - * @return Returns the length of the current token - */ - public int getCurrentLength() { - return getCurrentEndOffset() - getCurrentStartOffset(); - } - - /** - * Reads the next token. - * @param ignoreComments If set, comments will be overread - * @return Return the token id. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int readNext(boolean ignoreComments) throws CoreException { - int curr= 0; - do { - try { - curr= fScanner.getNextToken(); - if (curr == ITerminalSymbols.TokenNameEOF) { - throw new CoreException(createError(END_OF_FILE, "End Of File", null)); //$NON-NLS-1$ - } - } catch (InvalidInputException e) { - throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); - } - } while (ignoreComments && isComment(curr)); - return curr; - } - - /** - * Reads the next token. - * @param ignoreComments If set, comments will be overread. - * @return Return the token id. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - private int readNextWithEOF(boolean ignoreComments) throws CoreException { - int curr= 0; - do { - try { - curr= fScanner.getNextToken(); - } catch (InvalidInputException e) { - throw new CoreException(createError(LEXICAL_ERROR, e.getMessage(), e)); - } - } while (ignoreComments && isComment(curr)); - return curr; - } - - /** - * Reads the next token from the given offset. - * @param offset The offset to start reading from. - * @param ignoreComments If set, comments will be overread. - * @return Returns the token id. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int readNext(int offset, boolean ignoreComments) throws CoreException { - setOffset(offset); - return readNext(ignoreComments); - } - - /** - * Reads the next token from the given offset and returns the start offset of the token. - * @param offset The offset to start reading from. - * @param ignoreComments If set, comments will be overread - * @return Returns the start position of the next token. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getNextStartOffset(int offset, boolean ignoreComments) throws CoreException { - readNext(offset, ignoreComments); - return getCurrentStartOffset(); - } - - /** - * Reads the next token from the given offset and returns the offset after the token. - * @param offset The offset to start reading from. - * @param ignoreComments If set, comments will be overread - * @return Returns the end position of the next token. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getNextEndOffset(int offset, boolean ignoreComments) throws CoreException { - readNext(offset, ignoreComments); - return getCurrentEndOffset(); - } - - /** - * Reads until a token is reached. - * @param tok The token to read to. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public void readToToken(int tok) throws CoreException { - int curr= 0; - do { - curr= readNext(false); - } while (curr != tok); - } - - /** - * Reads until a token is reached, starting from the given offset. - * @param tok The token to read to. - * @param offset The offset to start reading from. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public void readToToken(int tok, int offset) throws CoreException { - setOffset(offset); - readToToken(tok); - } - - /** - * Reads from the given offset until a token is reached and returns the start offset of the token. - * @param token The token to be found. - * @param startOffset The offset to start reading from. - * @return Returns the start position of the found token. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getTokenStartOffset(int token, int startOffset) throws CoreException { - readToToken(token, startOffset); - return getCurrentStartOffset(); - } - - /** - * Reads from the given offset until a token is reached and returns the offset after the token. - * @param token The token to be found. - * @param startOffset Offset to start reading from - * @return Returns the end position of the found token. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getTokenEndOffset(int token, int startOffset) throws CoreException { - readToToken(token, startOffset); - return getCurrentEndOffset(); - } - - /** - * Reads from the given offset until a token is reached and returns the offset after the previous token. - * @param token The token to be found. - * @param startOffset The offset to start scanning from. - * @return Returns the end offset of the token previous to the given token. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getPreviousTokenEndOffset(int token, int startOffset) throws CoreException { - setOffset(startOffset); - int res= startOffset; - int curr= readNext(false); - while (curr != token) { - res= getCurrentEndOffset(); - curr= readNext(false); - } - return res; - } - - /** - * Evaluates the start offset of comments directly ahead of a token specified by its start offset - * - * @param lastPos An offset to before the node start offset. Can be 0 but better is the end location of the previous node. - * @param nodeStart Start offset of the node to find the comments for. - * @return Returns the start offset of comments directly ahead of a token. - * @exception CoreException Thrown when a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getTokenCommentStart(int lastPos, int nodeStart) throws CoreException { - setOffset(lastPos); - - int prevEndPos= lastPos; - int prevEndLine= prevEndPos > 0 ? getLineOfOffset(prevEndPos - 1) : 0; - int nodeLine= getLineOfOffset(nodeStart); - - int res= -1; - - int curr= readNextWithEOF(false); - int currStartPos= getCurrentStartOffset(); - int currStartLine= getLineOfOffset(currStartPos); - while (curr != ITerminalSymbols.TokenNameEOF && nodeStart > currStartPos) { - if (TokenScanner.isComment(curr)) { - int linesDifference= currStartLine - prevEndLine; - if ((linesDifference > 1) || (res == -1 && (linesDifference != 0 || nodeLine == currStartLine))) { - res= currStartPos; // begin new - } - } else { - res= -1; - } - - if (curr == ITerminalSymbols.TokenNameCOMMENT_LINE) { - prevEndLine= currStartLine; - } else { - prevEndLine= getLineOfOffset(getCurrentEndOffset() - 1); - } - curr= readNextWithEOF(false); - currStartPos= getCurrentStartOffset(); - currStartLine= getLineOfOffset(currStartPos); - } - if (res == -1 || curr == ITerminalSymbols.TokenNameEOF) { - return nodeStart; - } - if (currStartLine - prevEndLine > 1) { - return nodeStart; - } - return res; - } - - /** - * Looks for comments after a node and returns the end position of the comment still belonging to the node. - * @param nodeEnd The end position of the node - * @param nextTokenStart The start positoion of the next node. Optional, can be -1 - * the line information shoould be taken from the scanner object - * @return Returns returns the end position of the comment still belonging to the node. - * @exception CoreException Thrown when the end of the file has been reached (code END_OF_FILE) - * or a lexical error was detected while scanning (code LEXICAL_ERROR) - */ - public int getTokenCommentEnd(int nodeEnd, int nextTokenStart) throws CoreException { - // assign comments to the previous comments as long they are all on the same line as the - // node end position or if they are on the next line but there is a separation from the next - // node - // } //aa - // // aa - // - // // bb - // public void b... - // - // } /* cc */ /* - // cc/* - // /*dd*/ - // public void d... - - int prevEndLine= getLineOfOffset(nodeEnd - 1); - int prevEndPos= nodeEnd; - int res= nodeEnd; - boolean sameLineComment= true; - - setOffset(nodeEnd); - - - int curr= readNextWithEOF(false); - while (curr == ITerminalSymbols.TokenNameCOMMENT_LINE || curr == ITerminalSymbols.TokenNameCOMMENT_BLOCK) { - int currStartLine= getLineOfOffset(getCurrentStartOffset()); - int linesDifference= currStartLine - prevEndLine; - - if (linesDifference > 1) { - return prevEndPos; // separated comments - } - - if (curr == ITerminalSymbols.TokenNameCOMMENT_LINE) { - prevEndPos= getLineEnd(currStartLine); - prevEndLine= currStartLine; - } else { - prevEndPos= getCurrentEndOffset(); - prevEndLine= getLineOfOffset(prevEndPos - 1); - } - if (sameLineComment) { - if (linesDifference == 0) { - res= prevEndPos; - } else { - sameLineComment= false; - } - } - curr= readNextWithEOF(false); - } - if (curr == ITerminalSymbols.TokenNameEOF) { - return prevEndPos; - } - int currStartLine= getLineOfOffset(getCurrentStartOffset()); - int linesDifference= currStartLine - prevEndLine; - if (linesDifference > 1) { - return prevEndPos; // separated comments - } - return res; - } - - public int getLineOfOffset(int offset) throws CoreException { - if (fDocument != null) { - try { - return fDocument.getLineOfOffset(offset); - } catch (BadLocationException e) { - String message= "Illegal offset: " + offset; //$NON-NLS-1$ - throw new CoreException(createError(DOCUMENT_ERROR, message, e)); - } - } - return getScanner().getLineNumber(offset); - } - - public int getLineEnd(int line) throws CoreException { - if (fDocument != null) { - try { - IRegion region= fDocument.getLineInformation(line); - return region.getOffset() + region.getLength(); - } catch (BadLocationException e) { - String message= "Illegal line: " + line; //$NON-NLS-1$ - throw new CoreException(createError(DOCUMENT_ERROR, message, e)); - } - } - return getScanner().getLineEnd(line); - } - - public static boolean isComment(int token) { - return token == ITerminalSymbols.TokenNameCOMMENT_BLOCK || token == ITerminalSymbols.TokenNameCOMMENT_JAVADOC - || token == ITerminalSymbols.TokenNameCOMMENT_LINE; - } - - public static boolean isModifier(int token) { - switch (token) { - case ITerminalSymbols.TokenNamepublic: - case ITerminalSymbols.TokenNameprotected: - case ITerminalSymbols.TokenNameprivate: - case ITerminalSymbols.TokenNamestatic: - case ITerminalSymbols.TokenNamefinal: - case ITerminalSymbols.TokenNameabstract: - case ITerminalSymbols.TokenNamenative: - case ITerminalSymbols.TokenNamevolatile: - case ITerminalSymbols.TokenNamestrictfp: - case ITerminalSymbols.TokenNametransient: - case ITerminalSymbols.TokenNamesynchronized: - return true; - default: - return false; - } - } - - private IStatus createError(int code, String message, Throwable e) { - return JavaUIStatus.createError(code, message, e); - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeBindingVisitor.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeBindingVisitor.java deleted file mode 100644 index 49729c058e..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeBindingVisitor.java +++ /dev/null @@ -1,30 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for - * bug "inline method - doesn't handle implicit cast" (see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941). - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import org.eclipse.jdt.core.dom.ITypeBinding; - -/** - * Interface used in type binding visiting algorithms. - * - * @see Bindings#visitHierarchy(ITypeBinding, TypeBindingVisitor) - */ -public interface TypeBindingVisitor { - - /** - * @param type a type binding - * @return <code>true</code> to continue visiting types, - * or <code>false</code> to abort and return <code>false</code> - */ - public boolean visit(ITypeBinding type); -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeRules.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeRules.java deleted file mode 100644 index 95a177c9a5..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/dom/TypeRules.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Dmitry Stalnov (dstalnov@fusionone.com) - contributed fix for - * bug "inline method - doesn't handle implicit cast" (see - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=24941). - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.dom; - -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.PrimitiveType; - -import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TType; -import org.eclipse.jdt.internal.corext.refactoring.typeconstraints.types.TypeEnvironment; -import org.eclipse.jdt.internal.corext.util.JDTUIHelperClasses; - -/** - * Helper class to check if objects are assignable to each other. - * Methods with multiple arguments also work across bindings environments. - * - * @see JDTUIHelperClasses - */ -public class TypeRules { - - /** - * Tests if two types are assign compatible. Void types are never compatible. - * - * @param typeToAssign The binding of the type to assign - * @param definedType The type of the object that is assigned - * @return <code>true</code> iff definedType = typeToAssign is a valid assignment - */ - public static boolean canAssign(ITypeBinding typeToAssign, ITypeBinding definedType) { - TypeEnvironment typeEnvironment= new TypeEnvironment(false, true); - TType defined= typeEnvironment.create(definedType); - TType toAssign= typeEnvironment.create(typeToAssign); - return toAssign.canAssignTo(defined); - } - - public static boolean isArrayCompatible(ITypeBinding definedType) { - if (definedType.isTopLevel()) { - if (definedType.isClass()) { - return "Object".equals(definedType.getName()) && "java.lang".equals(definedType.getPackage().getName()); //$NON-NLS-1$//$NON-NLS-2$ - } else { - String qualifiedName= definedType.getQualifiedName(); - return "java.io.Serializable".equals(qualifiedName) || "java.lang.Cloneable".equals(qualifiedName); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - return false; - } - - public static boolean isJavaLangObject(ITypeBinding definedType) { - return definedType.isTopLevel() && definedType.isClass() && "Object".equals(definedType.getName()) && "java.lang".equals(definedType.getPackage().getName()); //$NON-NLS-1$//$NON-NLS-2$ - } - - /** - * Tests if a two types are cast compatible - * @param castType The binding of the type to cast to - * @param bindingToCast The binding ef the expression to cast. - * @return boolean Returns true if (castType) bindingToCast is a valid cast expression (can be unnecessary, but not invalid). - */ - public static boolean canCast(ITypeBinding castType, ITypeBinding bindingToCast) { - //see bug 80715 - - String voidName= PrimitiveType.VOID.toString(); - - if (castType.isAnonymous() || castType.isNullType() || voidName.equals(castType.getName())) { - throw new IllegalArgumentException(); - } - - if (castType == bindingToCast) { - return true; - } - - if (voidName.equals(bindingToCast.getName())) { - return false; - } - - if (bindingToCast.isArray()) { - if (!castType.isArray()) { - return isArrayCompatible(castType); // can not cast an arraytype to a non array type (except to Object, Serializable...) - } - - int toCastDim= bindingToCast.getDimensions(); - int castTypeDim= castType.getDimensions(); - if (toCastDim == castTypeDim) { - bindingToCast= bindingToCast.getElementType(); - castType= castType.getElementType(); - if (castType.isPrimitive() && castType != bindingToCast) { - return false; // can't assign arrays of different primitive types to each other - } - // fall through - } else if (toCastDim < castTypeDim) { - return isArrayCompatible(bindingToCast.getElementType()); - } else { - return isArrayCompatible(castType.getElementType()); - } - } - if (castType.isPrimitive()) { - if (!bindingToCast.isPrimitive()) { - return false; - } - String boolName= PrimitiveType.BOOLEAN.toString(); - return (!boolName.equals(castType.getName()) && !boolName.equals(bindingToCast.getName())); - } else { - if (bindingToCast.isPrimitive()) { - return false; - } - if (castType.isArray()) { - return isArrayCompatible(bindingToCast); - } - if (castType.isInterface()) { - if ((bindingToCast.getModifiers() & Modifier.FINAL) != 0) { - return Bindings.isSuperType(castType, bindingToCast); - } else { - return true; - } - } - if (bindingToCast.isInterface()) { - if ((castType.getModifiers() & Modifier.FINAL) != 0) { - return Bindings.isSuperType(bindingToCast, castType); - } else { - return true; - } - } - if (isJavaLangObject(castType)) { - return true; - } - - return Bindings.isSuperType(bindingToCast, castType) || Bindings.isSuperType(castType, bindingToCast); - } - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRefactoring.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRefactoring.java index abc791d296..2b6404bc4d 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRefactoring.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CleanUpRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -86,9 +86,9 @@ import org.eclipse.jdt.internal.ui.IJavaStatusConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.fix.IMultiFix.MultiFixContext; import org.eclipse.jdt.internal.ui.fix.MapCleanUpOptions; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.ui.refactoring.IScheduledRefactoring; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class CleanUpRefactoring extends Refactoring implements IScheduledRefactoring { @@ -854,11 +854,11 @@ public class CleanUpRefactoring extends Refactoring implements IScheduledRefacto } public static ASTParser createCleanUpASTParser() { - ASTParser result= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser result= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); result.setResolveBindings(true); - result.setStatementsRecovery(ASTProvider.SHARED_AST_STATEMENT_RECOVERY); - result.setBindingsRecovery(ASTProvider.SHARED_BINDING_RECOVERY); + result.setStatementsRecovery(IASTSharedValues.SHARED_AST_STATEMENT_RECOVERY); + result.setBindingsRecovery(IASTSharedValues.SHARED_BINDING_RECOVERY); return result; } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java index 6c5da0d0ec..bcf5fa2bbf 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/CodeStyleFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -67,9 +67,10 @@ import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; import org.eclipse.jdt.ui.text.java.IProblemLocation; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; + +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** * A fix which fixes code style issues. diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java index 2d04891622..12c92dbcd0 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java @@ -58,8 +58,9 @@ import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; + +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** * Operation to convert for loops over iterables to enhanced for loops. diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ImportsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ImportsFix.java index 3580ba038d..d9cd0b6566 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ImportsFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/ImportsFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2008 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; import org.eclipse.jdt.internal.ui.actions.ActionMessages; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class ImportsFix extends TextEditFix { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/Java50Fix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/Java50Fix.java index 91424b5777..b18a91ab2c 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/Java50Fix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/Java50Fix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -64,7 +64,7 @@ import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** * Fix which introduce new language constructs to pre Java50 code. diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java index 8186cb7df0..e60058694a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/LambdaExpressionsFix.java @@ -62,6 +62,7 @@ import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2; @@ -78,7 +79,6 @@ import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; public class LambdaExpressionsFix extends CompilationUnitRewriteOperationsFix { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsRewriteOperations.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsRewriteOperations.java index 8b6edf34b1..724bc4708c 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsRewriteOperations.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsRewriteOperations.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2013 GK Software AG and others. + * Copyright (c) 2011, 2016 GK Software AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -55,8 +55,8 @@ import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.text.java.IProblemLocation; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class NullAnnotationsRewriteOperations { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java index af978d6659..6064e94ece 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/PotentialProgrammingProblemsFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2014 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -63,10 +63,10 @@ import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; import org.eclipse.jdt.ui.text.java.IProblemLocation; -import org.eclipse.jdt.internal.ui.javaeditor.ASTProvider; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation; import org.eclipse.jdt.internal.ui.text.correction.SerialVersionHashOperation; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class PotentialProgrammingProblemsFix extends CompilationUnitRewriteOperationsFix { @@ -112,7 +112,7 @@ public class PotentialProgrammingProblemsFix extends CompilationUnitRewriteOpera throw new OperationCanceledException(); result= new RefactoringStatus(); - ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL); + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setProject(fProject); IBinding[] bindings= parser.createBindings(types, new SubProgressMonitor(monitor, 1)); for (int i= 0; i < bindings.length; i++) { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnimplementedCodeFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnimplementedCodeFix.java index 374e254c7e..afb0efd787 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnimplementedCodeFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnimplementedCodeFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2011 IBM Corporation and others. + * Copyright (c) 2007, 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 v1.0 * which accompanies this distribution, and is available at @@ -51,7 +51,7 @@ import org.eclipse.jdt.ui.cleanup.ICleanUpFix; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class UnimplementedCodeFix extends CompilationUnitRewriteOperationsFix { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnusedCodeFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnusedCodeFix.java index ad0ad86187..958c454ed6 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnusedCodeFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/UnusedCodeFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -75,7 +75,7 @@ import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.ui.fix.UnusedCodeCleanUp; import org.eclipse.jdt.internal.ui.text.correction.JavadocTagsSubProcessor; import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** * Fix which removes unused code. diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/VariableDeclarationFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/VariableDeclarationFix.java index 6cb627a965..f991f8111b 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/VariableDeclarationFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/VariableDeclarationFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -47,6 +47,7 @@ import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; import org.eclipse.jdt.internal.corext.dom.VariableDeclarationRewrite; @@ -54,8 +55,6 @@ import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewr import org.eclipse.jdt.ui.cleanup.ICleanUpFix; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; - public class VariableDeclarationFix extends CompilationUnitRewriteOperationsFix { private static class WrittenNamesFinder extends GenericVisitor { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java index a26b18c6ce..e57c8e8490 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -30,7 +30,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.util.Messages; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** */ diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java index 3eab70fc92..2da692c544 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContext.java @@ -72,11 +72,12 @@ import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatch; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; +import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.template.java.CompilationUnitCompletion.Variable; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; -import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.corext.util.TypeNameMatchCollector; import org.eclipse.jdt.ui.JavaUI; @@ -647,7 +648,7 @@ public class JavaContext extends CompilationUnitContext { document.addPosition(position); try { - JavaModelUtil.applyEdit(cu, fImportRewrite.rewriteImports(null), false, null); + JavaElementUtil.applyEdit(cu, fImportRewrite.rewriteImports(null), false, null); setCompletionOffset(position.getOffset()); } catch (CoreException e) { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaDocContext.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaDocContext.java index f7fcf95b35..9b714d440a 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaDocContext.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/JavaDocContext.java @@ -27,7 +27,7 @@ import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.internal.corext.util.Strings; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; import org.eclipse.jdt.ui.PreferenceConstants; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/SignatureUtil.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/SignatureUtil.java deleted file mode 100644 index 816141f0c1..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/template/java/SignatureUtil.java +++ /dev/null @@ -1,320 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.template.java; - -import java.util.Arrays; - -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; - -/** - * Utilities for Signature operations. - * - * @see Signature - * @since 3.1 - */ -public final class SignatureUtil { - - /** - * The signature of the null type. This type does not really exist in the - * type system. It represents the bound of type variables that have no lower - * bound, for example the parameter type to the <code>add</code> method of - * an instance of <code>java.util.List<? extends Number></code>. - * <p> - * The only possible value that has that type is <code>null</code>. - * </p> - * <p> - * The representation of the null type is the signature of a type variable - * named <code>null</code> ({@value}), which will only work if no such - * variable gets declared in the same context. - */ - private static final String NULL_TYPE_SIGNATURE= "Tnull;"; //$NON-NLS-1$ - private static final char[] NULL_TYPE_SIGNATURE_ARRAY= NULL_TYPE_SIGNATURE.toCharArray(); - /** - * The signature of <code>java.lang.Object</code> ({@value}). - */ - private static final String OBJECT_SIGNATURE= "Ljava.lang.Object;"; //$NON-NLS-1$ - private static final char[] OBJECT_SIGNATURE_ARRAY= OBJECT_SIGNATURE.toCharArray(); - - private SignatureUtil() { - // do not instantiate - } - - /** - * Returns <code>true</code> if <code>signature</code> is the - * signature of the <code>java.lang.Object</code> type. - * - * @param signature the signature - * @return <code>true</code> if <code>signature</code> is the - * signature of the <code>java.lang.Object</code> type, - * <code>false</code> otherwise - */ - public static boolean isJavaLangObject(String signature) { - return OBJECT_SIGNATURE.equals(signature); - } - - /** - * Returns the upper bound of a type signature. Returns the signature of <code>java.lang.Object</code> if - * <code>signature</code> is a lower bound (<code>? super T</code>); returns - * the signature of the type <code>T</code> of an upper bound (<code>? extends T</code>) - * or <code>signature</code> itself if it is not a bound signature. - * - * @param signature the signature - * @return the upper bound signature of <code>signature</code> - */ - public static String getUpperBound(String signature) { - return String.valueOf(getUpperBound(signature.toCharArray())); - } - - /** - * Returns the upper bound of a type signature. Returns the signature of <code>java.lang.Object</code> if - * <code>signature</code> is a lower bound (<code>? super T</code>); returns - * the signature of the type <code>T</code> of an upper bound (<code>? extends T</code>) - * or <code>signature</code> itself if it is not a bound signature. - * - * @param signature the signature - * @return the upper bound signature of <code>signature</code> - */ - public static char[] getUpperBound(char[] signature) { - if (signature.length < 1) - return signature; - - if (signature[0] == Signature.C_STAR) - return OBJECT_SIGNATURE_ARRAY; - - int superIndex= indexOf(signature, Signature.C_SUPER); - if (superIndex == 0) - return OBJECT_SIGNATURE_ARRAY; - - if (superIndex != -1) { - char afterSuper= signature[superIndex + 1]; - if (afterSuper == Signature.C_STAR) { - char[] type= new char[signature.length - 1]; - System.arraycopy(signature, 0, type, 0, superIndex); - type[superIndex]= Signature.C_STAR; - System.arraycopy(signature, superIndex + 2, type, superIndex + 1, signature.length - superIndex - 2); - return getUpperBound(type); - } - - if (afterSuper == Signature.C_EXTENDS) { - int typeEnd= typeEnd(signature, superIndex + 1); - char[] type= new char[signature.length - (typeEnd - superIndex - 1)]; - System.arraycopy(signature, 0, type, 0, superIndex); - type[superIndex]= Signature.C_STAR; - System.arraycopy(signature, typeEnd, type, superIndex + 1, signature.length - typeEnd); - return getUpperBound(type); - } - - } - - if (signature[0] == Signature.C_EXTENDS) { - char[] type= new char[signature.length - 1]; - System.arraycopy(signature, 1, type, 0, signature.length - 1); - return type; - } - - return signature; - } - - /** - * Returns the lower bound of a type signature. Returns the null type - * signature if <code>signature</code> is a wildcard or upper bound (<code>? extends T</code>); - * returns the signature of the type <code>T</code> of a lower bound (<code>? super T</code>) - * or <code>signature</code> itself if it is not a bound signature. - * - * @param signature the signature - * @return the lower bound signature of <code>signature</code> - */ - public static String getLowerBound(String signature) { - return String.valueOf(getLowerBound(signature.toCharArray())); - } - - /** - * Returns the lower bound of a type signature. Returns the null type - * signature if <code>signature</code> is a wildcard or upper bound (<code>? extends T</code>); - * returns the signature of the type <code>T</code> of a lower bound (<code>? super T</code>) - * or <code>signature</code> itself if it is not a bound signature. - * - * @param signature the signature - * @return the lower bound signature of <code>signature</code> - */ - public static char[] getLowerBound(char[] signature) { - if (signature.length < 1) - return signature; - - if (signature.length == 1 && signature[0] == Signature.C_STAR) - return signature; - - int superIndex= indexOf(signature, Signature.C_EXTENDS); - if (superIndex == 0) - return NULL_TYPE_SIGNATURE_ARRAY; - - if (superIndex != -1) { - char afterSuper= signature[superIndex + 1]; - if (afterSuper == Signature.C_STAR || afterSuper == Signature.C_EXTENDS) - // impossible captured type - return NULL_TYPE_SIGNATURE_ARRAY; - } - - char[][] typeArguments= Signature.getTypeArguments(signature); - for (int i= 0; i < typeArguments.length; i++) - if (Arrays.equals(typeArguments[i], NULL_TYPE_SIGNATURE_ARRAY)) - return NULL_TYPE_SIGNATURE_ARRAY; - - if (signature[0] == Signature.C_SUPER) { - char[] type= new char[signature.length - 1]; - System.arraycopy(signature, 1, type, 0, signature.length - 1); - return type; - } - - return signature; - } - - private static int indexOf(char[] signature, char ch) { - for (int i= 0; i < signature.length; i++) { - if (signature[i] == ch) - return i; - } - return -1; - } - - /** - * Returns the fully qualified type name of the given signature, with any - * type parameters and arrays erased. - * - * @param signature the signature - * @return the fully qualified type name of the signature - * @throws IllegalArgumentException if the signature is syntactically incorrect - */ - public static String stripSignatureToFQN(String signature) throws IllegalArgumentException { - signature= Signature.getTypeErasure(signature); - signature= Signature.getElementType(signature); - return Signature.toString(signature); - } - - /** - * Returns the qualified signature corresponding to - * <code>signature</code>. - * - * @param signature the signature to qualify - * @param context the type inside which an unqualified type will be - * resolved to find the qualifier, or <code>null</code> if no - * context is available - * @return the qualified signature - */ - public static String qualifySignature(final String signature, final IType context) { - if (context == null) - return signature; - - String qualifier= Signature.getSignatureQualifier(signature); - if (qualifier.length() > 0) - return signature; - - String elementType= Signature.getElementType(signature); - String erasure= Signature.getTypeErasure(elementType); - String simpleName= Signature.getSignatureSimpleName(erasure); - String genericSimpleName= Signature.getSignatureSimpleName(elementType); - - int dim= Signature.getArrayCount(signature); - - try { - String[][] strings= context.resolveType(simpleName); - if (strings != null && strings.length > 0) - qualifier= strings[0][0]; - } catch (JavaModelException e) { - // ignore - not found - } - - if (qualifier.length() == 0) - return signature; - - String qualifiedType= Signature.toQualifiedName(new String[] {qualifier, genericSimpleName}); - String qualifiedSignature= Signature.createTypeSignature(qualifiedType, true); - String newSignature= Signature.createArraySignature(qualifiedSignature, dim); - - return newSignature; - } - - /** - * Takes a method signature - * <code>[< typeVariableName : formalTypeDecl >] ( paramTypeSig1* ) retTypeSig</code> - * and returns it with any parameter signatures filtered through - * <code>getLowerBound</code> and the return type filtered through - * <code>getUpperBound</code>. Any preceding formal type variable - * declarations are removed. - * <p> - * TODO this is a temporary workaround for - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=83600 - * </p> - * - * @param signature the method signature to convert - * @return the signature with no bounded types - */ - public static char[] unboundedSignature(char[] signature) { - if (signature == null || signature.length < 2) - return signature; - - final boolean BUG_83600= true; - // XXX the signatures from CompletionRequestor contain a superfluous '+' - // before type parameters to parameter types - if (BUG_83600) { - signature= fix83600(signature); - } - - StringBuffer res= new StringBuffer("("); //$NON-NLS-1$ - char[][] parameters= Signature.getParameterTypes(signature); - for (int i= 0; i < parameters.length; i++) { - char[] param= parameters[i]; - res.append(getLowerBound(param)); - } - res.append(')'); - res.append(getUpperBound(Signature.getReturnType(signature))); - return res.toString().toCharArray(); - } - - /** - * TODO this is a temporary workaround for - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=83600 and - * https://bugs.eclipse.org/bugs/show_bug.cgi?id=85293 - * - * @param signature the method signature to convert - * @return the fixed signature - */ - public static char[] fix83600(char[] signature) { - if (signature == null || signature.length < 2) - return signature; - - return Signature.removeCapture(signature); - } - - private static int typeEnd(char[] signature, int pos) { - int depth= 0; - while (pos < signature.length) { - switch (signature[pos]) { - case Signature.C_GENERIC_START: - depth++; - break; - case Signature.C_GENERIC_END: - if (depth == 0) - return pos; - depth--; - break; - case Signature.C_SEMICOLON: - if (depth == 0) - return pos + 1; - break; - } - pos++; - } - return pos + 1; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java deleted file mode 100644 index f73a580f9d..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java +++ /dev/null @@ -1,474 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.util; - -import java.util.Map; - -import org.eclipse.core.runtime.Assert; - -import org.eclipse.text.edits.TextEdit; - -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.Document; -import org.eclipse.jface.text.IRegion; - -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.ToolFactory; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.formatter.CodeFormatter; -import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; - -import org.eclipse.jdt.internal.ui.JavaPlugin; - -public class CodeFormatterUtil { - - /** - * Creates a string that represents the given number of indentation units. - * The returned string can contain tabs and/or spaces depending on the core formatter preferences. - * - * @param indentationUnits - * the number of indentation units to generate - * @param project - * the project from which to get the formatter settings, - * <code>null</code> if the workspace default should be used - * @return the indent string - */ - public static String createIndentString(int indentationUnits, IJavaProject project) { - Map<String, String> options= project != null ? project.getOptions(true) : JavaCore.getOptions(); - return ToolFactory.createCodeFormatter(options).createIndentationString(indentationUnits); - } - - /** - * Gets the current tab width. - * - * @param project - * The project where the source is used, used for project specific options or - * <code>null</code> if the project is unknown and the workspace default should be used - * @return The tab width - */ - public static int getTabWidth(IJavaProject project) { - /* - * If the tab-char is SPACE, FORMATTER_INDENTATION_SIZE is not used - * by the core formatter. - * We piggy back the visual tab length setting in that preference in - * that case. - */ - String key; - if (JavaCore.SPACE.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE; - else - key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE; - - return getCoreOption(project, key, 4); - } - - /** - * Returns the current indent width. - * - * @param project - * the project where the source is used or, - * <code>null</code> if the project is unknown and the workspace default should be used - * @return the indent width - * @since 3.1 - */ - public static int getIndentWidth(IJavaProject project) { - String key; - if (DefaultCodeFormatterConstants.MIXED.equals(getCoreOption(project, DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR))) - key= DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE; - else - key= DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE; - - return getCoreOption(project, key, 4); - } - - /** - * Returns the possibly <code>project</code>-specific core preference defined under <code>key</code>. - * - * @param project - * the project to get the preference from, - * or <code>null</code> to get the global preference - * @param key - * the key of the preference - * @return the value of the preference - * @since 3.1 - */ - private static String getCoreOption(IJavaProject project, String key) { - if (project == null) - return JavaCore.getOption(key); - return project.getOption(key, true); - } - - /** - * Returns the possibly <code>project</code>-specific core preference defined under <code>key</code>, - * or <code>def</code> if the value is not a integer. - * - * @param project - * the project to get the preference from, - * or <code>null</code> to get the global preference - * @param key - * the key of the preference - * @param def - * the default value - * @return the value of the preference - * @since 3.1 - */ - private static int getCoreOption(IJavaProject project, String key, int def) { - try { - return Integer.parseInt(getCoreOption(project, key)); - } catch (NumberFormatException e) { - return def; - } - } - - // transition code - - /** - * Old API. Consider to use format2 (TextEdit) - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param project - * The project from which to retrieve the formatter options from - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return the formatted source string - */ - public static String format(int kind, String source, int indentationLevel, String lineSeparator, IJavaProject project) { - Map<String, String> options= project != null ? project.getOptions(true) : null; - return format(kind, source, indentationLevel, lineSeparator, options); - } - - /** - * Old API. Consider to use format2 (TextEdit) - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return the formatted source string - */ - public static String format(int kind, String source, int indentationLevel, String lineSeparator, Map<String, String> options) { - TextEdit edit= format2(kind, source, indentationLevel, lineSeparator, options); - if (edit == null) { - return source; - } else { - Document document= new Document(source); - try { - edit.apply(document, TextEdit.NONE); - } catch (BadLocationException e) { - JavaPlugin.log(e); // bug in the formatter - Assert.isTrue(false, "Formatter created edits with wrong positions: " + e.getMessage()); //$NON-NLS-1$ - } - return document.get(); - } - } - - /** - * Creates edits that describe how to format the given string. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param offset - * The given offset to start recording the edits (inclusive). - * @param length the given length to stop recording the edits (exclusive). - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException - * If the offset and length are not inside the string, a IllegalArgumentException is thrown. - */ - public static TextEdit format2(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator, Map<String, String> options) { - if (offset < 0 || length < 0 || offset + length > source.length()) { - throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + source.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - return ToolFactory.createCodeFormatter(options).format(kind, source, offset, length, indentationLevel, lineSeparator); - } - - /** - * Creates edits that describe how to format the given string. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException - * If the offset and length are not inside the string, a IllegalArgumentException is thrown. - */ - public static TextEdit format2(int kind, String source, int indentationLevel, String lineSeparator, Map<String, String> options) { - return format2(kind, source, 0, source.length(), indentationLevel, lineSeparator, options); - } - - /** - * Creates edits that describe how to re-format the given string. - * This method should be used for formatting existing code. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param offset - * The given offset to start recording the edits (inclusive). - * @param length the given length to stop recording the edits (exclusive). - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException - * If the offset and length are not inside the string, a IllegalArgumentException is thrown. - */ - public static TextEdit reformat(int kind, String source, int offset, int length, int indentationLevel, String lineSeparator, Map<String, String> options) { - if (offset < 0 || length < 0 || offset + length > source.length()) { - throw new IllegalArgumentException("offset or length outside of string. offset: " + offset + ", length: " + length + ", string size: " + source.length()); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - return ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING).format(kind, source, offset, length, indentationLevel, lineSeparator); - } - - /** - * Creates edits that describe how to re-format the regions in the given string. - * This method should be used for formatting existing code. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * <p>No region in <code>regions</code> must overlap with any other region in <code>regions</code>. - * Each region must be within source. There must be at least one region. Regions must be sorted - * by their offsets, smaller offset first.</p> - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of K_EXPRESSION, K_STATEMENTS, K_CLASS_BODY_DECLARATIONS, K_COMPILATION_UNIT, K_UNKNOWN - * @param source - * The source to format - * @param regions - * a set of regions in the string to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException if there is no region, a region overlaps with another region, or the regions are not - * sorted in the ascending order. - * @since 3.4 - */ - public static TextEdit reformat(int kind, String source, IRegion[] regions, int indentationLevel, String lineSeparator, Map<String, String> options) { - return ToolFactory.createCodeFormatter(options, ToolFactory.M_FORMAT_EXISTING).format(kind, source, regions, indentationLevel, lineSeparator); - } - - /** - * Creates edits that describe how to re-format the given string. - * This method should be used for formatting existing code. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * @param kind - * Use to specify the kind of the code snippet to format. - * It can be any of the kind constants defined in {@link CodeFormatter} - * @param source - * The source to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException - * If the offset and length are not inside the string, a IllegalArgumentException is thrown. - */ - public static TextEdit reformat(int kind, String source, int indentationLevel, String lineSeparator, Map<String, String> options) { - return reformat(kind, source, 0, source.length(), indentationLevel, lineSeparator, options); - } - - /** - * Creates edits that describe how to format the given string. - * The given node is used to infer the kind to use to format the string. - * Consider to use {@link #format2(int, String, int, String, Map)} if the kind is already known. - * Returns <code>null</code> if the code could not be formatted for the given kind. - * - * @param node - * Use to infer the kind of the code snippet to format. - * @param source - * The source to format - * @param indentationLevel - * The initial indentation level, used to shift left/right the entire source fragment. - * An initial indentation level of zero or below has no effect. - * @param lineSeparator - * The line separator to use in formatted source, - * if set to <code>null</code>, then the platform default one will be used. - * @param options - * The options map to use for formatting with the default code formatter. - * Recognized options are documented on {@link JavaCore#getDefaultOptions()}. - * If set to <code>null</code>, then use the current settings from {@link JavaCore#getOptions()}. - * @return an TextEdit describing the changes required to format source - * @throws IllegalArgumentException - * If the offset and length are not inside the string, a IllegalArgumentException is thrown. - */ - public static TextEdit format2(ASTNode node, String source, int indentationLevel, String lineSeparator, Map<String, String> options) { - int code; - String prefix= ""; //$NON-NLS-1$ - String suffix= ""; //$NON-NLS-1$ - if (node instanceof Statement) { - code= CodeFormatter.K_STATEMENTS; - if (node.getNodeType() == ASTNode.SWITCH_CASE) { - prefix= "switch(1) {"; //$NON-NLS-1$ - suffix= "}"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - } - } else if (node instanceof Expression && node.getNodeType() != ASTNode.VARIABLE_DECLARATION_EXPRESSION) { - code= CodeFormatter.K_EXPRESSION; - } else if (node instanceof BodyDeclaration) { - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - } else { - switch (node.getNodeType()) { - case ASTNode.ARRAY_TYPE: - case ASTNode.PARAMETERIZED_TYPE: - case ASTNode.PRIMITIVE_TYPE: - case ASTNode.QUALIFIED_TYPE: - case ASTNode.SIMPLE_TYPE: - suffix= " x;"; //$NON-NLS-1$ - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - break; - case ASTNode.WILDCARD_TYPE: - prefix= "A<"; //$NON-NLS-1$ - suffix= "> x;"; //$NON-NLS-1$ - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - break; - case ASTNode.COMPILATION_UNIT: - code= CodeFormatter.K_COMPILATION_UNIT; - break; - case ASTNode.VARIABLE_DECLARATION_EXPRESSION: - case ASTNode.SINGLE_VARIABLE_DECLARATION: - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.VARIABLE_DECLARATION_FRAGMENT: - prefix= "A "; //$NON-NLS-1$ - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.PACKAGE_DECLARATION: - case ASTNode.IMPORT_DECLARATION: - suffix= "\nclass A {}"; //$NON-NLS-1$ - code= CodeFormatter.K_COMPILATION_UNIT; - break; - case ASTNode.JAVADOC: - suffix= "void foo();"; //$NON-NLS-1$ - code= CodeFormatter.K_CLASS_BODY_DECLARATIONS; - break; - case ASTNode.CATCH_CLAUSE: - prefix= "try {}"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.ANONYMOUS_CLASS_DECLARATION: - prefix= "new A()"; //$NON-NLS-1$ - suffix= ";"; //$NON-NLS-1$ - code= CodeFormatter.K_STATEMENTS; - break; - case ASTNode.MEMBER_VALUE_PAIR: - prefix= "@Author("; //$NON-NLS-1$ - suffix= ") class x {}"; //$NON-NLS-1$ - code= CodeFormatter.K_COMPILATION_UNIT; - break; - case ASTNode.MODIFIER: - suffix= " class x {}"; //$NON-NLS-1$ - code= CodeFormatter.K_COMPILATION_UNIT; - break; - case ASTNode.TYPE_PARAMETER: - prefix= "class X<"; //$NON-NLS-1$ - suffix= "> {}"; //$NON-NLS-1$ - code= CodeFormatter.K_COMPILATION_UNIT; - break; - case ASTNode.MEMBER_REF: - case ASTNode.METHOD_REF: - case ASTNode.METHOD_REF_PARAMETER: - case ASTNode.TAG_ELEMENT: - case ASTNode.TEXT_ELEMENT: - // Javadoc formatting not yet supported: - return null; - default: - //Assert.isTrue(false, "Node type not covered: " + node.getClass().getName()); //$NON-NLS-1$ - return null; - } - } - - String concatStr= prefix + source + suffix; - TextEdit edit= format2(code, concatStr, prefix.length(), source.length(), indentationLevel, lineSeparator, options); - if (edit != null && prefix.length() > 0) { - edit.moveTree(-prefix.length()); - } - return edit; - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/History.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/History.java index af3c19fdf5..25a44dd794 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/History.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/History.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2015 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -52,7 +52,7 @@ import org.eclipse.jdt.internal.corext.CorextMessages; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIException; import org.eclipse.jdt.internal.ui.JavaUIStatus; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; /** * History stores a list of key, object pairs. The list is bounded at size diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java index b5a998e78c..eba8901950 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JDTUIHelperClasses.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2013 IBM Corporation and others. + * Copyright (c) 2013, 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 v1.0 * which accompanies this distribution, and is available at @@ -34,11 +34,19 @@ import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; -import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; - /** * The org.eclipse.jdt.ui bundle contains a few internal helper classes that simplify - * common tasks when dealing with JDT Core or UI APIs. Here's a list of the most important ones: + * common tasks when dealing with JDT Core or UI APIs. With bug 508777, many of these + * classes have been moved to the org.eclipse.jdt.core.manipulation bundle. We've kept + * the original package/class names to reduce binary compatibility problems for bundles + * that illegally accessed these classes. + * <p> + * Some classes had to be split in two. They are listed with fully-qualified names here. + * Back-links in Javadoc from classes in org.eclipse.jdt.core.manipulation to this + * class are not possible, so we use line comments there: // @see JDTUIHelperClasses + * </p> + * + * Here's a list of the most important helper classes: * * <h2>Java Model</h2> * <p> @@ -77,7 +85,8 @@ import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; * <ul> * <li>{@link ASTNodes}</li> * <li>{@link ASTNodeSearchUtil}</li> - * <li>{@link ASTResolving}</li> + * <li>{@link org.eclipse.jdt.internal.ui.text.correction.ASTResolving}</li> + * <li>{@link org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving}</li> * <li>{@link Bindings}</li> * <li>{@link TypeRules}</li> * </ul> @@ -112,6 +121,16 @@ import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; * <li>{@link VariableDeclarationRewrite}</li> * </ul> * + * <p> + * Label and text manipulation helpers: + * </p> + * <ul> + * <li>{@link org.eclipse.jdt.internal.corext.util.Strings}</li> + * <li>{@link org.eclipse.jdt.internal.core.manipulation.util.Strings}</li> + * <li>{@link org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels}</li> + * <li>{@link org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels}</li> + * </ul> + * * @noreference This class is not intended to be referenced by clients */ public final class JDTUIHelperClasses { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java deleted file mode 100644 index dccce34fbb..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java +++ /dev/null @@ -1,959 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Matt Chapman, mpchapman@gmail.com - 89977 Make JDT .java agnostic - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.util; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; -import org.eclipse.core.runtime.CoreException; -import org.eclipse.core.runtime.IPath; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.SubMonitor; - -import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IStorage; - -import org.eclipse.text.edits.TextEdit; - -import org.eclipse.jdt.core.ClasspathContainerInitializer; -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IClasspathContainer; -import org.eclipse.jdt.core.IClasspathEntry; -import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IField; -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.IType; -import org.eclipse.jdt.core.ITypeHierarchy; -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.core.compiler.CharOperation; - -import org.eclipse.jdt.internal.corext.CorextMessages; -import org.eclipse.jdt.internal.corext.ValidateEditException; - -import org.eclipse.jdt.launching.IVMInstall; -import org.eclipse.jdt.launching.IVMInstall2; -import org.eclipse.jdt.launching.JavaRuntime; -import org.eclipse.jdt.launching.environments.IExecutionEnvironment; - -/** - * Utility methods for the Java Model. - * - * @see JDTUIHelperClasses - */ -public final class JavaModelUtil { - - /** - * The latest available {@link JavaCore}{@code #VERSION_*} level. - * @since 3.7 - */ - public static final String VERSION_LATEST; - static { - VERSION_LATEST= JavaCore.VERSION_1_8; // make sure it is not inlined - } - - /** - * Only use this suffix for creating new .java files. - * In general, use one of the three *JavaLike*(..) methods in JavaCore or create - * a name from an existing compilation unit with {@link #getRenamedCUName(ICompilationUnit, String)} - * <p> - * Note: Unlike {@link JavaCore#getJavaLikeExtensions()}, this suffix includes a leading ".". - * </p> - * - * @see JavaCore#getJavaLikeExtensions() - * @see JavaCore#isJavaLikeFileName(String) - * @see JavaCore#removeJavaLikeExtension(String) - * @see #getRenamedCUName(ICompilationUnit, String) - */ - public static final String DEFAULT_CU_SUFFIX= ".java"; //$NON-NLS-1$ - - /** - * The name of the package-info.java file. - * @since 3.8 - */ - public static final String PACKAGE_INFO_JAVA= "package-info.java"; //$NON-NLS-1$ - - /** - * The name of the package-info.class file. - * @since 3.9 - */ - public static final String PACKAGE_INFO_CLASS= "package-info.class"; //$NON-NLS-1$ - - /** - * The name of the package.html file. - * @since 3.9 - */ - public static final String PACKAGE_HTML= "package.html"; //$NON-NLS-1$ - - /** - * Finds a type container by container name. The returned element will be of type - * <code>IType</code> or a <code>IPackageFragment</code>. <code>null</code> is returned if the - * type container could not be found. - * - * @param jproject The Java project defining the context to search - * @param typeContainerName A dot separated name of the type container - * @return returns the container - * @throws JavaModelException thrown when the project can not be accessed - * @see #getTypeContainerName(IType) - */ - public static IJavaElement findTypeContainer(IJavaProject jproject, String typeContainerName) throws JavaModelException { - // try to find it as type - IJavaElement result= jproject.findType(typeContainerName); - if (result == null) { - // find it as package - IPath path= new Path(typeContainerName.replace('.', '/')); - result= jproject.findElement(path); - if (!(result instanceof IPackageFragment)) { - result= null; - } - - } - return result; - } - - /** - * Finds a type in a compilation unit. Typical usage is to find the corresponding - * type in a working copy. - * @param cu the compilation unit to search in - * @param typeQualifiedName the type qualified name (type name with enclosing type names (separated by dots)) - * @return the type found, or null if not existing - * @throws JavaModelException thrown when the cu can not be accessed - */ - public static IType findTypeInCompilationUnit(ICompilationUnit cu, String typeQualifiedName) throws JavaModelException { - IType[] types= cu.getAllTypes(); - for (int i= 0; i < types.length; i++) { - String currName= types[i].getTypeQualifiedName('.'); - if (typeQualifiedName.equals(currName)) { - return types[i]; - } - } - return null; - } - - /** - * Returns the element of the given compilation unit which is "equal" to the - * given element. Note that the given element usually has a parent different - * from the given compilation unit. - * - * @param cu the cu to search in - * @param element the element to look for - * @return an element of the given cu "equal" to the given element - */ - public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) { - IJavaElement[] elements= cu.findElements(element); - if (elements != null && elements.length > 0) { - return elements[0]; - } - return null; - } - - /** - * Returns the fully qualified name of a type's container. (package name or enclosing type name) - * @param type the type - * @return the type container name - */ - public static String getTypeContainerName(IType type) { - IType outerType= type.getDeclaringType(); - if (outerType != null) { - return outerType.getFullyQualifiedName('.'); - } else { - return type.getPackageFragment().getElementName(); - } - } - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - * @param name1 the first name - * @param name2 the second name - * @return the concatenated name - */ - public static String concatenateName(String name1, String name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length() > 0) { - buf.append(name1); - } - if (name2 != null && name2.length() > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Concatenates two names. Uses a dot for separation. - * Both strings can be empty or <code>null</code>. - * @param name1 the first string - * @param name2 the second string - * @return the concatenated string - */ - public static String concatenateName(char[] name1, char[] name2) { - StringBuffer buf= new StringBuffer(); - if (name1 != null && name1.length > 0) { - buf.append(name1); - } - if (name2 != null && name2.length > 0) { - if (buf.length() > 0) { - buf.append('.'); - } - buf.append(name2); - } - return buf.toString(); - } - - /** - * Returns whether the two names match. They match if they - * are equal, or if they are the same name but one is missing a dot-separated qualifier. - * - * @param nameA a potentially qualified name - * @param nameB a potentially qualified name - * @return <code>true</code> iff the given names match - * @since 3.8 - */ - public static boolean isMatchingName(String nameA, String nameB) { - int a= nameA.length(); - int b= nameB.length(); - if (a == b) { - return nameA.equals(nameB); - } else if (a < b - 1) { - return nameB.endsWith(nameA) && nameB.charAt(b - a - 1) == '.'; - } else if (b < a - 1) { - return nameA.endsWith(nameB) && nameA.charAt(a - b - 1) == '.'; - } else { - return false; - } - } - - /** - * Evaluates if a member (possible from another package) is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package in focus - * @return returns <code>true</code> if the member is visible from the package - * @throws JavaModelException thrown when the member can not be accessed - */ - public static boolean isVisible(IMember member, IPackageFragment pack) throws JavaModelException { - - int type= member.getElementType(); - if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - - int otherflags= member.getFlags(); - IType declaringType= member.getDeclaringType(); - if (Flags.isPublic(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { - return true; - } else if (Flags.isPrivate(otherflags)) { - return false; - } - - IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - return (pack != null && otherpack != null && isSamePackage(pack, otherpack)); - } - - /** - * Evaluates if a member in the focus' element hierarchy is visible from - * elements in a package. - * @param member The member to test the visibility for - * @param pack The package of the focus element focus - * @return returns <code>true</code> if the member is visible from the package - * @throws JavaModelException thrown when the member can not be accessed - */ - public static boolean isVisibleInHierarchy(IMember member, IPackageFragment pack) throws JavaModelException { - int type= member.getElementType(); - if (type == IJavaElement.INITIALIZER || (type == IJavaElement.METHOD && member.getElementName().startsWith("<"))) { //$NON-NLS-1$ - return false; - } - - int otherflags= member.getFlags(); - - IType declaringType= member.getDeclaringType(); - if (Flags.isPublic(otherflags) || Flags.isProtected(otherflags) || (declaringType != null && isInterfaceOrAnnotation(declaringType))) { - return true; - } else if (Flags.isPrivate(otherflags)) { - return false; - } - - IPackageFragment otherpack= (IPackageFragment) member.getAncestor(IJavaElement.PACKAGE_FRAGMENT); - return (pack != null && pack.equals(otherpack)); - } - - - /** - * Returns the package fragment root of <code>IJavaElement</code>. If the given - * element is already a package fragment root, the element itself is returned. - * @param element the element - * @return the package fragment root of the element or <code>null</code> - */ - public static IPackageFragmentRoot getPackageFragmentRoot(IJavaElement element) { - return (IPackageFragmentRoot) element.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); - } - - /** - * Finds a method in a type. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @param type the type - * @return The first found method or <code>null</code>, if nothing foun - * @throws JavaModelException thrown when the type can not be accessed - */ - public static IMethod findMethod(String name, String[] paramTypes, boolean isConstructor, IType type) throws JavaModelException { - IMethod[] methods= type.getMethods(); - for (int i= 0; i < methods.length; i++) { - if (isSameMethodSignature(name, paramTypes, isConstructor, methods[i])) { - return methods[i]; - } - } - return null; - } - - /** - * Finds a method in a type and all its super types. The super class hierarchy is searched first, then the super interfaces. - * This searches for a method with the same name and signature. Parameter types are only - * compared by the simple name, no resolving for the fully qualified type name is done. - * Constructors are only compared by parameters, not the name. - * NOTE: For finding overridden methods or for finding the declaring method, use {@link MethodOverrideTester} - * @param hierarchy The hierarchy containing the type - * @param type The type to start the search from - * @param name The name of the method to find - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor If the method is a constructor - * @return The first found method or <code>null</code>, if nothing found - * @throws JavaModelException thrown when the type can not be accessed - */ - public static IMethod findMethodInHierarchy(ITypeHierarchy hierarchy, IType type, String name, String[] paramTypes, boolean isConstructor) throws JavaModelException { - IMethod method= findMethod(name, paramTypes, isConstructor, type); - if (method != null) { - return method; - } - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null) { - IMethod res= findMethodInHierarchy(hierarchy, superClass, name, paramTypes, isConstructor); - if (res != null) { - return res; - } - } - if (!isConstructor) { - IType[] superInterfaces= hierarchy.getSuperInterfaces(type); - for (int i= 0; i < superInterfaces.length; i++) { - IMethod res= findMethodInHierarchy(hierarchy, superInterfaces[i], name, paramTypes, false); - if (res != null) { - return res; - } - } - } - return method; - } - - - /** - * Tests if a method equals to the given signature. - * Parameter types are only compared by the simple name, no resolving for - * the fully qualified type name is done. Constructors are only compared by - * parameters, not the name. - * @param name Name of the method - * @param paramTypes The type signatures of the parameters e.g. <code>{"QString;","I"}</code> - * @param isConstructor Specifies if the method is a constructor - * @param curr the method - * @return Returns <code>true</code> if the method has the given name and parameter types and constructor state. - * @throws JavaModelException thrown when the method can not be accessed - */ - public static boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod curr) throws JavaModelException { - if (isConstructor || name.equals(curr.getElementName())) { - if (isConstructor == curr.isConstructor()) { - String[] currParamTypes= curr.getParameterTypes(); - if (paramTypes.length == currParamTypes.length) { - for (int i= 0; i < paramTypes.length; i++) { - String t1= Signature.getSimpleName(Signature.toString(paramTypes[i])); - String t2= Signature.getSimpleName(Signature.toString(currParamTypes[i])); - if (!t1.equals(t2)) { - return false; - } - } - return true; - } - } - } - return false; - } - - /** - * Tests if two <code>IPackageFragment</code>s represent the same logical java package. - * @param pack1 the first package - * @param pack2 the second package - * @return <code>true</code> if the package fragments' names are equal. - */ - public static boolean isSamePackage(IPackageFragment pack1, IPackageFragment pack2) { - return pack1.getElementName().equals(pack2.getElementName()); - } - - /** - * Checks whether the given type has a valid main method or not. - * @param type the type to test - * @return returns <code>true</code> if the type has a main method - * @throws JavaModelException thrown when the type can not be accessed - */ - public static boolean hasMainMethod(IType type) throws JavaModelException { - IMethod[] methods= type.getMethods(); - for (int i= 0; i < methods.length; i++) { - if (methods[i].isMainMethod()) { - return true; - } - } - return false; - } - - /** - * Checks if the field is boolean. - * @param field the field - * @return returns <code>true</code> if the field returns a boolean - * @throws JavaModelException thrown when the field can not be accessed - */ - public static boolean isBoolean(IField field) throws JavaModelException{ - return field.getTypeSignature().equals(Signature.SIG_BOOLEAN); - } - - /** - * @param type the type to test - * @return <code>true</code> iff the type is an interface or an annotation - * @throws JavaModelException thrown when the field can not be accessed - */ - public static boolean isInterfaceOrAnnotation(IType type) throws JavaModelException { - return type.isInterface(); - } - - /** - * Resolves a type name in the context of the declaring type. - * - * @param refTypeSig the type name in signature notation (for example 'QVector') this can also be an array type, but dimensions will be ignored. - * @param declaringType the context for resolving (type where the reference was made in) - * @return returns the fully qualified type name or build-in-type name. if a unresolved type couldn't be resolved null is returned - * @throws JavaModelException thrown when the type can not be accessed - */ - public static String getResolvedTypeName(String refTypeSig, IType declaringType) throws JavaModelException { - int arrayCount= Signature.getArrayCount(refTypeSig); - char type= refTypeSig.charAt(arrayCount); - if (type == Signature.C_UNRESOLVED) { - String name= ""; //$NON-NLS-1$ - int bracket= refTypeSig.indexOf(Signature.C_GENERIC_START, arrayCount + 1); - if (bracket > 0) - name= refTypeSig.substring(arrayCount + 1, bracket); - else { - int semi= refTypeSig.indexOf(Signature.C_SEMICOLON, arrayCount + 1); - if (semi == -1) { - throw new IllegalArgumentException(); - } - name= refTypeSig.substring(arrayCount + 1, semi); - } - String[][] resolvedNames= declaringType.resolveType(name); - if (resolvedNames != null && resolvedNames.length > 0) { - return JavaModelUtil.concatenateName(resolvedNames[0][0], resolvedNames[0][1]); - } - return null; - } else { - return Signature.toString(refTypeSig.substring(arrayCount)); - } - } - - /** - * Returns if a CU can be edited. - * @param cu the compilation unit - * @return <code>true</code> if the CU can be edited - */ - public static boolean isEditable(ICompilationUnit cu) { - Assert.isNotNull(cu); - IResource resource= cu.getPrimary().getResource(); - return (resource.exists() && !resource.getResourceAttributes().isReadOnly()); - } - - /** - * Returns true if a cu is a primary cu (original or shared working copy) - * @param cu the compilation unit - * @return return <code>true</code> if the CU is primary - */ - public static boolean isPrimary(ICompilationUnit cu) { - return cu.getOwner() == null; - } - - /** - * Checks whether the given type signature is from a primitive type. - * - * @param typeSignature the type signature string to check - * @return <code>true</code> if the type is a primitive type, <code> false</code> otherwise - * @throws JavaModelException if this element does not exist or if an exception occurs while - * accessing its corresponding resource. - * @since 3.7 - */ - public static boolean isPrimitive(String typeSignature) throws JavaModelException { - return Signature.getTypeSignatureKind(Signature.getElementType(typeSignature)) == Signature.BASE_TYPE_SIGNATURE; - } - - /* - * Don't log not-exists exceptions - * - * Also see bug http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253. - * Since 3.4 we also don't log non-exists exception in non-working copies. - */ - public static boolean isExceptionToBeLogged(CoreException exception) { - if (!(exception instanceof JavaModelException)) - return true; - JavaModelException je= (JavaModelException)exception; - if (!je.isDoesNotExist()) - return true; - return false; - } - - public static IType[] getAllSuperTypes(IType type, IProgressMonitor pm) throws JavaModelException { - try { - // workaround for 23656 - IType[] superTypes= SuperTypeHierarchyCache.getTypeHierarchy(type).getAllSupertypes(type); - if (type.isInterface()) { - IType objekt= type.getJavaProject().findType("java.lang.Object");//$NON-NLS-1$ - if (objekt != null) { - IType[] superInterfacesAndObject= new IType[superTypes.length + 1]; - System.arraycopy(superTypes, 0, superInterfacesAndObject, 0, superTypes.length); - superInterfacesAndObject[superTypes.length]= objekt; - return superInterfacesAndObject; - } - } - return superTypes; - } finally { - if (pm != null) - pm.done(); - } - } - - public static boolean isSuperType(ITypeHierarchy hierarchy, IType possibleSuperType, IType type) { - // filed bug 112635 to add this method to ITypeHierarchy - IType superClass= hierarchy.getSuperclass(type); - if (superClass != null && (possibleSuperType.equals(superClass) || isSuperType(hierarchy, possibleSuperType, superClass))) { - return true; - } - if (Flags.isInterface(hierarchy.getCachedFlags(possibleSuperType))) { - IType[] superInterfaces= hierarchy.getSuperInterfaces(type); - for (int i= 0; i < superInterfaces.length; i++) { - IType curr= superInterfaces[i]; - if (possibleSuperType.equals(curr) || isSuperType(hierarchy, possibleSuperType, curr)) { - return true; - } - } - } - return false; - } - - public static boolean isExcludedPath(IPath resourcePath, IPath[] exclusionPatterns) { - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) { - char[] pattern= exclusionPatterns[i].toString().toCharArray(); - if (CharOperation.pathMatch(pattern, path, true, '/')) { - return true; - } - } - return false; - } - - - /** - * Returns whether the given resource path matches one of the exclusion - * patterns. - * @param resourcePath the resource path - * @param exclusionPatterns the exclusion patterns - * @return returns <code> true</code> if the given resource path matches one of the exclusion - * - * @see IClasspathEntry#getExclusionPatterns - */ - public static boolean isExcluded(IPath resourcePath, char[][] exclusionPatterns) { - if (exclusionPatterns == null) return false; - char[] path = resourcePath.toString().toCharArray(); - for (int i = 0, length = exclusionPatterns.length; i < length; i++) - if (CharOperation.pathMatch(exclusionPatterns[i], path, true, '/')) - return true; - return false; - } - - - /** - * Force a reconcile of a compilation unit. - * @param unit the compilation unit - * @throws JavaModelException thrown when the compilation unit can not be accessed - */ - public static void reconcile(ICompilationUnit unit) throws JavaModelException { - unit.reconcile( - ICompilationUnit.NO_AST, - false /* don't force problem detection */, - null /* use primary owner */, - null /* no progress monitor */); - } - - /** - * Helper method that tests if an classpath entry can be found in a - * container. <code>null</code> is returned if the entry can not be found - * or if the container does not allows the configuration of source - * attachments - * @param jproject The container's parent project - * @param containerPath The path of the container - * @param libPath The path of the library to be found - * @return IClasspathEntry A classpath entry from the container of - * <code>null</code> if the container can not be modified. - * @throws JavaModelException thrown if accessing the container failed - */ - public static IClasspathEntry getClasspathEntryToEdit(IJavaProject jproject, IPath containerPath, IPath libPath) throws JavaModelException { - IClasspathContainer container= JavaCore.getClasspathContainer(containerPath, jproject); - ClasspathContainerInitializer initializer= JavaCore.getClasspathContainerInitializer(containerPath.segment(0)); - if (container != null && initializer != null && initializer.canUpdateClasspathContainer(containerPath, jproject)) { - return findEntryInContainer(container, libPath); - } - return null; // attachment not possible - } - - /** - * Finds an entry in a container. <code>null</code> is returned if the entry can not be found - * @param container The container - * @param libPath The path of the library to be found - * @return IClasspathEntry A classpath entry from the container of - * <code>null</code> if the container can not be modified. - */ - public static IClasspathEntry findEntryInContainer(IClasspathContainer container, IPath libPath) { - IClasspathEntry[] entries= container.getClasspathEntries(); - for (int i= 0; i < entries.length; i++) { - IClasspathEntry curr= entries[i]; - IClasspathEntry resolved= JavaCore.getResolvedClasspathEntry(curr); - if (resolved != null && libPath.equals(resolved.getPath())) { - return curr; // return the real entry - } - } - return null; // attachment not possible - } - - /** - * Returns the classpath entry of the given package fragment root. This is the raw entry, except - * if the root is a referenced library, in which case it's the resolved entry. - * - * @param root a package fragment root - * @return the corresponding classpath entry - * @throws JavaModelException if accessing the entry failed - * @since 3.6 - */ - public static IClasspathEntry getClasspathEntry(IPackageFragmentRoot root) throws JavaModelException { - IClasspathEntry rawEntry= root.getRawClasspathEntry(); - int rawEntryKind= rawEntry.getEntryKind(); - switch (rawEntryKind) { - case IClasspathEntry.CPE_LIBRARY: - case IClasspathEntry.CPE_VARIABLE: - case IClasspathEntry.CPE_CONTAINER: // should not happen, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=305037 - if (root.isArchive() && root.getKind() == IPackageFragmentRoot.K_BINARY) { - IClasspathEntry resolvedEntry= root.getResolvedClasspathEntry(); - if (resolvedEntry.getReferencingEntry() != null) - return resolvedEntry; - else - return rawEntry; - } - } - return rawEntry; - } - - /** - * Get all compilation units of a selection. - * - * @param javaElements the selected java elements - * @return all compilation units containing and contained in elements from javaElements - * @throws JavaModelException if this element does not exist or if an exception occurs while - * accessing its corresponding resource - */ - public static ICompilationUnit[] getAllCompilationUnits(IJavaElement[] javaElements) throws JavaModelException { - HashSet<ICompilationUnit> result= new HashSet<>(); - for (int i= 0; i < javaElements.length; i++) { - addAllCus(result, javaElements[i]); - } - return result.toArray(new ICompilationUnit[result.size()]); - } - - private static void addAllCus(HashSet<ICompilationUnit> collector, IJavaElement javaElement) throws JavaModelException { - switch (javaElement.getElementType()) { - case IJavaElement.JAVA_PROJECT: - IJavaProject javaProject= (IJavaProject) javaElement; - IPackageFragmentRoot[] packageFragmentRoots= javaProject.getPackageFragmentRoots(); - for (int i= 0; i < packageFragmentRoots.length; i++) - addAllCus(collector, packageFragmentRoots[i]); - return; - - case IJavaElement.PACKAGE_FRAGMENT_ROOT: - IPackageFragmentRoot packageFragmentRoot= (IPackageFragmentRoot) javaElement; - if (packageFragmentRoot.getKind() != IPackageFragmentRoot.K_SOURCE) - return; - IJavaElement[] packageFragments= packageFragmentRoot.getChildren(); - for (int j= 0; j < packageFragments.length; j++) - addAllCus(collector, packageFragments[j]); - return; - - case IJavaElement.PACKAGE_FRAGMENT: - IPackageFragment packageFragment= (IPackageFragment) javaElement; - collector.addAll(Arrays.asList(packageFragment.getCompilationUnits())); - return; - - case IJavaElement.COMPILATION_UNIT: - collector.add((ICompilationUnit) javaElement); - return; - - default: - IJavaElement cu= javaElement.getAncestor(IJavaElement.COMPILATION_UNIT); - if (cu != null) - collector.add((ICompilationUnit) cu); - } - } - - - public static void setComplianceOptions(Map<String, String> map, String compliance) { - JavaCore.setComplianceOptions(compliance, map); - } - - public static void setDefaultClassfileOptions(Map<String, String> map, String compliance) { - map.put(JavaCore.COMPILER_CODEGEN_INLINE_JSR_BYTECODE, is50OrHigher(compliance) ? JavaCore.ENABLED : JavaCore.DISABLED); - map.put(JavaCore.COMPILER_LOCAL_VARIABLE_ATTR, JavaCore.GENERATE); - map.put(JavaCore.COMPILER_LINE_NUMBER_ATTR, JavaCore.GENERATE); - map.put(JavaCore.COMPILER_SOURCE_FILE_ATTR, JavaCore.GENERATE); - map.put(JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL, JavaCore.PRESERVE); - } - - /** - * @param version1 the first version - * @param version2 the second version - * @return <code>true</code> iff version1 is less than version2 - */ - public static boolean isVersionLessThan(String version1, String version2) { - if (JavaCore.VERSION_CLDC_1_1.equals(version1)) { - version1= JavaCore.VERSION_1_1 + 'a'; - } - if (JavaCore.VERSION_CLDC_1_1.equals(version2)) { - version2= JavaCore.VERSION_1_1 + 'a'; - } - return version1.compareTo(version2) < 0; - } - - - public static boolean is50OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_5); - } - - public static boolean is17OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_7); - } - - public static boolean is18OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_8); - } - - /** - * Checks if the given project or workspace has source compliance 1.5 or greater. - * - * @param project the project to test or <code>null</code> to test the workspace settings - * @return <code>true</code> if the given project or workspace has source compliance 1.5 or greater. - */ - public static boolean is50OrHigher(IJavaProject project) { - return is50OrHigher(getSourceCompliance(project)); - } - - /** - * Checks if the given project or workspace has source compliance 1.7 or greater. - * - * @param project the project to test or <code>null</code> to test the workspace settings - * @return <code>true</code> if the given project or workspace has source compliance 1.7 or greater. - */ - public static boolean is17OrHigher(IJavaProject project) { - return is17OrHigher(getSourceCompliance(project)); - } - - /** - * Checks if the given project or workspace has source compliance 1.8 or greater. - * - * @param project the project to test or <code>null</code> to test the workspace settings - * @return <code>true</code> if the given project or workspace has source compliance 1.8 or - * greater. - */ - public static boolean is18OrHigher(IJavaProject project) { - return is18OrHigher(getSourceCompliance(project)); - } - - private static String getSourceCompliance(IJavaProject project) { - return project != null ? project.getOption(JavaCore.COMPILER_SOURCE, true) : JavaCore.getOption(JavaCore.COMPILER_SOURCE); - } - - /** - * Checks if the JRE of the given project or workspace default JRE have source compliance 1.5 or - * greater. - * - * @param project the project to test or <code>null</code> to test the workspace JRE - * @return <code>true</code> if the JRE of the given project or workspace default JRE have - * source compliance 1.5 or greater. - * @throws CoreException if unable to determine the project's VM install - */ - public static boolean is50OrHigherJRE(IJavaProject project) throws CoreException { - IVMInstall vmInstall; - if (project == null) { - vmInstall= JavaRuntime.getDefaultVMInstall(); - } else { - vmInstall= JavaRuntime.getVMInstall(project); - } - if (!(vmInstall instanceof IVMInstall2)) - return true; // assume 1.5. - - String compliance= getCompilerCompliance((IVMInstall2) vmInstall, null); - if (compliance == null) - return true; // assume 1.5 - return is50OrHigher(compliance); - } - - public static String getCompilerCompliance(IVMInstall2 vMInstall, String defaultCompliance) { - String version= vMInstall.getJavaVersion(); - if (version == null) { - return defaultCompliance; - } else if (version.startsWith(JavaCore.VERSION_1_8)) { - return JavaCore.VERSION_1_8; - } else if (version.startsWith(JavaCore.VERSION_1_7)) { - return JavaCore.VERSION_1_7; - } else if (version.startsWith(JavaCore.VERSION_1_6)) { - return JavaCore.VERSION_1_6; - } else if (version.startsWith(JavaCore.VERSION_1_5)) { - return JavaCore.VERSION_1_5; - } else if (version.startsWith(JavaCore.VERSION_1_4)) { - return JavaCore.VERSION_1_4; - } else if (version.startsWith(JavaCore.VERSION_1_3)) { - return JavaCore.VERSION_1_3; - } else if (version.startsWith(JavaCore.VERSION_1_2)) { - return JavaCore.VERSION_1_3; - } else if (version.startsWith(JavaCore.VERSION_1_1)) { - return JavaCore.VERSION_1_3; - } - return defaultCompliance; - } - - public static String getExecutionEnvironmentCompliance(IExecutionEnvironment executionEnvironment) { - Map<String, String> complianceOptions= executionEnvironment.getComplianceOptions(); - if (complianceOptions != null) { - Object compliance= complianceOptions.get(JavaCore.COMPILER_COMPLIANCE); - if (compliance instanceof String) - return (String)compliance; - } - - // fallback: - String desc= executionEnvironment.getId(); - if (desc.indexOf(JavaCore.VERSION_1_8) != -1) { - return JavaCore.VERSION_1_8; - } else if (desc.indexOf(JavaCore.VERSION_1_7) != -1) { - return JavaCore.VERSION_1_7; - } else if (desc.indexOf(JavaCore.VERSION_1_6) != -1) { - return JavaCore.VERSION_1_6; - } else if (desc.indexOf(JavaCore.VERSION_1_5) != -1) { - return JavaCore.VERSION_1_5; - } else if (desc.indexOf(JavaCore.VERSION_1_4) != -1) { - return JavaCore.VERSION_1_4; - } - return JavaCore.VERSION_1_3; - } - - /** - * Compute a new name for a compilation unit, given the name of the new main type. - * This query tries to maintain the existing extension (e.g. ".java"). - * - * @param cu a compilation unit - * @param newMainName the new name of the cu's main type (without extension) - * @return the new name for the compilation unit - */ - public static String getRenamedCUName(ICompilationUnit cu, String newMainName) { - String oldName = cu.getElementName(); - int i = oldName.lastIndexOf('.'); - if (i != -1) { - return newMainName + oldName.substring(i); - } else { - return newMainName; - } - } - - /** - * Applies an text edit to a compilation unit. Filed bug 117694 against jdt.core. - * @param cu the compilation unit to apply the edit to - * @param edit the edit to apply - * @param save is set, save the CU after the edit has been applied - * @param monitor the progress monitor to use - * @throws CoreException Thrown when the access to the CU failed - * @throws ValidateEditException if validate edit fails - */ - public static void applyEdit(ICompilationUnit cu, TextEdit edit, boolean save, IProgressMonitor monitor) throws CoreException, ValidateEditException { - SubMonitor subMonitor= SubMonitor.convert(monitor, CorextMessages.JavaModelUtil_applyedit_operation, 2); - IFile file= (IFile) cu.getResource(); - if (!save || !file.exists()) { - cu.applyTextEdit(edit, subMonitor.split(2)); - } else { - IStatus status= Resources.makeCommittable(file, null); - if (!status.isOK()) { - throw new ValidateEditException(status); - } - cu.applyTextEdit(edit, subMonitor.split(1)); - cu.save(subMonitor.split(1), true); - } - } - - public static boolean isImplicitImport(String qualifier, ICompilationUnit cu) { - if ("java.lang".equals(qualifier)) { //$NON-NLS-1$ - return true; - } - String packageName= cu.getParent().getElementName(); - if (qualifier.equals(packageName)) { - return true; - } - String typeName= JavaCore.removeJavaLikeExtension(cu.getElementName()); - String mainTypeName= JavaModelUtil.concatenateName(packageName, typeName); - return qualifier.equals(mainTypeName); - } - - public static boolean isOpenableStorage(Object storage) { - if (storage instanceof IJarEntryResource) { - return ((IJarEntryResource) storage).isFile(); - } else { - return storage instanceof IStorage; - } - } - - /** - * Tells whether the given CU is the package-info.java. - * - * @param cu the compilation unit to test - * @return <code>true</code> if the given CU is the package-info.java - * @since 3.4 - */ - public static boolean isPackageInfo(ICompilationUnit cu) { - return PACKAGE_INFO_JAVA.equals(cu.getElementName()); - } - - public static boolean isPolymorphicSignature(IMethod method) { - return method.getAnnotation("java.lang.invoke.MethodHandle$PolymorphicSignature").exists(); //$NON-NLS-1$ - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java deleted file mode 100644 index 3d538cace0..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/JdtFlags.java +++ /dev/null @@ -1,426 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - * Rabea Gransberger <rgransberger@gmx.de> - [quick fix] Fix several visibility issues - https://bugs.eclipse.org/394692 - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.util; - -import org.eclipse.core.runtime.Assert; - -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IField; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IMember; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; -import org.eclipse.jdt.core.dom.AnnotationTypeDeclaration; -import org.eclipse.jdt.core.dom.BodyDeclaration; -import org.eclipse.jdt.core.dom.EnumConstantDeclaration; -import org.eclipse.jdt.core.dom.EnumDeclaration; -import org.eclipse.jdt.core.dom.IBinding; -import org.eclipse.jdt.core.dom.IMethodBinding; -import org.eclipse.jdt.core.dom.ITypeBinding; -import org.eclipse.jdt.core.dom.IVariableBinding; -import org.eclipse.jdt.core.dom.Modifier; -import org.eclipse.jdt.core.dom.TypeDeclaration; - - -/** - * Java element flags from a Java language model point of view. - * <p> - * {@link IMember#getFlags()} (and hence {@link Flags}) only take explicitly declared flags - * from source into account. - * This class also considers the implicit properties as defined in the Java Language Specification. - * </p> - * <p> - * <code>JdtFlags</code> is the right choice for most analysis tasks and for presentation in the UI. - * </p> - * - * @see JDTUIHelperClasses - */ -public class JdtFlags { - private JdtFlags(){ - } - - public static final String VISIBILITY_STRING_PRIVATE= "private"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PACKAGE= ""; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PROTECTED= "protected"; //$NON-NLS-1$ - public static final String VISIBILITY_STRING_PUBLIC= "public"; //$NON-NLS-1$ - - - public static final int VISIBILITY_CODE_INVALID= -1; - - public static boolean isDefaultMethod(IMethodBinding method) { - int modifiers= method.getModifiers(); - // https://bugs.eclipse.org/bugs/show_bug.cgi?id=405517#c7 - ITypeBinding declaringClass= method.getDeclaringClass(); - if (declaringClass.isInterface()) { - return !Modifier.isAbstract(modifiers) && !Modifier.isStatic(modifiers); - } - return false; - } - - public static boolean isDefaultMethod(IMethod method) throws JavaModelException { - return Flags.isDefaultMethod(method.getFlags()); - } - - public static boolean isAbstract(IMember member) throws JavaModelException{ - int flags= member.getFlags(); - if (!member.isBinary() && isInterfaceOrAnnotationMethod(member)) { - return !Flags.isStatic(flags) && !Flags.isDefaultMethod(flags); - } - return Flags.isAbstract(flags); - } - - public static boolean isAbstract(IMethodBinding member) { - return Modifier.isAbstract(member.getModifiers()); - } - - public static boolean isStatic(BodyDeclaration bodyDeclaration) { - if (isNestedInterfaceOrAnnotation(bodyDeclaration)) - return true; - int nodeType= bodyDeclaration.getNodeType(); - if (!(nodeType == ASTNode.METHOD_DECLARATION || nodeType == ASTNode.ANNOTATION_TYPE_MEMBER_DECLARATION) && - isInterfaceOrAnnotationMember(bodyDeclaration)) - return true; - if (bodyDeclaration instanceof EnumConstantDeclaration) - return true; - if (bodyDeclaration instanceof EnumDeclaration && bodyDeclaration.getParent() instanceof AbstractTypeDeclaration) - return true; - return Modifier.isStatic(bodyDeclaration.getModifiers()); - } - - public static boolean isStatic(IMember member) throws JavaModelException { - if (isNestedInterfaceOrAnnotation(member)) - return true; - if (member.getElementType() != IJavaElement.METHOD - && isInterfaceOrAnnotationMember(member)) - return true; - if (isEnum(member) && (member.getElementType() == IJavaElement.FIELD || member.getDeclaringType() != null)) - return true; - return Flags.isStatic(member.getFlags()); - } - - public static boolean isStatic(IMethodBinding methodBinding){ - return Modifier.isStatic(methodBinding.getModifiers()); - } - - public static boolean isDeprecated(IMember member) throws JavaModelException{ - return Flags.isDeprecated(member.getFlags()); - } - - public static boolean isFinal(IMember member) throws JavaModelException{ - if (isInterfaceOrAnnotationField(member)) - return true; - if (isAnonymousType(member)) - return true; - if (isEnumConstant(member) || isEnumTypeFinal(member)) - return true; - return Flags.isFinal(member.getFlags()); - } - - private static boolean isEnumTypeFinal(IMember member) throws JavaModelException { - if (!(isEnum(member) && member.getElementType() == IJavaElement.TYPE)) - return false; - // An enum type is implicitly final unless it contains at least one enum constant that has a class body. - IJavaElement[] children= member.getChildren(); - for (IJavaElement child : children) { - if (isEnumConstant((IMember) child) && ((IField) child).getChildren().length != 0) { - return false; - } - } - return true; - } - - public static boolean isNative(IMember member) throws JavaModelException{ - return Flags.isNative(member.getFlags()); - } - - public static boolean isPackageVisible(IMember member) throws JavaModelException{ - return (! isPrivate(member) && ! isProtected(member) && ! isPublic(member)); - } - - public static boolean isPackageVisible(BodyDeclaration bodyDeclaration) { - return (! isPrivate(bodyDeclaration) && ! isProtected(bodyDeclaration) && ! isPublic(bodyDeclaration)); - } - - public static boolean isPackageVisible(IBinding binding) { - return (! isPrivate(binding) && ! isProtected(binding) && ! isPublic(binding)); - } - - public static boolean isPrivate(IMember member) throws JavaModelException{ - return Flags.isPrivate(member.getFlags()); - } - - public static boolean isPrivate(BodyDeclaration bodyDeclaration) { - return Modifier.isPrivate(bodyDeclaration.getModifiers()); - } - - public static boolean isPrivate(IBinding binding) { - return Modifier.isPrivate(binding.getModifiers()); - } - - public static boolean isProtected(IMember member) throws JavaModelException{ - return Flags.isProtected(member.getFlags()); - } - - public static boolean isProtected(BodyDeclaration bodyDeclaration) { - return Modifier.isProtected(bodyDeclaration.getModifiers()); - } - - public static boolean isProtected(IBinding binding) { - return Modifier.isProtected(binding.getModifiers()); - } - - public static boolean isPublic(IMember member) throws JavaModelException{ - if (isInterfaceOrAnnotationMember(member)) - return true; - if (isEnumConstant(member)) - return true; - return Flags.isPublic(member.getFlags()); - } - - public static boolean isPublic(IBinding binding) { - if (isInterfaceOrAnnotationMember(binding)) - return true; - return Modifier.isPublic(binding.getModifiers()); - } - - - public static boolean isPublic(BodyDeclaration bodyDeclaration) { - if (isInterfaceOrAnnotationMember(bodyDeclaration)) - return true; - return Modifier.isPublic(bodyDeclaration.getModifiers()); - } - - public static boolean isStatic(IVariableBinding variableBinding){ - if (isInterfaceOrAnnotationMember(variableBinding)) - return true; - return Modifier.isStatic(variableBinding.getModifiers()); - } - - public static boolean isSynchronized(IMember member) throws JavaModelException{ - return Flags.isSynchronized(member.getFlags()); - } - - public static boolean isSynthetic(IMember member) throws JavaModelException{ - return Flags.isSynthetic(member.getFlags()); - } - - public static boolean isAnnotation(IMember member) throws JavaModelException{ - return Flags.isAnnotation(member.getFlags()); - } - - public static boolean isEnum(IMember member) throws JavaModelException{ - return Flags.isEnum(member.getFlags()); - } - - public static boolean isVarargs(IMethod method) throws JavaModelException{ - return Flags.isVarargs(method.getFlags()); - } - - public static boolean isTransient(IMember member) throws JavaModelException{ - return Flags.isTransient(member.getFlags()); - } - - public static boolean isVolatile(IMember member) throws JavaModelException{ - return Flags.isVolatile(member.getFlags()); - } - - private static boolean isInterfaceOrAnnotationMethod(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.METHOD && isInterfaceOrAnnotationMember(member); - } - - private static boolean isInterfaceOrAnnotationField(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.FIELD && isInterfaceOrAnnotationMember(member); - } - - private static boolean isInterfaceOrAnnotationMember(IMember member) throws JavaModelException { - return member.getDeclaringType() != null && JavaModelUtil.isInterfaceOrAnnotation(member.getDeclaringType()); - } - - private static boolean isInterfaceOrAnnotationMember(IBinding binding) { - ITypeBinding declaringType= null; - if (binding instanceof IVariableBinding) { - declaringType= ((IVariableBinding) binding).getDeclaringClass(); - } else if (binding instanceof IMethodBinding) { - declaringType= ((IMethodBinding) binding).getDeclaringClass(); - } else if (binding instanceof ITypeBinding) { - declaringType= ((ITypeBinding) binding).getDeclaringClass(); - } - return declaringType != null && (declaringType.isInterface() || declaringType.isAnnotation()); - } - - private static boolean isInterfaceOrAnnotationMember(BodyDeclaration bodyDeclaration) { - return isInterfaceOrAnnotation(bodyDeclaration.getParent()); - } - - private static boolean isInterfaceOrAnnotation(ASTNode node) { - boolean isInterface= (node instanceof TypeDeclaration) && ((TypeDeclaration) node).isInterface(); - boolean isAnnotation= node instanceof AnnotationTypeDeclaration; - return isInterface || isAnnotation; - } - - private static boolean isNestedInterfaceOrAnnotation(BodyDeclaration bodyDeclaration) { - return bodyDeclaration.getParent() instanceof AbstractTypeDeclaration && isInterfaceOrAnnotation(bodyDeclaration); - } - - private static boolean isNestedInterfaceOrAnnotation(IMember member) throws JavaModelException{ - return member.getElementType() == IJavaElement.TYPE && - member.getDeclaringType() != null && - JavaModelUtil.isInterfaceOrAnnotation((IType)member); - } - - private static boolean isEnumConstant(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.FIELD && isEnum(member); - } - - private static boolean isAnonymousType(IMember member) throws JavaModelException { - return member.getElementType() == IJavaElement.TYPE && - ((IType)member).isAnonymous(); - } - - public static int getVisibilityCode(IMember member) throws JavaModelException { - if (isPublic(member)) - return Modifier.PUBLIC; - else if (isProtected(member)) - return Modifier.PROTECTED; - else if (isPackageVisible(member)) - return Modifier.NONE; - else if (isPrivate(member)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - public static int getVisibilityCode(BodyDeclaration bodyDeclaration) { - if (isPublic(bodyDeclaration)) - return Modifier.PUBLIC; - else if (isProtected(bodyDeclaration)) - return Modifier.PROTECTED; - else if (isPackageVisible(bodyDeclaration)) - return Modifier.NONE; - else if (isPrivate(bodyDeclaration)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - public static int getVisibilityCode(IBinding binding) { - if (isPublic(binding)) - return Modifier.PUBLIC; - else if (isProtected(binding)) - return Modifier.PROTECTED; - else if (isPackageVisible(binding)) - return Modifier.NONE; - else if (isPrivate(binding)) - return Modifier.PRIVATE; - Assert.isTrue(false); - return VISIBILITY_CODE_INVALID; - } - - - public static String getVisibilityString(int visibilityCode){ - if (Modifier.isPublic(visibilityCode)) - return VISIBILITY_STRING_PUBLIC; - if (Modifier.isProtected(visibilityCode)) - return VISIBILITY_STRING_PROTECTED; - if (Modifier.isPrivate(visibilityCode)) - return VISIBILITY_STRING_PRIVATE; - return VISIBILITY_STRING_PACKAGE; - } - - public static int getVisibilityCode(String visibilityString) { - Assert.isNotNull(visibilityString); - if (VISIBILITY_STRING_PACKAGE.equals(visibilityString)) - return 0; - else if (VISIBILITY_STRING_PRIVATE.equals(visibilityString)) - return Modifier.PRIVATE; - else if (VISIBILITY_STRING_PROTECTED.equals(visibilityString)) - return Modifier.PROTECTED; - else if (VISIBILITY_STRING_PUBLIC.equals(visibilityString)) - return Modifier.PUBLIC; - return VISIBILITY_CODE_INVALID; - } - - public static void assertVisibility(int visibility){ - Assert.isTrue( visibility == Modifier.PUBLIC || - visibility == Modifier.PROTECTED || - visibility == Modifier.NONE || - visibility == Modifier.PRIVATE); - } - - /** - * Compares two visibilities. - * - * @param newVisibility the 'new' visibility - * @param oldVisibility the 'old' visibility - * @return <code>true</code> iff the 'new' visibility is strictly higher than the old visibility - * - * @see Modifier#PUBLIC - * @see Modifier#PROTECTED - * @see Modifier#NONE - * @see Modifier#PRIVATE - */ - public static boolean isHigherVisibility(int newVisibility, int oldVisibility){ - assertVisibility(oldVisibility); - assertVisibility(newVisibility); - switch (oldVisibility) { - case Modifier.PRIVATE : - return newVisibility == Modifier.NONE - || newVisibility == Modifier.PUBLIC - || newVisibility == Modifier.PROTECTED; - case Modifier.NONE : - return newVisibility == Modifier.PUBLIC - || newVisibility == Modifier.PROTECTED; - - case Modifier.PROTECTED : - return newVisibility == Modifier.PUBLIC; - - case Modifier.PUBLIC : - return false; - default: - Assert.isTrue(false); - return false; - } - } - - public static int getLowerVisibility(int visibility1, int visibility2) { - if (isHigherVisibility(visibility1, visibility2)) - return visibility2; - else - return visibility1; - } - - /** - * Gets the higher visibility of the given parameters. - * - * @param visibility1 First visibility value to compare. Valid inputs are the {@link Modifier} visibility constants. - * @param visibility2 Second visibility value to compare. Valid inputs are the {@link Modifier} visibility constants. - * @return The parameter value with the higher visibility. - * @since 3.9 - */ - public static int getHigherVisibility(int visibility1, int visibility2) { - if (isHigherVisibility(visibility1, visibility2)) - return visibility1; - else - return visibility2; - } - - public static int clearAccessModifiers(int flags) { - return clearFlag(Modifier.PROTECTED | Modifier.PUBLIC | Modifier.PRIVATE, flags); - } - - public static int clearFlag(int flag, int flags){ - return flags & ~ flag; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/LRUMap.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/LRUMap.java deleted file mode 100644 index ca664e2bb5..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/LRUMap.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.jdt.internal.corext.util; - -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * Least-recently-used cache. When the map tops the maximum size configured in the constructor, it - * automatically removes the oldest entry in terms of last access. - * <p> - * Invoking the <tt>put</tt> or <tt>get</tt> method results in an access to the corresponding entry. - * The <tt>putAll</tt> method generates one entry access for each mapping in the specified map, in - * the order that key-value mappings are provided by the specified map's entry set iterator. <i>No - * other methods generate entry accesses.</i> In particular, operations on collection-views do - * <i>not</i> affect the order of iteration of the backing map. - * - * @param <K> type of the keys - * @param <V> type of the values - */ -public class LRUMap<K,V> extends LinkedHashMap<K,V> { - - private static final long serialVersionUID= 1L; - private final int fMaxSize; - - /** - * Creates an empty LRU map with the given maximum size. - * - * @param maxSize the maximum number of elements in the cache - */ - public LRUMap(int maxSize) { - super(maxSize, 0.75f, true); - fMaxSize= maxSize; - } - - @Override - protected boolean removeEldestEntry(Map.Entry<K,V> eldest) { - return size() > fMaxSize; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java deleted file mode 100644 index 2a578c7045..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/MethodOverrideTester.java +++ /dev/null @@ -1,558 +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 v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ - -package org.eclipse.jdt.internal.corext.util; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.core.runtime.Assert; - -import org.eclipse.jdt.core.Flags; -import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IMember; -import org.eclipse.jdt.core.IMethod; -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeHierarchy; -import org.eclipse.jdt.core.ITypeParameter; -import org.eclipse.jdt.core.JavaModelException; -import org.eclipse.jdt.core.Signature; - - -/** - * Finds overriding and overridden methods based on the Java model. - * - * @see JDTUIHelperClasses - */ -public class MethodOverrideTester { - private static class Substitutions { - - public static final Substitutions EMPTY_SUBST= new Substitutions(); - - private HashMap<String, String[]> fMap; - - public Substitutions() { - fMap= null; - } - - public void addSubstitution(String typeVariable, String substitution, String erasure) { - if (fMap == null) { - fMap= new HashMap<>(3); - } - fMap.put(typeVariable, new String[] { substitution, erasure }); - } - - private String[] getSubstArray(String typeVariable) { - if (fMap != null) { - return fMap.get(typeVariable); - } - return null; - } - - public String getSubstitution(String typeVariable) { - String[] subst= getSubstArray(typeVariable); - if (subst != null) { - return subst[0]; - } - return null; - } - - public String getErasure(String typeVariable) { - String[] subst= getSubstArray(typeVariable); - if (subst != null) { - return subst[1]; - } - return null; - } - } - - private final IType fFocusType; - private final ITypeHierarchy fHierarchy; - - private Map <IMethod, Substitutions> fMethodSubstitutions; - private Map<IType, Substitutions> fTypeVariableSubstitutions; - - public MethodOverrideTester(IType focusType, ITypeHierarchy hierarchy) { - if (focusType == null || hierarchy == null) { - throw new IllegalArgumentException(); - } - fFocusType= focusType; - fHierarchy= hierarchy; - fTypeVariableSubstitutions= null; - fMethodSubstitutions= null; - } - - public IType getFocusType() { - return fFocusType; - } - - public ITypeHierarchy getTypeHierarchy() { - return fHierarchy; - } - - /** - * Finds the method that declares the given method. A declaring method is the 'original' method declaration that does - * not override nor implement a method. <code>null</code> is returned it the given method does not override - * a method. When searching, super class are examined before implemented interfaces. - * @param overriding the overriding method - * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. - * @return the declaring method, or <code>null</code> - * @throws JavaModelException if a problem occurs - */ - public IMethod findDeclaringMethod(IMethod overriding, boolean testVisibility) throws JavaModelException { - IMethod result= null; - IMethod overridden= findOverriddenMethod(overriding, testVisibility); - while (overridden != null) { - result= overridden; - overridden= findOverriddenMethod(result, testVisibility); - } - return result; - } - - /** - * Finds the method that is overridden by the given method. - * First the super class is examined and then the implemented interfaces. - * @param overriding the overriding method - * @param testVisibility If true the result is tested on visibility. Null is returned if the method is not visible. - * @return a method that is directly overridden by the given method, or <code>null</code> - * @throws JavaModelException if a problem occurs - */ - public IMethod findOverriddenMethod(IMethod overriding, boolean testVisibility) throws JavaModelException { - int flags= overriding.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) { - return null; - } - - IType type= overriding.getDeclaringType(); - IType superClass= fHierarchy.getSuperclass(type); - if (superClass != null) { - IMethod res= findOverriddenMethodInHierarchy(superClass, overriding); - if (res != null) { - if (!testVisibility || JavaModelUtil.isVisibleInHierarchy(res, type.getPackageFragment())) { - return res; - } - } - } - IType[] interfaces= fHierarchy.getSuperInterfaces(type); - for (int i= 0; i < interfaces.length; i++) { - IMethod res= findOverriddenMethodInHierarchy(interfaces[i], overriding); - if (res != null) { - return res; // methods from interfaces are always public and therefore visible - } - } - return null; - } - - /** - * Finds the directly overridden method in a type and its super types. First the super class is examined and then the implemented interfaces. - * With generics it is possible that 2 methods in the same type are overidden at the same time. In that case, the first overridden method found is returned. - * @param type The type to find methods in - * @param overriding The overriding method - * @return The first overridden method or <code>null</code> if no method is overridden - * @throws JavaModelException if a problem occurs - */ - public IMethod findOverriddenMethodInHierarchy(IType type, IMethod overriding) throws JavaModelException { - IMethod method= findOverriddenMethodInType(type, overriding); - if (method != null) { - return method; - } - IType superClass= fHierarchy.getSuperclass(type); - if (superClass != null) { - IMethod res= findOverriddenMethodInHierarchy(superClass, overriding); - if (res != null) { - return res; - } - } - IType[] superInterfaces= fHierarchy.getSuperInterfaces(type); - for (int i= 0; i < superInterfaces.length; i++) { - IMethod res= findOverriddenMethodInHierarchy(superInterfaces[i], overriding); - if (res != null) { - return res; - } - } - return method; - } - - /** - * Finds an overridden method in a type. With generics it is possible that 2 methods in the same type are overridden at the same time. - * In that case the first overridden method found is returned. - * @param overriddenType The type to find methods in - * @param overriding The overriding method - * @return The first overridden method or <code>null</code> if no method is overridden - * @throws JavaModelException if a problem occurs - */ - public IMethod findOverriddenMethodInType(IType overriddenType, IMethod overriding) throws JavaModelException { - int flags= overriding.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) - return null; - IMethod[] overriddenMethods= overriddenType.getMethods(); - for (int i= 0; i < overriddenMethods.length; i++) { - IMethod overridden= overriddenMethods[i]; - flags= overridden.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overridden.isConstructor()) - continue; - if (isSubsignature(overriding, overridden)) { - return overridden; - } - } - return null; - } - - /** - * Finds an overriding method in a type. - * @param overridingType The type to find methods in - * @param overridden The overridden method - * @return The overriding method or <code>null</code> if no method is overriding. - * @throws JavaModelException if a problem occurs - */ - public IMethod findOverridingMethodInType(IType overridingType, IMethod overridden) throws JavaModelException { - int flags= overridden.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overridden.isConstructor()) - return null; - IMethod[] overridingMethods= overridingType.getMethods(); - for (int i= 0; i < overridingMethods.length; i++) { - IMethod overriding= overridingMethods[i]; - flags= overriding.getFlags(); - if (Flags.isPrivate(flags) || Flags.isStatic(flags) || overriding.isConstructor()) - continue; - if (isSubsignature(overriding, overridden)) { - return overriding; - } - } - return null; - } - - /** - * Tests if a method is a subsignature of another method. - * @param overriding overriding method (m1) - * @param overridden overridden method (m2) - * @return <code>true</code> iff the method <code>m1</code> is a subsignature of the method <code>m2</code>. - * This is one of the requirements for m1 to override m2. - * Accessibility and return types are not taken into account. - * Note that subsignature is <em>not</em> symmetric! - * @throws JavaModelException if a problem occurs - */ - public boolean isSubsignature(IMethod overriding, IMethod overridden) throws JavaModelException { - if (!overridden.getElementName().equals(overriding.getElementName())) { - return false; - } - int nParameters= overridden.getNumberOfParameters(); - if (nParameters != overriding.getNumberOfParameters()) { - return false; - } - - if (!hasCompatibleTypeParameters(overriding, overridden)) { - return false; - } - - return nParameters == 0 || hasCompatibleParameterTypes(overriding, overridden); - } - - private boolean hasCompatibleTypeParameters(IMethod overriding, IMethod overridden) throws JavaModelException { - ITypeParameter[] overriddenTypeParameters= overridden.getTypeParameters(); - ITypeParameter[] overridingTypeParameters= overriding.getTypeParameters(); - int nOverridingTypeParameters= overridingTypeParameters.length; - if (overriddenTypeParameters.length != nOverridingTypeParameters) { - return nOverridingTypeParameters == 0; - } - Substitutions overriddenSubst= getMethodSubstitions(overridden); - Substitutions overridingSubst= getMethodSubstitions(overriding); - for (int i= 0; i < nOverridingTypeParameters; i++) { - String erasure1= overriddenSubst.getErasure(overriddenTypeParameters[i].getElementName()); - String erasure2= overridingSubst.getErasure(overridingTypeParameters[i].getElementName()); - if (erasure1 == null || !erasure1.equals(erasure2)) { - return false; - } - // comparing only the erasure is not really correct: Need to compare all bounds, that can be in different order - int nBounds= overriddenTypeParameters[i].getBounds().length; - if (nBounds > 1 && nBounds != overridingTypeParameters[i].getBounds().length) { - return false; - } - } - return true; - } - - private boolean hasCompatibleParameterTypes(IMethod overriding, IMethod overridden) throws JavaModelException { - String[] overriddenParamTypes= overridden.getParameterTypes(); - String[] overridingParamTypes= overriding.getParameterTypes(); - - String[] substitutedOverriding= new String[overridingParamTypes.length]; - boolean testErasure= false; - - for (int i= 0; i < overridingParamTypes.length; i++) { - String overriddenParamSig= overriddenParamTypes[i]; - String overriddenParamName= getSubstitutedTypeName(overriddenParamSig, overridden); - String overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding); - substitutedOverriding[i]= overridingParamName; - if (!overriddenParamName.equals(overridingParamName)) { - testErasure= true; - break; - } - } - if (testErasure) { - for (int i= 0; i < overridingParamTypes.length; i++) { - String overriddenParamSig= overriddenParamTypes[i]; - String overriddenParamName= getErasedTypeName(overriddenParamSig, overridden); - String overridingParamName= substitutedOverriding[i]; - if (overridingParamName == null) - overridingParamName= getSubstitutedTypeName(overridingParamTypes[i], overriding); - if (!overriddenParamName.equals(overridingParamName)) { - return false; - } - } - } - return true; - } - - private String getVariableSubstitution(IMember context, String variableName) throws JavaModelException { - IType type; - if (context instanceof IMethod) { - String subst= getMethodSubstitions((IMethod) context).getSubstitution(variableName); - if (subst != null) { - return subst; - } - type= context.getDeclaringType(); - } else { - type= (IType) context; - } - String subst= getTypeSubstitions(type).getSubstitution(variableName); - if (subst != null) { - return subst; - } - IJavaElement parent= type.getParent(); - if (parent instanceof IMethod) { - return getVariableSubstitution((IMethod) parent, variableName); - } else if (type.getDeclaringType() != null) { - return getVariableSubstitution(type.getDeclaringType(), variableName); - } - return variableName; // not a type variable - } - - private String getVariableErasure(IMember context, String variableName) throws JavaModelException { - IType type; - if (context instanceof IMethod) { - String subst= getMethodSubstitions((IMethod) context).getErasure(variableName); - if (subst != null) { - return subst; - } - type= context.getDeclaringType(); - } else { - type= (IType) context; - } - String subst= getTypeSubstitions(type).getErasure(variableName); - if (subst != null) { - return subst; - } - IJavaElement parent= type.getParent(); - if (parent instanceof IMethod) { - return getVariableErasure((IMethod) parent, variableName); - } else if (type.getDeclaringType() != null) { - return getVariableErasure(type.getDeclaringType(), variableName); - } - return variableName; // not a type variable - } - - /* - * Returns the substitutions for a method's type parameters - */ - private Substitutions getMethodSubstitions(IMethod method) throws JavaModelException { - if (fMethodSubstitutions == null) { - fMethodSubstitutions= new LRUMap<>(3); - } - - Substitutions s= fMethodSubstitutions.get(method); - if (s == null) { - ITypeParameter[] typeParameters= method.getTypeParameters(); - if (typeParameters.length == 0) { - s= Substitutions.EMPTY_SUBST; - } else { - IType instantiatedType= method.getDeclaringType(); - s= new Substitutions(); - for (int i= 0; i < typeParameters.length; i++) { - ITypeParameter curr= typeParameters[i]; - s.addSubstitution(curr.getElementName(), '+' + String.valueOf(i), getTypeParameterErasure(curr, instantiatedType)); - } - } - fMethodSubstitutions.put(method, s); - } - return s; - } - - /* - * Returns the substitutions for a type's type parameters - */ - private Substitutions getTypeSubstitions(IType type) throws JavaModelException { - if (fTypeVariableSubstitutions == null) { - fTypeVariableSubstitutions= new HashMap<>(); - computeSubstitutions(fFocusType, null, null); - } - Substitutions subst= fTypeVariableSubstitutions.get(type); - if (subst == null) { - return Substitutions.EMPTY_SUBST; - } - return subst; - } - - private void computeSubstitutions(IType instantiatedType, IType instantiatingType, String[] typeArguments) throws JavaModelException { - Substitutions s= new Substitutions(); - fTypeVariableSubstitutions.put(instantiatedType, s); - - ITypeParameter[] typeParameters= instantiatedType.getTypeParameters(); - - if (instantiatingType == null) { // the focus type - for (int i= 0; i < typeParameters.length; i++) { - ITypeParameter curr= typeParameters[i]; - // use star to make type variables different from type refs - s.addSubstitution(curr.getElementName(), '*' + curr.getElementName(), getTypeParameterErasure(curr, instantiatedType)); - } - } else { - if (typeParameters.length == typeArguments.length) { - for (int i= 0; i < typeParameters.length; i++) { - ITypeParameter curr= typeParameters[i]; - String substString= getSubstitutedTypeName(typeArguments[i], instantiatingType); // substitute in the context of the instantiatingType - String erasure= getErasedTypeName(typeArguments[i], instantiatingType); // get the erasure from the type argument - s.addSubstitution(curr.getElementName(), substString, erasure); - } - } else if (typeArguments.length == 0) { // raw type reference - for (int i= 0; i < typeParameters.length; i++) { - ITypeParameter curr= typeParameters[i]; - String erasure= getTypeParameterErasure(curr, instantiatedType); - s.addSubstitution(curr.getElementName(), erasure, erasure); - } - } else { - // code with errors - } - } - String superclassTypeSignature= instantiatedType.getSuperclassTypeSignature(); - if (superclassTypeSignature != null) { - String[] superTypeArguments= Signature.getTypeArguments(superclassTypeSignature); - IType superclass= fHierarchy.getSuperclass(instantiatedType); - if (superclass != null && !fTypeVariableSubstitutions.containsKey(superclass)) { - computeSubstitutions(superclass, instantiatedType, superTypeArguments); - } - } - String[] superInterfacesTypeSignature; - if (instantiatedType.isAnonymous()) { - // special case: superinterface is also returned by IType#getSuperclassTypeSignature() - superInterfacesTypeSignature= new String[] { superclassTypeSignature }; - } else { - superInterfacesTypeSignature= instantiatedType.getSuperInterfaceTypeSignatures(); - } - int nInterfaces= superInterfacesTypeSignature.length; - if (nInterfaces > 0) { - IType[] superInterfaces= fHierarchy.getSuperInterfaces(instantiatedType); - if (superInterfaces.length == nInterfaces) { - for (int i= 0; i < nInterfaces; i++) { - String[] superTypeArguments= Signature.getTypeArguments(superInterfacesTypeSignature[i]); - IType superInterface= superInterfaces[i]; - if (!fTypeVariableSubstitutions.containsKey(superInterface)) { - computeSubstitutions(superInterface, instantiatedType, superTypeArguments); - } - } - } - } - } - - private String getTypeParameterErasure(ITypeParameter typeParameter, IType context) throws JavaModelException { - String[] bounds= typeParameter.getBounds(); - if (bounds.length > 0) { - return getErasedTypeName(Signature.createTypeSignature(bounds[0], false), context); - } - return "Object"; //$NON-NLS-1$ - } - - - /** - * Translates the type signature to a 'normalized' type name where all variables are substituted for the given type or method context. - * The returned name contains only simple names and can be used to compare against other substituted type names - * @param typeSig The type signature to translate - * @param context The context for the substitution - * @return a type name - * @throws JavaModelException if a problem occurs - */ - private String getSubstitutedTypeName(String typeSig, IMember context) throws JavaModelException { - return internalGetSubstitutedTypeName(typeSig, context, false, new StringBuffer()).toString(); - } - - private String getErasedTypeName(String typeSig, IMember context) throws JavaModelException { - return internalGetSubstitutedTypeName(typeSig, context, true, new StringBuffer()).toString(); - } - - private StringBuffer internalGetSubstitutedTypeName(String typeSig, IMember context, boolean erasure, StringBuffer buf) throws JavaModelException { - int sigKind= Signature.getTypeSignatureKind(typeSig); - switch (sigKind) { - case Signature.BASE_TYPE_SIGNATURE: - return buf.append(Signature.toString(typeSig)); - case Signature.ARRAY_TYPE_SIGNATURE: - internalGetSubstitutedTypeName(Signature.getElementType(typeSig), context, erasure, buf); - for (int i= Signature.getArrayCount(typeSig); i > 0; i--) { - buf.append('[').append(']'); - } - return buf; - case Signature.CLASS_TYPE_SIGNATURE: { - String erasureSig= Signature.getTypeErasure(typeSig); - String erasureName= Signature.getSimpleName(Signature.toString(erasureSig)); - - char ch= erasureSig.charAt(0); - if (ch == Signature.C_RESOLVED) { - buf.append(erasureName); - } else if (ch == Signature.C_UNRESOLVED) { // could be a type variable - if (erasure) { - buf.append(getVariableErasure(context, erasureName)); - } else { - buf.append(getVariableSubstitution(context, erasureName)); - } - } else { - Assert.isTrue(false, "Unknown class type signature"); //$NON-NLS-1$ - } - if (!erasure) { - String[] typeArguments= Signature.getTypeArguments(typeSig); - if (typeArguments.length > 0) { - buf.append('<'); - for (int i= 0; i < typeArguments.length; i++) { - if (i > 0) { - buf.append(','); - } - internalGetSubstitutedTypeName(typeArguments[i], context, erasure, buf); - } - buf.append('>'); - } - } - return buf; - } - case Signature.TYPE_VARIABLE_SIGNATURE: - String varName= Signature.toString(typeSig); - if (erasure) { - return buf.append(getVariableErasure(context, varName)); - } else { - return buf.append(getVariableSubstitution(context, varName)); - } - case Signature.WILDCARD_TYPE_SIGNATURE: { - buf.append('?'); - char ch= typeSig.charAt(0); - if (ch == Signature.C_STAR) { - return buf; - } else if (ch == Signature.C_EXTENDS) { - buf.append(" extends "); //$NON-NLS-1$ - } else { - buf.append(" super "); //$NON-NLS-1$ - } - return internalGetSubstitutedTypeName(typeSig.substring(1), context, erasure, buf); - } - case Signature.CAPTURE_TYPE_SIGNATURE: - return internalGetSubstitutedTypeName(typeSig.substring(1), context, erasure, buf); - default: - Assert.isTrue(false, "Unhandled type signature kind"); //$NON-NLS-1$ - return buf; - } - } - -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Resources.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Resources.java index 19d1472f80..bdcf06b226 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Resources.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Resources.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -37,7 +37,7 @@ import org.eclipse.jdt.internal.corext.CorextMessages; import org.eclipse.jdt.internal.ui.IJavaStatusConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIStatus; -import org.eclipse.jdt.internal.ui.viewsupport.BasicElementLabels; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class Resources { diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Strings.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Strings.java index 5028d317af..6b978612ea 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Strings.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/Strings.java @@ -12,44 +12,19 @@ package org.eclipse.jdt.internal.corext.util; import org.eclipse.osgi.util.TextProcessor; -import org.eclipse.core.runtime.Assert; - import org.eclipse.jface.action.LegacyActionTools; import org.eclipse.jface.viewers.StyledString; import org.eclipse.jface.viewers.StyledString.Styler; -import org.eclipse.jface.text.BadLocationException; -import org.eclipse.jface.text.DefaultLineTracker; -import org.eclipse.jface.text.ILineTracker; -import org.eclipse.jface.text.IRegion; - -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.formatter.IndentManipulation; - - /** * Helper class to provide String manipulation functions not available in standard JDK. + * + * @see JDTUIHelperClasses */ -public class Strings { +public class Strings extends org.eclipse.jdt.internal.core.manipulation.util.Strings { private Strings(){} - - /** - * Tells whether we have to use the {@link TextProcessor} - * <p> - * This is used for performance optimization. - * </p> - * @since 3.4 - */ - public static final boolean USE_TEXT_PROCESSOR; - static { - String testString= "args : String[]"; //$NON-NLS-1$ - USE_TEXT_PROCESSOR= testString != TextProcessor.process(testString); - } - - private static final String JAVA_ELEMENT_DELIMITERS= TextProcessor.getDefaultDelimiters() + "<>(),?{} "; //$NON-NLS-1$ - /** * Sets the given <code>styler</code> to use for <code>matchingRegions</code> (obtained from * {@link org.eclipse.jdt.core.search.SearchPattern#getMatchingRegions}) in the @@ -167,493 +142,6 @@ public class Strings { } } - /** - * Adds special marks so that that the given string is readable in a BiDi environment. - * - * @param string the string - * @return the processed styled string - * @since 3.4 - */ - public static String markLTR(String string) { - if (!USE_TEXT_PROCESSOR) - return string; - - return TextProcessor.process(string); - } - - /** - * Adds special marks so that that the given string is readable in a BiDi environment. - * - * @param string the string - * @param delimiters the delimiters - * @return the processed styled string - * @since 3.4 - */ - public static String markLTR(String string, String delimiters) { - if (!USE_TEXT_PROCESSOR) - return string; - - return TextProcessor.process(string, delimiters); - } - - /** - * Adds special marks so that that the given Java element label is readable in a BiDi - * environment. - * - * @param string the string - * @return the processed styled string - * @since 3.6 - */ - public static String markJavaElementLabelLTR(String string) { - if (!USE_TEXT_PROCESSOR) - return string; - - return TextProcessor.process(string, JAVA_ELEMENT_DELIMITERS); - } - - /** - * Tests if a char is lower case. Fix for 26529. - * @param ch the char - * @return return true if char is lower case - */ - public static boolean isLowerCase(char ch) { - return Character.toLowerCase(ch) == ch; - } - - public static boolean startsWithIgnoreCase(String text, String prefix) { - int textLength= text.length(); - int prefixLength= prefix.length(); - if (textLength < prefixLength) - return false; - for (int i= prefixLength - 1; i >= 0; i--) { - if (Character.toLowerCase(prefix.charAt(i)) != Character.toLowerCase(text.charAt(i))) - return false; - } - return true; - } - - public static String removeNewLine(String message) { - StringBuffer result= new StringBuffer(); - int current= 0; - int index= message.indexOf('\n', 0); - while (index != -1) { - result.append(message.substring(current, index)); - if (current < index && index != 0) - result.append(' '); - current= index + 1; - index= message.indexOf('\n', current); - } - result.append(message.substring(current)); - return result.toString(); - } - - /** - * Converts the given string into an array of lines. The lines - * don't contain any line delimiter characters. - * - * @param input the string - * @return the string converted into an array of strings. Returns <code> - * null</code> if the input string can't be converted in an array of lines. - */ - public static String[] convertIntoLines(String input) { - try { - ILineTracker tracker= new DefaultLineTracker(); - tracker.set(input); - int size= tracker.getNumberOfLines(); - String result[]= new String[size]; - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - int offset= region.getOffset(); - result[i]= input.substring(offset, offset + region.getLength()); - } - return result; - } catch (BadLocationException e) { - return null; - } - } - - /** - * Returns <code>true</code> if the given string only consists of - * white spaces according to Java. If the string is empty, <code>true - * </code> is returned. - * - * @param s the string to test - * @return <code>true</code> if the string only consists of white - * spaces; otherwise <code>false</code> is returned - * - * @see java.lang.Character#isWhitespace(char) - */ - public static boolean containsOnlyWhitespaces(String s) { - int size= s.length(); - for (int i= 0; i < size; i++) { - if (!Character.isWhitespace(s.charAt(i))) - return false; - } - return true; - } - - /** - * Removes leading tabs and spaces from the given string. If the string - * doesn't contain any leading tabs or spaces then the string itself is - * returned. - * @param line the line - * @return the trimmed line - */ - public static String trimLeadingTabsAndSpaces(String line) { - int size= line.length(); - int start= size; - for (int i= 0; i < size; i++) { - char c= line.charAt(i); - if (!IndentManipulation.isIndentChar(c)) { - start= i; - break; - } - } - if (start == 0) - return line; - else if (start == size) - return ""; //$NON-NLS-1$ - else - return line.substring(start); - } - - public static String trimTrailingTabsAndSpaces(String line) { - int size= line.length(); - int end= size; - for (int i= size - 1; i >= 0; i--) { - char c= line.charAt(i); - if (IndentManipulation.isIndentChar(c)) { - end= i; - } else { - break; - } - } - if (end == size) - return line; - else if (end == 0) - return ""; //$NON-NLS-1$ - else - return line.substring(0, end); - } - - /** - * Returns the indent of the given string in indentation units. Odd spaces - * are not counted. - * - * @param line the text line - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @return the number of indent units - * @since 3.1 - */ - public static int computeIndentUnits(String line, IJavaProject project) { - return IndentManipulation.measureIndentUnits(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Returns the indent of the given string in indentation units. Odd spaces - * are not counted. - * - * @param line the text line - * @param tabWidth the width of the '\t' character in space equivalents - * @param indentWidth the width of one indentation unit in space equivalents - * @return the indent of the given string in indentation units - * - * @since 3.1 - */ - public static int computeIndentUnits(String line, int tabWidth, int indentWidth) { - return IndentManipulation.measureIndentUnits(line, tabWidth, indentWidth); - } - - /** - * Computes the visual length of the indentation of a - * <code>CharSequence</code>, counting a tab character as the size until - * the next tab stop and every other whitespace character as one. - * - * @param line the string to measure the indent of - * @param tabSize the visual size of a tab in space equivalents - * @return the visual length of the indentation of <code>line</code> - * @since 3.1 - */ - public static int measureIndentLength(CharSequence line, int tabSize) { - return IndentManipulation.measureIndentInSpaces(line, tabSize); - } - - /** - * Removes the given number of indents from the line. Asserts that the given line - * has the requested number of indents. If <code>indentsToRemove <= 0</code> - * the line is returned. - * @param line the line - * @param indentsToRemove the indents to remove - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @return the trimmed line - * - * @since 3.1 - */ - public static String trimIndent(String line, int indentsToRemove, IJavaProject project) { - return IndentManipulation.trimIndent(line, indentsToRemove, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Removes the given number of indents from the line. Asserts that the given line - * has the requested number of indents. If <code>indentsToRemove <= 0</code> - * the line is returned. - * @param line the line - * @param indentsToRemove the indents to remove - * @param tabWidth the tab width - * @param indentWidth the indent width - * @return the trimmed line - * - * @since 3.1 - */ - public static String trimIndent(String line, int indentsToRemove, int tabWidth, int indentWidth) { - return IndentManipulation.trimIndent(line, indentsToRemove, tabWidth, indentWidth); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. - * @param lines the lines - - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @since 3.1 - */ - public static void trimIndentation(String[] lines, IJavaProject project) { - trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), true); - } - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. - * @param lines the lines - * @param tabWidth the size of one tab in space equivalents - * @param indentWidth the size of the indent in space equivalents - * - * @since 3.1 - */ - public static void trimIndentation(String[] lines, int tabWidth, int indentWidth) { - trimIndentation(lines, tabWidth, indentWidth, true); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. If <code> - * considerFirstLine</code> is false the first line will be ignored. - * @param lines the lines - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @param considerFirstLine If <code>considerFirstLine</code> is false the first line will be ignored. - * @since 3.1 - */ - public static void trimIndentation(String[] lines, IJavaProject project, boolean considerFirstLine) { - trimIndentation(lines, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine); - } - - /** - * Removes the common number of indents from all lines. If a line - * only consists out of white space it is ignored. If <code> - * considerFirstLine</code> is false the first line will be ignored. - * @param lines the lines - * @param tabWidth the size of one tab in space equivalents - * @param indentWidth the size of the indent in space equivalents - * @param considerFirstLine If <code> considerFirstLine</code> is false the first line will be ignored. - * @since 3.1 - */ - public static void trimIndentation(String[] lines, int tabWidth, int indentWidth, boolean considerFirstLine) { - String[] toDo= new String[lines.length]; - // find indentation common to all lines - int minIndent= Integer.MAX_VALUE; // very large - for (int i= considerFirstLine ? 0 : 1; i < lines.length; i++) { - String line= lines[i]; - if (containsOnlyWhitespaces(line)) - continue; - toDo[i]= line; - int indent= computeIndentUnits(line, tabWidth, indentWidth); - if (indent < minIndent) { - minIndent= indent; - } - } - - if (minIndent > 0) { - // remove this indent from all lines - for (int i= considerFirstLine ? 0 : 1; i < toDo.length; i++) { - String s= toDo[i]; - if (s != null) - lines[i]= trimIndent(s, minIndent, tabWidth, indentWidth); - else { - String line= lines[i]; - int indent= computeIndentUnits(line, tabWidth, indentWidth); - if (indent > minIndent) - lines[i]= trimIndent(line, minIndent, tabWidth, indentWidth); - else - lines[i]= trimLeadingTabsAndSpaces(line); - } - } - } - } - - /** - * Returns that part of the indentation of <code>line</code> that makes up - * a multiple of indentation units. - * - * @param line the line to scan - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @return the indent part of <code>line</code>, but no odd spaces - * @since 3.1 - */ - public static String getIndentString(String line, IJavaProject project) { - return IndentManipulation.extractIndentString(line, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project)); - } - - /** - * Returns that part of the indentation of <code>line</code> that makes up - * a multiple of indentation units. - * - * @param line the line to scan - * @param tabWidth the size of one tab in space equivalents - * @param indentWidth the size of the indent in space equivalents - * @return the indent part of <code>line</code>, but no odd spaces - * @since 3.1 - */ - public static String getIndentString(String line, int tabWidth, int indentWidth) { - return IndentManipulation.extractIndentString(line, tabWidth, indentWidth); - } - - public static String[] removeTrailingEmptyLines(String[] sourceLines) { - int lastNonEmpty= findLastNonEmptyLineIndex(sourceLines); - String[] result= new String[lastNonEmpty + 1]; - for (int i= 0; i < result.length; i++) { - result[i]= sourceLines[i]; - } - return result; - } - - private static int findLastNonEmptyLineIndex(String[] sourceLines) { - for (int i= sourceLines.length - 1; i >= 0; i--) { - if (! sourceLines[i].trim().equals(""))//$NON-NLS-1$ - return i; - } - return -1; - } - - /** - * Change the indent of, possible multi-line, code range. The current indent is removed, a new indent added. - * The first line of the code will not be changed. (It is considered to have no indent as it might start in - * the middle of a line) - * @param code the code - * @param codeIndentLevel level of indentation - * - * @param project the java project from which to get the formatter - * preferences, or <code>null</code> for global preferences - * @param newIndent new indent - * @param lineDelim line delimiter - * @return the changed code - * @since 3.1 - */ - public static String changeIndent(String code, int codeIndentLevel, IJavaProject project, String newIndent, String lineDelim) { - return IndentManipulation.changeIndent(code, codeIndentLevel, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), newIndent, lineDelim); - } - - /** - * Change the indent of, possible muti-line, code range. The current indent is removed, a new indent added. - * The first line of the code will not be changed. (It is considered to have no indent as it might start in - * the middle of a line) - * @param code the code - * @param codeIndentLevel indent level - * @param tabWidth the size of one tab in space equivalents - * @param indentWidth the size of the indent in space equivalents - * @param newIndent new indent - * @param lineDelim line delimiter - * @return the changed code - * @since 3.1 - */ - public static String changeIndent(String code, int codeIndentLevel, int tabWidth, int indentWidth, String newIndent, String lineDelim) { - return IndentManipulation.changeIndent(code, codeIndentLevel, tabWidth, indentWidth, newIndent, lineDelim); - } - - public static String trimIndentation(String source, IJavaProject project, boolean considerFirstLine) { - return trimIndentation(source, CodeFormatterUtil.getTabWidth(project), CodeFormatterUtil.getIndentWidth(project), considerFirstLine); - } - - public static String trimIndentation(String source, int tabWidth, int indentWidth, boolean considerFirstLine) { - try { - ILineTracker tracker= new DefaultLineTracker(); - tracker.set(source); - int size= tracker.getNumberOfLines(); - if (size == 1) - return source; - String lines[]= new String[size]; - for (int i= 0; i < size; i++) { - IRegion region= tracker.getLineInformation(i); - int offset= region.getOffset(); - lines[i]= source.substring(offset, offset + region.getLength()); - } - Strings.trimIndentation(lines, tabWidth, indentWidth, considerFirstLine); - StringBuffer result= new StringBuffer(); - int last= size - 1; - for (int i= 0; i < size; i++) { - result.append(lines[i]); - if (i < last) - result.append(tracker.getLineDelimiter(i)); - } - return result.toString(); - } catch (BadLocationException e) { - Assert.isTrue(false,"Can not happend"); //$NON-NLS-1$ - return null; - } - } - - - /** - * Concatenate the given strings into one strings using the passed line delimiter as a - * delimiter. No delimiter is added to the last line. - * @param lines the lines - * @param delimiter line delimiter - * @return the concatenated lines - */ - public static String concatenate(String[] lines, String delimiter) { - StringBuffer buffer= new StringBuffer(); - for (int i= 0; i < lines.length; i++) { - if (i > 0) - buffer.append(delimiter); - buffer.append(lines[i]); - } - return buffer.toString(); - } - - public static boolean equals(String s, char[] c) { - if (s.length() != c.length) - return false; - - for (int i = c.length; --i >= 0;) - if (s.charAt(i) != c[i]) - return false; - return true; - } - - public static String removeTrailingCharacters(String text, char toRemove) { - int size= text.length(); - int end= size; - for (int i= size - 1; i >= 0; i--) { - char c= text.charAt(i); - if (c == toRemove) { - end= i; - } else { - break; - } - } - if (end == size) - return text; - else if (end == 0) - return ""; //$NON-NLS-1$ - else - return text.substring(0, end); - } - public static String removeMnemonicIndicator(String string) { return LegacyActionTools.removeMnemonics(string); } diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/SuperTypeHierarchyCache.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/SuperTypeHierarchyCache.java deleted file mode 100644 index 0386d32cf0..0000000000 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/SuperTypeHierarchyCache.java +++ /dev/null @@ -1,234 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * which accompanies this distribution, and is available at - * http://www.eclipse.org/legal/epl-v10.html - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.internal.corext.util; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; - -import org.eclipse.core.runtime.IProgressMonitor; - -import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.ITypeHierarchy; -import org.eclipse.jdt.core.ITypeHierarchyChangedListener; -import org.eclipse.jdt.core.JavaModelException; - -/** - * A thread-safe cache for super type hierarchies. - * - * @see JDTUIHelperClasses - */ -public class SuperTypeHierarchyCache { - - private static class HierarchyCacheEntry implements ITypeHierarchyChangedListener { - - private ITypeHierarchy fTypeHierarchy; - private long fLastAccess; - - public HierarchyCacheEntry(ITypeHierarchy hierarchy) { - fTypeHierarchy= hierarchy; - fTypeHierarchy.addTypeHierarchyChangedListener(this); - markAsAccessed(); - } - - @Override - public void typeHierarchyChanged(ITypeHierarchy typeHierarchy) { - removeHierarchyEntryFromCache(this); - } - - public ITypeHierarchy getTypeHierarchy() { - return fTypeHierarchy; - } - - public void markAsAccessed() { - fLastAccess= System.currentTimeMillis(); - } - - public long getLastAccess() { - return fLastAccess; - } - - public void dispose() { - if (fTypeHierarchy != null) { - fTypeHierarchy.removeTypeHierarchyChangedListener(this); - fTypeHierarchy= null; - } - } - - @Override - public String toString() { - return "Super hierarchy of: " + fTypeHierarchy.getType().getElementName(); //$NON-NLS-1$ - } - - } - - - private static final int CACHE_SIZE= 8; - - private static ArrayList<HierarchyCacheEntry> fgHierarchyCache= new ArrayList<>(CACHE_SIZE); - private static Map<IType, MethodOverrideTester> fgMethodOverrideTesterCache= new LRUMap<>(CACHE_SIZE); - - private static int fgCacheHits= 0; - private static int fgCacheMisses= 0; - - /** - * Returns a super type hierarchy that contains the given type. - * The returned hierarchy may actually be based on a subtype of the - * requested type. Therefore, queries such as {@link ITypeHierarchy#getAllClasses()} - * or {@link ITypeHierarchy#getRootInterfaces()} may return more types than the same - * queries on a type hierarchy for just the given type. - * - * @param type the focus type - * @return a supertype hierarchy that contains <code>type</code> - * @throws JavaModelException if a problem occurs - */ - public static ITypeHierarchy getTypeHierarchy(IType type) throws JavaModelException { - return getTypeHierarchy(type, null); - } - - public static MethodOverrideTester getMethodOverrideTester(IType type) throws JavaModelException { - MethodOverrideTester test= null; - synchronized (fgMethodOverrideTesterCache) { - test= fgMethodOverrideTesterCache.get(type); - } - if (test == null) { - ITypeHierarchy hierarchy= getTypeHierarchy(type); // don't nest the locks - synchronized (fgMethodOverrideTesterCache) { - test= fgMethodOverrideTesterCache.get(type); // test again after waiting a long time for 'getTypeHierarchy' - if (test == null) { - test= new MethodOverrideTester(type, hierarchy); - fgMethodOverrideTesterCache.put(type, test); - } - } - } - return test; - } - - private static void removeMethodOverrideTester(ITypeHierarchy hierarchy) { - synchronized (fgMethodOverrideTesterCache) { - for (Iterator<MethodOverrideTester> iter= fgMethodOverrideTesterCache.values().iterator(); iter.hasNext();) { - MethodOverrideTester curr= iter.next(); - if (curr.getTypeHierarchy().equals(hierarchy)) { - iter.remove(); - } - } - } - } - - /** - * Returns a super type hierarchy that contains the given type. - * The returned hierarchy may actually be based on a subtype of the - * requested type. Therefore, queries such as {@link ITypeHierarchy#getAllClasses()} - * or {@link ITypeHierarchy#getRootInterfaces()} may return more types than the same - * queries on a type hierarchy for just the given type. - * - * @param type the focus type - * @param progressMonitor progress monitor - * @return a supertype hierarchy that contains <code>type</code> - * @throws JavaModelException if a problem occurs - */ - public static ITypeHierarchy getTypeHierarchy(IType type, IProgressMonitor progressMonitor) throws JavaModelException { - ITypeHierarchy hierarchy= findTypeHierarchyInCache(type); - if (hierarchy == null) { - fgCacheMisses++; - hierarchy= type.newSupertypeHierarchy(progressMonitor); - addTypeHierarchyToCache(hierarchy); - } else { - fgCacheHits++; - } - return hierarchy; - } - - private static void addTypeHierarchyToCache(ITypeHierarchy hierarchy) { - synchronized (fgHierarchyCache) { - int nEntries= fgHierarchyCache.size(); - if (nEntries >= CACHE_SIZE) { - // find obsolete entries or remove entry that was least recently accessed - HierarchyCacheEntry oldest= null; - ArrayList<HierarchyCacheEntry> obsoleteHierarchies= new ArrayList<>(CACHE_SIZE); - for (int i= 0; i < nEntries; i++) { - HierarchyCacheEntry entry= fgHierarchyCache.get(i); - ITypeHierarchy curr= entry.getTypeHierarchy(); - if (!curr.exists() || hierarchy.contains(curr.getType())) { - obsoleteHierarchies.add(entry); - } else { - if (oldest == null || entry.getLastAccess() < oldest.getLastAccess()) { - oldest= entry; - } - } - } - if (!obsoleteHierarchies.isEmpty()) { - for (int i= 0; i < obsoleteHierarchies.size(); i++) { - removeHierarchyEntryFromCache(obsoleteHierarchies.get(i)); - } - } else if (oldest != null) { - removeHierarchyEntryFromCache(oldest); - } - } - HierarchyCacheEntry newEntry= new HierarchyCacheEntry(hierarchy); - fgHierarchyCache.add(newEntry); - } - } - - - /** - * Check if the given type is in the hierarchy cache. - * @param type a type - * @return <code>true</code> if a hierarchy for the given type is cached - */ - public static boolean hasInCache(IType type) { - return findTypeHierarchyInCache(type) != null; - } - - - private static ITypeHierarchy findTypeHierarchyInCache(IType type) { - synchronized (fgHierarchyCache) { - for (int i= fgHierarchyCache.size() - 1; i>= 0; i--) { - HierarchyCacheEntry curr= fgHierarchyCache.get(i); - ITypeHierarchy hierarchy= curr.getTypeHierarchy(); - if (!hierarchy.exists()) { - removeHierarchyEntryFromCache(curr); - } else { - if (hierarchy.contains(type)) { - curr.markAsAccessed(); - return hierarchy; - } - } - } - } - return null; - } - - private static void removeHierarchyEntryFromCache(HierarchyCacheEntry entry) { - synchronized (fgHierarchyCache) { - removeMethodOverrideTester(entry.getTypeHierarchy()); - entry.dispose(); - fgHierarchyCache.remove(entry); - } - } - - - /** - * Gets the number of times the hierarchy could be taken from the hierarchy. - * @return Returns a int - */ - public static int getCacheHits() { - return fgCacheHits; - } - - /** - * Gets the number of times the hierarchy was build. Used for testing. - * @return Returns a int - */ - public static int getCacheMisses() { - return fgCacheMisses; - } -} diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/TypeInfoFilter.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/TypeInfoFilter.java index 6251687da8..7d9555cb19 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/TypeInfoFilter.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/util/TypeInfoFilter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2012 IBM Corporation and others. + * 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 v1.0 * which accompanies this distribution, and is available at @@ -17,6 +17,8 @@ import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchPattern; import org.eclipse.jdt.core.search.TypeNameMatch; +import org.eclipse.jdt.internal.core.manipulation.util.Strings; + import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension; import org.eclipse.jdt.internal.ui.util.PatternMatcher; |