diff --git a/.mvn/extensions.xml b/.mvn/extensions.xml index 623109cd8ea..05a34b1e815 100644 --- a/.mvn/extensions.xml +++ b/.mvn/extensions.xml @@ -3,6 +3,6 @@ org.eclipse.tycho tycho-build - 4.0.8 + 4.0.10 diff --git a/org.eclipse.jdt.core.manipulation/.settings/.api_filters b/org.eclipse.jdt.core.manipulation/.settings/.api_filters index aa01ed20907..ece44acdf99 100644 --- a/org.eclipse.jdt.core.manipulation/.settings/.api_filters +++ b/org.eclipse.jdt.core.manipulation/.settings/.api_filters @@ -31,12 +31,4 @@ - - - - - - - - diff --git a/org.eclipse.jdt.core.manipulation/META-INF/MANIFEST.MF b/org.eclipse.jdt.core.manipulation/META-INF/MANIFEST.MF index cce3d0f53df..fc6299b123b 100644 --- a/org.eclipse.jdt.core.manipulation/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.core.manipulation/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.core.manipulation Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.core.manipulation; singleton:=true -Bundle-Version: 1.21.300.qualifier +Bundle-Version: 1.21.400.qualifier Bundle-Vendor: %providerName Bundle-Activator: org.eclipse.jdt.internal.core.manipulation.JavaManipulationPlugin Bundle-Localization: plugin diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/ImportReferencesCollector.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/ImportReferencesCollector.java index 6ae8911fc1a..19da9cd7a3f 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/ImportReferencesCollector.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/ImportReferencesCollector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -114,7 +114,7 @@ private ImportReferencesCollector(IJavaProject project, CompilationUnit astRoot, fTypeImports= resultingTypeImports; fStaticImports= resultingStaticImports; fSubRange= rangeLimit; - if (project == null || !JavaModelUtil.is50OrHigher(project)) { + if (project == null) { fStaticImports= null; // do not collect } fASTRoot= astRoot; // can be null diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/OrganizeImportsOperation.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/OrganizeImportsOperation.java index aaa8c803536..a237a8f8f30 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/OrganizeImportsOperation.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/core/manipulation/OrganizeImportsOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -42,7 +42,6 @@ import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.SourceRange; @@ -74,9 +73,9 @@ 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.util.StaticImportFavoritesCompletionInvoker; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; +import org.eclipse.jdt.internal.corext.util.StaticImportFavoritesCompletionInvoker; @@ -204,7 +203,7 @@ private static class UnresolvedTypeData { public UnresolvedTypeData(SimpleName ref) { this.ref= ref; - this.typeKinds= ASTResolving.getPossibleTypeKinds(ref, true); + this.typeKinds= ASTResolving.getPossibleTypeKinds(ref); this.foundInfos= new ArrayList<>(3); } @@ -233,7 +232,6 @@ public void addInfo(TypeNameMatch info) { private IPackageFragment fCurrPackage; private ScopeAnalyzer fAnalyzer; - private boolean fAllowDefaultPackageImports; private Map fUnresolvedTypes; private Set fImportsAdded; @@ -259,8 +257,6 @@ public TypeReferenceProcessor(Set oldSingleImports, Set oldDeman fCurrPackage= (IPackageFragment) cu.getParent(); - fAllowDefaultPackageImports= JavaCore.VERSION_1_3.equals(cu.getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true)); - fImportsAdded= new HashSet<>(); fUnresolvedTypes= new HashMap<>(); } @@ -364,12 +360,10 @@ public boolean process(IProgressMonitor monitor) throws JavaModelException { TypeNameMatchCollector collector= new TypeNameMatchCollector(typesFound); new SearchEngine().searchAllTypeNames(null, allTypes, scope, collector, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor); - boolean is50OrHigher= JavaModelUtil.is50OrHigher(project); - for (TypeNameMatch curr : typesFound) { UnresolvedTypeData data= fUnresolvedTypes.get(curr.getSimpleTypeName()); - if (data != null && isVisible(curr) && isOfKind(curr, data.typeKinds, is50OrHigher)) { - if (fAllowDefaultPackageImports || curr.getPackageName().length() > 0) { + if (data != null && isVisible(curr) && isOfKind(curr, data.typeKinds)) { + if (curr.getPackageName().length() > 0) { data.addInfo(curr); } } @@ -447,13 +441,13 @@ private TypeNameMatch[] processTypeInfo(List typeRefsFound) { } } - private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) { + private boolean isOfKind(TypeNameMatch curr, int typeKinds) { int flags= curr.getModifiers(); if (Flags.isAnnotation(flags)) { - return is50OrHigher && (typeKinds & TypeKinds.ANNOTATIONS) != 0; + return (typeKinds & TypeKinds.ANNOTATIONS) != 0; } if (Flags.isEnum(flags)) { - return is50OrHigher && (typeKinds & TypeKinds.ENUMS) != 0; + return (typeKinds & TypeKinds.ENUMS) != 0; } if (Flags.isInterface(flags)) { return (typeKinds & TypeKinds.INTERFACES) != 0; diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiCatchCleanUpCore.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiCatchCleanUpCore.java index bcb7a7bbb24..778060a6d12 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiCatchCleanUpCore.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/MultiCatchCleanUpCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020, 2024 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2025 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -57,7 +57,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -122,7 +121,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(final CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.MULTI_CATCH) || !JavaModelUtil.is1d7OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.MULTI_CATCH)) { return null; } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UnnecessaryArrayCreationCleanUpCore.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UnnecessaryArrayCreationCleanUpCore.java index c79c242fb91..4c10c0e3780 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UnnecessaryArrayCreationCleanUpCore.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/fix/UnnecessaryArrayCreationCleanUpCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019 Red Hat Inc. and others. + * Copyright (c) 2019, 2024 Red Hat Inc. and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -26,7 +26,6 @@ import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore; import org.eclipse.jdt.internal.corext.fix.UnnecessaryArrayCreationFixCore; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -71,7 +70,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_ARRAY_CREATION) || !JavaModelUtil.is50OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.REMOVE_UNNECESSARY_ARRAY_CREATION)) { return null; } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java index 61e00426fb7..62be4eaab7c 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.java @@ -113,6 +113,7 @@ private CorrectionMessages() { public static String LocalCorrectionsSubProcessor_surroundwith_trymulticatch_var_description; public static String LocalCorrectionsSubProcessor_add_default_case_description; public static String LocalCorrectionsSubProcessor_add_default_case_label_description; + public static String LocalCorrectionsSubProcessor_add_permitted_types_description; public static String LocalCorrectionsSubProcessor_remove_default_case_description; public static String LocalCorrectionsSubProcessor_add_missing_cases_description; public static String LocalCorrectionsSubProcessor_addthrows_description; @@ -350,6 +351,7 @@ private CorrectionMessages() { public static String QuickAssistProcessor_invertequals_description; public static String QuickAssistProcessor_typetoarrayInitializer_description; public static String QuickAssistProcessor_createmethodinsuper_description; + public static String QuickAssistProcessor_create_permitted_switch_cases_desc; public static String LinkedNamesAssistProposal_proposalinfo; public static String LinkedNamesAssistProposal_description; public static String QuickTemplateProcessor_surround_label; diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties index a614b2f6014..ea95a51666f 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/CorrectionMessages.properties @@ -88,6 +88,7 @@ LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description=Surround wit LocalCorrectionsSubProcessor_surroundwith_trymulticatch_var_description=Change type of ''{0}'' to ''{1}'' and surround with try/multi-catch LocalCorrectionsSubProcessor_add_default_case_description=Add 'default' case LocalCorrectionsSubProcessor_add_default_case_label_description=Add 'default' case label +LocalCorrectionsSubProcessor_add_permitted_types_description=Add permitted type cases LocalCorrectionsSubProcessor_remove_default_case_description=Remove 'default' case LocalCorrectionsSubProcessor_add_missing_cases_description=Add missing case statements LocalCorrectionsSubProcessor_addthrows_description=Add throws declaration @@ -452,6 +453,7 @@ QuickAssistProcessor_create_new_impl=Create new implementation of ''{0}'' QuickAssistProcessor_create_new_impl_desc=Open the New > Class wizard. QuickAssistProcessor_create_new_interface_impl=Create new interface, extending ''{0}'' QuickAssistProcessor_create_new_interface_impl_desc=Open the New > Interface wizard. +QuickAssistProcessor_create_permitted_switch_cases_desc=Add permitted type case stubs. LinkedNamesAssistProposal_proposalinfo=Link all references for a local rename (does not change references in other files) LinkedNamesAssistProposal_description=Rename in file diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/GetterSetterCorrectionBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/GetterSetterCorrectionBaseSubProcessor.java index 8c9075b7c6d..2394852bd00 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/GetterSetterCorrectionBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/GetterSetterCorrectionBaseSubProcessor.java @@ -31,7 +31,6 @@ 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.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; @@ -59,7 +58,6 @@ import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.refactoring.RefactoringAvailabilityTesterCore; import org.eclipse.jdt.internal.corext.refactoring.sef.SelfEncapsulateFieldRefactoring; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.text.java.IInvocationContext; @@ -339,15 +337,13 @@ private static boolean isBoolean(ProposalParameter context) { private static Expression getAssignedValue(ProposalParameter context) { ASTNode parent= context.accessNode.getParent(); ASTRewrite astRewrite= context.astRewrite; - IJavaProject javaProject= context.compilationUnit.getJavaProject(); IMethodBinding getter= findGetter(context); Expression getterExpression= null; if (getter != null) { getterExpression= astRewrite.getAST().newSimpleName("placeholder"); //$NON-NLS-1$ } ITypeBinding type= context.variableBinding.getType(); - boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject); - Expression result= GetterSetterUtil.getAssignedValue(parent, astRewrite, getterExpression, type, is50OrHigher); + Expression result= GetterSetterUtil.getAssignedValue(parent, astRewrite, getterExpression, type); if (result != null && getterExpression != null && getterExpression.getParent() != null) { getterExpression.getParent().setStructuralProperty(getterExpression.getLocationInParent(), createMethodInvocation(context, getter, null)); } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java index f0eba4c7888..a912ac9e31c 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/IProposalRelevance.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2012, 2023 IBM Corporation and others. + * Copyright (c) 2012, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -30,6 +30,7 @@ public interface IProposalRelevance { int CREATE_NON_STATIC_ACCESS_USING_DECLARING_TYPE= 12; int CREATE_INDIRECT_ACCESS_TO_STATIC= 12; int CREATE_NON_STATIC_ACCESS_USING_INSTANCE_TYPE= 11; + int ADD_PERMITTED_TYPES= 11; int REMOVE_UNUSED_CAST= 10; int ADD_UNIMPLEMENTED_METHODS= 10; diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsBaseSubProcessor.java new file mode 100644 index 00000000000..3815cf2b80c --- /dev/null +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsBaseSubProcessor.java @@ -0,0 +1,2012 @@ +/******************************************************************************* + * Copyright (c) 2024, 2025 IBM Corporation and others. + * + * This program and the accompanying materials + * are made available under the terms of the Eclipse Public License 2.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * IBM Corporation - initial API and implementation + * Red Hat Inc. - refactored to base version in jdt.core.manipulation + *******************************************************************************/ +package org.eclipse.jdt.internal.ui.text.correction; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Hashtable; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import org.eclipse.core.runtime.CoreException; + +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.IMethod; +import org.eclipse.jdt.core.IType; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.core.Signature; +import org.eclipse.jdt.core.compiler.IProblem; +import org.eclipse.jdt.core.dom.AST; +import org.eclipse.jdt.core.dom.ASTNode; +import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; +import org.eclipse.jdt.core.dom.Annotation; +import org.eclipse.jdt.core.dom.Assignment; +import org.eclipse.jdt.core.dom.Block; +import org.eclipse.jdt.core.dom.BodyDeclaration; +import org.eclipse.jdt.core.dom.CatchClause; +import org.eclipse.jdt.core.dom.ClassInstanceCreation; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.EnumDeclaration; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.ExpressionStatement; +import org.eclipse.jdt.core.dom.FieldAccess; +import org.eclipse.jdt.core.dom.FieldDeclaration; +import org.eclipse.jdt.core.dom.IBinding; +import org.eclipse.jdt.core.dom.IMethodBinding; +import org.eclipse.jdt.core.dom.ITypeBinding; +import org.eclipse.jdt.core.dom.IVariableBinding; +import org.eclipse.jdt.core.dom.IfStatement; +import org.eclipse.jdt.core.dom.InfixExpression; +import org.eclipse.jdt.core.dom.Initializer; +import org.eclipse.jdt.core.dom.InstanceofExpression; +import org.eclipse.jdt.core.dom.LambdaExpression; +import org.eclipse.jdt.core.dom.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.NodeFinder; +import org.eclipse.jdt.core.dom.PackageDeclaration; +import org.eclipse.jdt.core.dom.ProvidesDirective; +import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.ReturnStatement; +import org.eclipse.jdt.core.dom.SimpleName; +import org.eclipse.jdt.core.dom.SingleVariableDeclaration; +import org.eclipse.jdt.core.dom.Statement; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; +import org.eclipse.jdt.core.dom.SwitchCase; +import org.eclipse.jdt.core.dom.SwitchExpression; +import org.eclipse.jdt.core.dom.SwitchStatement; +import org.eclipse.jdt.core.dom.ThrowStatement; +import org.eclipse.jdt.core.dom.TryStatement; +import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.TypeDeclaration; +import org.eclipse.jdt.core.dom.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.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; +import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.TypeLocation; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; +import org.eclipse.jdt.core.manipulation.CUCorrectionProposalCore; +import org.eclipse.jdt.core.manipulation.ChangeCorrectionProposalCore; +import org.eclipse.jdt.core.refactoring.CompilationUnitChange; +import org.eclipse.jdt.core.search.IJavaSearchConstants; +import org.eclipse.jdt.core.search.IJavaSearchScope; +import org.eclipse.jdt.core.search.SearchEngine; +import org.eclipse.jdt.core.search.SearchMatch; +import org.eclipse.jdt.core.search.SearchParticipant; +import org.eclipse.jdt.core.search.SearchPattern; +import org.eclipse.jdt.core.search.SearchRequestor; + +import org.eclipse.jdt.internal.core.manipulation.JavaManipulationPlugin; +import org.eclipse.jdt.internal.core.manipulation.StubUtility; +import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; +import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; +import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; +import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2Core; +import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; +import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.dom.Bindings; +import org.eclipse.jdt.internal.corext.dom.BodyDeclarationRewrite; +import org.eclipse.jdt.internal.corext.dom.CodeScopeBuilder; +import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; +import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; +import org.eclipse.jdt.internal.corext.dom.Selection; +import org.eclipse.jdt.internal.corext.dom.TypeRules; +import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; +import org.eclipse.jdt.internal.corext.fix.CodeStyleFixCore; +import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore; +import org.eclipse.jdt.internal.corext.fix.IProposableFix; +import org.eclipse.jdt.internal.corext.fix.SealedClassFixCore; +import org.eclipse.jdt.internal.corext.fix.UnusedCodeFixCore; +import org.eclipse.jdt.internal.corext.refactoring.code.Invocations; +import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil; +import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; +import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchAnalyzer; +import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; +import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer; +import org.eclipse.jdt.internal.corext.refactoring.util.SurroundWithAnalyzer; +import org.eclipse.jdt.internal.corext.util.JavaModelUtil; +import org.eclipse.jdt.internal.corext.util.Messages; + +import org.eclipse.jdt.ui.cleanup.CleanUpOptions; +import org.eclipse.jdt.ui.text.java.IInvocationContext; +import org.eclipse.jdt.ui.text.java.IProblemLocation; +import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposalCore; + +import org.eclipse.jdt.internal.ui.fix.CodeStyleCleanUpCore; +import org.eclipse.jdt.internal.ui.fix.UnnecessaryCodeCleanUpCore; +import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.ChangeDescription; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.InsertDescription; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.RemoveDescription; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ConstructorFromSuperclassProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateNewObjectProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateObjectReferenceProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateVariableReferenceProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.MissingAnnotationAttributesProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ModifierChangeCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.NewMethodCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposalCore; +import org.eclipse.jdt.internal.ui.util.ASTHelper; + +public abstract class LocalCorrectionsBaseSubProcessor { + + private final String ADD_EXCEPTION_TO_THROWS_ID= "org.eclipse.jdt.ui.correction.addThrowsDecl"; //$NON-NLS-1$ + + private final String ADD_FIELD_QUALIFICATION_ID= "org.eclipse.jdt.ui.correction.qualifyField"; //$NON-NLS-1$ + + public static final int SURROUND_WITH_TRY_CATCH= 0x100; + public static final int SURROUND_WITH_TRY_MULTI_CATCH= 0x101; + public static final int ADD_EXCEPTION_TO_CATCH= 0x102; + public static final int ADD_EXCEPTION_TO_MULTI_CATCH= 0x103; + public static final int ADD_THROWS= 0x104; + public static final int ADD_ADDITIONAL_CATCH= 0x105; + public static final int STATIC_INDIRECT_ACCESS= 0x200; + public static final int STATIC_NON_STATIC_ACCESS_USING_TYPE= 0x201; + public static final int STATIC_INSTANCE_ACCESS= 0x202; + public static final int INITIALIZE_VARIABLE=0x203; + public static final int ADD_CONSTRUCTOR_FROM_SUPERCLASS= 0x204; + + private static final int ADD_NEW_OBJECT= 0; + + private static final int ADD_NEW_OBJECT_2= 0; + + private static final int ADD_NEW_OBJECT_3= 0; + + private static final int CREATE_OBJECT_REFERENCE= 0; + + private static final int CREATE_VARIABLE_REFERENCE= 0; + + public static final int UNUSED_CODE= 0x300; + public static final int RENAME_CODE= 0x301; + public static final int REMOVE_REDUNDANT_SUPERINTERFACE= 0x302; + public static final int REMOVE_SEMICOLON= 0x303; + public static final int REMOVE_UNNECESSARY_CAST= 0x304; + public static final int REMOVE_UNNECESSARY_INSTANCEOF= 0x305; + public static final int UNQUALIFY_ENUM_CONSTANT= 0x306; + public static final int UNQUALIFIED_FIELD_ACCESS= 0x307; + public static final int MOVE_ELSE_CLAUSE= 0x308; + public static final int CHANGE_EXTENDS_TO_IMPLEMENTS= 0x309; + public static final int CHANGE_TO_INTERFACE= 0x30a; + public static final int ADD_PERMITTED_TYPE= 0x30b; + public static final int ADD_SEALED_SUPERTYPE= 0x30c; + public static final int REMOVE_PROPOSAL= 0x30d; + public static final int RETURN_ALLOCATED_OBJECT= 0x30e; + public static final int CREATE_PARAMETER= 0x400; + public static final int CHANGE_CODE= 0x401; + public static final int MISSING_ANNOTATION_ATTRIBUTES= 0x401; + public static final int INSERT_BREAK_STATEMENT= 0x402; + public static final int INSERT_FALL_THROUGH= 0x403; + public static final int INSERT_CASES_OMITTED= 0x404; + public static final int REPLACE_FIELD_ACCESS= 0x405; + public static final int ADD_MISSING_CASE= 0x406; + public static final int CREATE_DEFAULT= 0x407; + public static final int ADD_OVERRIDE= 0x408; + public static final int CHANGE_MODIFIER= 0x409; + public static final int CREATE_CONSTRUCTOR= 0x40a; + public static final int REMOVE_DEFAULT= 0x40b; + public static final int ADD_PERMITTED_TYPES= 0x40c; + + public void getUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ICompilationUnit cu= context.getCompilationUnit(); + + CompilationUnit astRoot= context.getASTRoot(); + ASTNode selectedNode= problem.getCoveringNode(astRoot); + if (selectedNode == null) { + return; + } + while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression) + && (selectedNode.getLocationInParent() != LambdaExpression.BODY_PROPERTY) && !(selectedNode instanceof MethodReference)) { + selectedNode= selectedNode.getParent(); + } + if (selectedNode == null) { + return; + } + boolean isSelectedNodeThrowStatement= false; + if (selectedNode instanceof ThrowStatement) { + isSelectedNodeThrowStatement= true; + } + + int offset= selectedNode.getStartPosition(); + int length= selectedNode.getLength(); + int selectionEnd= context.getSelectionOffset() + context.getSelectionLength(); + if (selectionEnd > offset + length) { + // extend the selection if more than one statement is selected (bug 72149) + length= selectionEnd - offset; + } + + //Surround with proposals + SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length); + if (refactoring == null) + return; + + List affectedLocals= new ArrayList<>(); + SimpleName vName= null; + ITypeBinding vType= null; + if (selectedNode.getAST().apiLevel() >= ASTHelper.JLS10 && (selectedNode instanceof VariableDeclarationStatement)) { + for (Object o : ((VariableDeclarationStatement) selectedNode).fragments()) { + VariableDeclarationFragment v= ((VariableDeclarationFragment) o); + vName= v.getName(); + vType= ((VariableDeclarationStatement) selectedNode).getType().resolveBinding(); + } + + // If no references to 'var' type exist, entire statement will be placed in try block + SurroundWithTryCatchAnalyzer analyzer= new SurroundWithTryCatchAnalyzer(cu, Selection.createFromStartLength(offset, length)); + astRoot.accept(analyzer); + affectedLocals= Arrays.asList(analyzer.getAffectedLocals()).stream().map(f -> f.getName().getIdentifier()).collect(Collectors.toList()); + } + + refactoring.setLeaveDirty(true); + if (refactoring.checkActivationBasics(astRoot).isOK() && !isSelectedNodeThrowStatement) { + String label; + if ((vType != null) && (vName != null) && ASTNodes.isVarType(selectedNode, astRoot) && affectedLocals.contains(vName.getIdentifier())) { + label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_var_description, new Object[] { vName.getIdentifier(), vType.getName() }); + } else { + label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description; + } + RefactoringCorrectionProposalCore proposal= new RefactoringCorrectionProposalCore(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH); + proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel()); + proposals.add(refactoringCorrectionProposalToT(proposal, SURROUND_WITH_TRY_CATCH)); + } + + refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length, true); + if (refactoring == null) + return; + + refactoring.setLeaveDirty(true); + if (refactoring.checkActivationBasics(astRoot).isOK()) { + String label; + if ((vType != null) && (vName != null) && ASTNodes.isVarType(selectedNode, astRoot) && affectedLocals.contains(vName.getIdentifier())) { + label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_var_description, new Object[] { vName.getIdentifier(), vType.getName() }); + } else { + label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description; + } + RefactoringCorrectionProposalCore proposal= new RefactoringCorrectionProposalCore(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH); + proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel()); + proposals.add(refactoringCorrectionProposalToT(proposal, SURROUND_WITH_TRY_MULTI_CATCH)); + } + + //Catch exception + BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); + if (decl == null) { + return; + } + + ASTNode enclosingNode= SurroundWithAnalyzer.getEnclosingNode(selectedNode); + if (enclosingNode == null) { + return; + } + + ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(enclosingNode, Selection.createFromStartLength(offset, length)); + if (uncaughtExceptions.length == 0) { + return; + } + + TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode); + AST ast= astRoot.getAST(); + if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES2_PROPERTY)) { + addAdditionalCatchProposal(context, proposals, cu, selectedNode, offset, length, decl, uncaughtExceptions, surroundingTry, ast); + + List catchClauses= surroundingTry.catchClauses(); + List filteredExceptions= SurroundWithTryCatchRefactoring.filterSubtypeExceptions(uncaughtExceptions); + ASTRewrite rewrite= ASTRewrite.create(ast); + + if (catchClauses != null && catchClauses.size() == 1) { + String label= filteredExceptions.size() > 1 + ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description + : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description; + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH); + ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); + + CatchClause catchClause= catchClauses.get(0); + Type originalType= catchClause.getException().getType(); + + if (originalType instanceof UnionType) { + UnionType unionType= (UnionType) originalType; + ListRewrite listRewrite= rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY); + @SuppressWarnings("unchecked") + List existingTypes= new ArrayList<>(unionType.types()); + + for (int i= 0; i < filteredExceptions.size(); i++) { + Type addedType= addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i); + boolean isReplaced= false; + + for (Type existingType : existingTypes) { + if (existingType.resolveBinding().isSubTypeCompatible(filteredExceptions.get(i))) { + listRewrite.replace(existingType, addedType, null); + isReplaced= true; + break; + } + } + + if (!isReplaced) { + listRewrite.insertLast(addedType, null); + } + } + } else { + Type firstType= null; + List typesToAdd= new ArrayList<>(); + + for (int i= 0; i < filteredExceptions.size(); i++) { + Type addedType= addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i); + + if (originalType.resolveBinding().isSubTypeCompatible(filteredExceptions.get(i))) { + firstType= addedType; + } else { + typesToAdd.add(addedType); + } + } + + if (!typesToAdd.isEmpty()) { + UnionType newUnionType= ast.newUnionType(); + List types= newUnionType.types(); + + if (firstType == null) { + types.add(ASTNodes.createMoveTarget(rewrite, originalType)); + } else { + types.add(firstType); + } + types.addAll(typesToAdd); + + rewrite.replace(originalType, newUnionType, null); + } else if (firstType != null) { + rewrite.replace(originalType, firstType, null); + } + } + + proposals.add(linkedCorrectionProposalToT(proposal, ADD_EXCEPTION_TO_CATCH)); + } else if (catchClauses != null && catchClauses.isEmpty() && filteredExceptions.size() > 1) { + String label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description; + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH); + ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); + + CodeScopeBuilder.Scope scope= CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length); + scope.setCursor(offset); + + CatchClause newCatchClause= ast.newCatchClause(); + String varName= StubUtility.getExceptionVariableName(cu.getJavaProject()); + String name= scope.createName(varName, false); + SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); + var.setName(ast.newSimpleName(name)); + + UnionType newUnionType= ast.newUnionType(); + List types= newUnionType.types(); + + for (int i= 0; i < filteredExceptions.size(); i++) { + types.add(addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i)); + } + + String nameKey= "name"; //$NON-NLS-1$ + proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey); + var.setType(newUnionType); + newCatchClause.setException(var); + String catchBody= StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n')); //$NON-NLS-1$ + + if (catchBody != null) { + ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT); + newCatchClause.getBody().statements().add(node); + } + + ListRewrite listRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY); + listRewrite.insertFirst(newCatchClause, null); + proposals.add(linkedCorrectionProposalToT(proposal, ADD_EXCEPTION_TO_MULTI_CATCH)); + } + } + + //Add throws declaration + if (enclosingNode instanceof MethodDeclaration) { + MethodDeclaration methodDecl= (MethodDeclaration) enclosingNode; + IMethodBinding binding= methodDecl.resolveBinding(); + boolean isApplicable= binding != null; + + if (isApplicable) { + IMethodBinding overriddenMethod= Bindings.findOverriddenMethod(binding, true); + + if (overriddenMethod != null) { + isApplicable= overriddenMethod.getDeclaringClass().isFromSource(); + + if (!isApplicable) { // bug 349051 + ITypeBinding[] exceptionTypes= overriddenMethod.getExceptionTypes(); + ArrayList unhandledExceptions= new ArrayList<>(uncaughtExceptions.length); + + for (ITypeBinding curr : uncaughtExceptions) { + if (isSubtype(curr, exceptionTypes)) { + unhandledExceptions.add(curr); + } + } + + uncaughtExceptions= unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]); + isApplicable= uncaughtExceptions.length > 0; + } + } + + if (isApplicable && binding != null) { + ITypeBinding[] methodExceptions= binding.getExceptionTypes(); + ArrayList unhandledExceptions= new ArrayList<>(uncaughtExceptions.length); + + for (ITypeBinding curr : uncaughtExceptions) { + if (!isSubtype(curr, methodExceptions)) { + unhandledExceptions.add(curr); + } + } + + uncaughtExceptions= unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]); + + List exceptions= methodDecl.thrownExceptionTypes(); + int nExistingExceptions= exceptions.size(); + + ChangeDescription[] desc= new ChangeDescription[nExistingExceptions + uncaughtExceptions.length]; + for (int i= 0; i < exceptions.size(); i++) { + Type elem= exceptions.get(i); + + if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) { + desc[i]= new RemoveDescription(); + } + } + + for (int i= 0; i < uncaughtExceptions.length; i++) { + desc[i + nExistingExceptions]= new InsertDescription(uncaughtExceptions[i], ""); //$NON-NLS-1$ + } + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description; + + ChangeMethodSignatureProposalCore proposal= new ChangeMethodSignatureProposalCore(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION); + + for (int i= 0; i < uncaughtExceptions.length; i++) { + addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions)); + } + + proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID); + proposals.add(changeMethodSignatureProposalToT(proposal, ADD_THROWS)); + } + } + } + } + + private Type addNewException(AST ast, List filteredExceptions, ASTRewrite rewrite, LinkedCorrectionProposalCore proposal, ImportRewrite imports, + ImportRewriteContext importRewriteContext, int i) { + ITypeBinding excBinding= filteredExceptions.get(i); + Type type= imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION); + + String typeKey= "type" + i; //$NON-NLS-1$ + proposal.addLinkedPosition(rewrite.track(type), false, typeKey); + addExceptionTypeLinkProposals(proposal, excBinding, typeKey); + + return type; + } + + private void addAdditionalCatchProposal(IInvocationContext context, Collection proposals, ICompilationUnit cu, ASTNode selectedNode, int offset, int length, + BodyDeclaration decl, + ITypeBinding[] uncaughtExceptions, TryStatement surroundingTry, AST ast) throws CoreException { + ASTRewrite rewrite= ASTRewrite.create(surroundingTry.getAST()); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description; +// Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH); + + ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); + + CodeScopeBuilder.Scope scope= CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length); + scope.setCursor(offset); + + ListRewrite clausesRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY); + for (int i= 0; i < uncaughtExceptions.length; i++) { + ITypeBinding excBinding= uncaughtExceptions[i]; + String varName= StubUtility.getExceptionVariableName(cu.getJavaProject()); + String name= scope.createName(varName, false); + SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); + var.setName(ast.newSimpleName(name)); + var.setType(imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION)); + CatchClause newClause= ast.newCatchClause(); + newClause.setException(var); + String catchBody= StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n')); + if (catchBody != null) { + ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT); + newClause.getBody().statements().add(node); + } + clausesRewrite.insertLast(newClause, null); + + String typeKey= "type" + i; //$NON-NLS-1$ + String nameKey= "name" + i; //$NON-NLS-1$ + proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey); + proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey); + addExceptionTypeLinkProposals(proposal, excBinding, typeKey); + } + proposals.add(linkedCorrectionProposalToT(proposal, ADD_ADDITIONAL_CATCH)); + } + + private void addExceptionTypeLinkProposals(LinkedCorrectionProposalCore proposal, ITypeBinding exc, String key) { + // all super classes except Object + while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$ + proposal.addLinkedPositionProposal(key, exc); + exc= exc.getSuperclass(); + } + } + + + private boolean isSubtype(ITypeBinding curr, ITypeBinding[] addedExceptions) { + while (curr != null) { + for (ITypeBinding addedException : addedExceptions) { + if (curr == addedException) { + return true; + } + } + curr= curr.getSuperclass(); + } + return false; + } + + + public void getUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ICompilationUnit cu= context.getCompilationUnit(); + + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (!(selectedNode instanceof Name)) { + return; + } + Name name= (Name) selectedNode; + IBinding binding= name.resolveBinding(); + if (!(binding instanceof IVariableBinding)) { + return; + } + IVariableBinding varBinding= (IVariableBinding) binding; + + CompilationUnit astRoot= context.getASTRoot(); + ASTNode node= astRoot.findDeclaringNode(binding); + if (node instanceof VariableDeclarationFragment) { + ASTRewrite rewrite= ASTRewrite.create(node.getAST()); + + VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; + if (fragment.getInitializer() != null) { + return; + } + Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); + if (expression == null) { + return; + } + rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description; + + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE); + proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$ + proposals.add(linkedCorrectionProposalToT(proposal, INITIALIZE_VARIABLE)); + } + } + + public void getConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode == null) { + return; + } + + TypeDeclaration typeDeclaration= null; + if (selectedNode.getLocationInParent() == TypeDeclaration.NAME_PROPERTY) { + typeDeclaration= (TypeDeclaration) selectedNode.getParent(); + } else { + BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode); + if (declaration instanceof Initializer && problem.getProblemId() == IProblem.UnhandledExceptionInDefaultConstructor) { + getUncaughtExceptionProposals(context, problem, proposals); + } + return; + } + + ITypeBinding binding= typeDeclaration.resolveBinding(); + if (binding == null || binding.getSuperclass() == null) { + return; + } + ICompilationUnit cu= context.getCompilationUnit(); + for (IMethodBinding curr : binding.getSuperclass().getDeclaredMethods()) { + if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) { + proposals.add(constructorFromSuperClassProposalToT(new ConstructorFromSuperclassProposalCore(cu, typeDeclaration, curr, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS), ADD_CONSTRUCTOR_FROM_SUPERCLASS)); + } + } + } + + public void getNewObjectProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode == null) { + return; + } + ASTNode selectedExpressionStatement= ASTNodes.getParent(selectedNode, ASTNode.EXPRESSION_STATEMENT); + if (selectedExpressionStatement != null) { + ExpressionStatement expressionStatement= (ExpressionStatement) selectedExpressionStatement; + Expression expression= expressionStatement.getExpression(); + ITypeBinding binding= null; + if (expression instanceof MethodInvocation) { + Expression expression2= ((MethodInvocation) expression).getExpression(); + binding= expression2 == null ? null : expression2.resolveTypeBinding(); + } + if (binding == null) { + return; + } + ICompilationUnit cu= context.getCompilationUnit(); + CreateNewObjectProposalCore createNewObjectProposal= new CreateNewObjectProposalCore(cu, expressionStatement, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); + if (createNewObjectProposal.hasProposal()) { + proposals.add(createNewObjectProposalToT(createNewObjectProposal, ADD_NEW_OBJECT)); + } + return; + } + + ASTNode selectedVariableDeclarationFragment= ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_FRAGMENT); + if (selectedVariableDeclarationFragment != null) { + VariableDeclarationFragment vdf= (VariableDeclarationFragment) selectedVariableDeclarationFragment; + VariableDeclarationStatement vds= (VariableDeclarationStatement) ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_STATEMENT); + if (vds == null) { + return; + } + Type type= vds.getType(); + ITypeBinding binding= type == null ? null : type.resolveBinding(); + if (binding == null) { + return; + } + ICompilationUnit cu= context.getCompilationUnit(); + CreateNewObjectProposalCore createNewObjectProposal= new CreateNewObjectProposalCore(cu, vdf, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); + if (createNewObjectProposal.hasProposal()) { + proposals.add(createNewObjectProposalToT(createNewObjectProposal, ADD_NEW_OBJECT_2)); + } + /* create instance of qualifier, ex; X in X.s; */ + Expression initializer= vdf.getInitializer(); + if(initializer instanceof QualifiedName == false) { + return; + } + QualifiedName qualifiedName= (QualifiedName)initializer; + IBinding resolveBinding= qualifiedName.getName().resolveBinding(); + if(resolveBinding instanceof IVariableBinding == false) { + return; + } + CreateNewObjectProposalCore createNewObjectProposal2= new CreateNewObjectProposalCore(cu, vdf, (IVariableBinding)resolveBinding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); + if (createNewObjectProposal2.hasProposal()) { + proposals.add(createNewObjectProposalToT(createNewObjectProposal2, ADD_NEW_OBJECT_3)); + } + return; + } + if (problem.getProblemId() == IProblem.StaticMethodRequested || + problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { + getUncaughtExceptionProposals(context, problem, proposals); + } + } + + public void getObjectReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + ITypeBinding binding= null; + if (selectedNode == null) { + return; + } + if (problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { + if (selectedNode instanceof QualifiedName) { + QualifiedName qualifiedName= (QualifiedName) selectedNode; + Name qualifier= qualifiedName.getQualifier(); + binding= qualifier.resolveTypeBinding(); + } + } else { + selectedNode= ASTNodes.getParent(selectedNode, ASTNode.EXPRESSION_STATEMENT); + if (selectedNode == null) { + if (problem.getProblemId() == IProblem.StaticMethodRequested) { + getUncaughtExceptionProposals(context, problem, proposals); + } + return; + } + ExpressionStatement expressionStatement= (ExpressionStatement) selectedNode; + Expression expression= expressionStatement.getExpression(); + if (expression instanceof MethodInvocation) { + Expression expression2= ((MethodInvocation) expression).getExpression(); + binding= expression2 == null ? null : expression2.resolveTypeBinding(); + } + } + if (binding == null) { + return; + } + ICompilationUnit cu= context.getCompilationUnit(); + CreateObjectReferenceProposalCore createObjectReferenceProposal= new CreateObjectReferenceProposalCore(cu, selectedNode, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); + if (createObjectReferenceProposal.hasProposal()) { + proposals.add(createObjectReferenceProposalToT(createObjectReferenceProposal, CREATE_OBJECT_REFERENCE)); + } + } + + public void getVariableReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode == null) { + return; + } + selectedNode= ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_FRAGMENT); + if (selectedNode == null) { + if (problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { + getUncaughtExceptionProposals(context, problem, proposals); + } + return; + } + VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode; + Type type= null; + if(fragment.getParent() instanceof VariableDeclarationStatement) { + type= ((VariableDeclarationStatement)fragment.getParent()).getType(); + } else if(fragment.getParent() instanceof FieldDeclaration) { + type= ((FieldDeclaration)fragment.getParent()).getType(); + } + if (type == null) { + return; + } + ITypeBinding binding= type.resolveBinding(); + if (binding == null) { + return; + } + ICompilationUnit cu= context.getCompilationUnit(); + CreateVariableReferenceProposalCore createVariableReferenceProposal= new CreateVariableReferenceProposalCore(cu, fragment, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); + if (createVariableReferenceProposal.hasProposal()) { + proposals.add(createVariableReferenceProposalToT(createVariableReferenceProposal, CREATE_VARIABLE_REFERENCE)); + } + } + + public void getRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (!(selectedNode instanceof Name)) { + return; + } + ASTNode node= ASTNodes.getNormalizedNode(selectedNode); + + ASTRewrite rewrite= ASTRewrite.create(node.getAST()); + rewrite.remove(node, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface; + + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE); + proposals.add(astRewriteCorrectionProposalToT(proposal, REMOVE_REDUNDANT_SUPERINTERFACE)); + + } + + public void getSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + String label= CorrectionMessages.LocalCorrectionsSubProcessor_removesemicolon_description; + ReplaceCorrectionProposalCore proposal= new ReplaceCorrectionProposalCore(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", IProposalRelevance.REMOVE_SEMICOLON); //$NON-NLS-1$ + proposals.add(replaceCorrectionProposalToT(proposal, REMOVE_SEMICOLON)); + } + + public void getUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + IProposableFix fix= UnusedCodeFixCore.createRemoveUnusedCastFix(context.getASTRoot(), problem); + if (fix != null) { + Map options= new Hashtable<>(); + options.put(CleanUpConstants.REMOVE_UNNECESSARY_CASTS, CleanUpOptions.TRUE); + FixCorrectionProposalCore proposal= new FixCorrectionProposalCore(fix, new UnnecessaryCodeCleanUpCore(options), IProposalRelevance.REMOVE_UNUSED_CAST, context); + proposals.add(fixCorrectionProposalToT(proposal, REMOVE_UNNECESSARY_CAST)); + } + } + + public void getUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + + ASTNode curr= ASTNodes.getUnparenthesedExpression(selectedNode); + + if (curr instanceof InstanceofExpression) { + AST ast= curr.getAST(); + + ASTRewrite rewrite= ASTRewrite.create(ast); + + InstanceofExpression inst= (InstanceofExpression) curr; + + InfixExpression expression= ast.newInfixExpression(); + expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand())); + expression.setOperator(InfixExpression.Operator.NOT_EQUALS); + expression.setRightOperand(ast.newNullLiteral()); + + rewrite.replace(inst, expression, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.UNNECESSARY_INSTANCEOF); + proposals.add(astRewriteCorrectionProposalToT(proposal, REMOVE_UNNECESSARY_INSTANCEOF)); + } + } + + public void getIllegalQualifiedEnumConstantLabelProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot()); + + ASTNode curr= ASTNodes.getUnparenthesedExpression(coveringNode); + + if (!(curr instanceof QualifiedName)) { + return; + } + + SimpleName simpleName= ((QualifiedName) curr).getName(); + final ASTRewrite rewrite= ASTRewrite.create(curr.getAST()); + rewrite.replace(coveringNode, simpleName, null); + + String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replace_with_unqualified_enum_constant, BasicElementLabels.getJavaElementName(simpleName.getIdentifier())); + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_WITH_UNQUALIFIED_ENUM_CONSTANT); + proposals.add(astRewriteCorrectionProposalToT(proposal, UNQUALIFY_ENUM_CONSTANT)); + } + + public void getUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + IProposableFix fix= CodeStyleFixCore.createAddFieldQualifierFix(context.getASTRoot(), problem); + if (fix != null) { + Map options= new HashMap<>(); + options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, CleanUpOptions.TRUE); + options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, CleanUpOptions.TRUE); + FixCorrectionProposalCore proposal= new FixCorrectionProposalCore(fix, new CodeStyleCleanUpCore(options), IProposalRelevance.ADD_FIELD_QUALIFIER, context); + proposal.setCommandId(ADD_FIELD_QUALIFICATION_ID); + proposals.add(fixCorrectionProposalToT(proposal, UNQUALIFIED_FIELD_ACCESS)); + } + } + + public void getUnnecessaryElseProposalsBase(IInvocationContext context, IProblemLocation problem, Collection proposals) { + CompilationUnit root= context.getASTRoot(); + ASTNode selectedNode= problem.getCoveringNode(root); + if (selectedNode == null) { + return; + } + ASTNode parent= selectedNode.getParent(); + if (parent instanceof ExpressionStatement) { + parent= parent.getParent(); + } + if (!(parent instanceof IfStatement)) { + return; + } + IfStatement ifStatement= (IfStatement) parent; + ASTNode ifParent= ifStatement.getParent(); + if (!(ifParent instanceof Block) && !(ifParent instanceof SwitchStatement) && !ASTNodes.isControlStatementBody(ifStatement.getLocationInParent())) { + return; + } + + ASTRewrite rewrite= ASTRewrite.create(root.getAST()); + ASTNode placeholder= QuickAssistProcessorUtil.getCopyOfInner(rewrite, ifStatement.getElseStatement(), false); + if (placeholder == null) { + return; + } + rewrite.remove(ifStatement.getElseStatement(), null); + + if (ifParent instanceof Block) { + ListRewrite listRewrite= rewrite.getListRewrite(ifParent, Block.STATEMENTS_PROPERTY); + listRewrite.insertAfter(placeholder, ifStatement, null); + } else if (ifParent instanceof SwitchStatement) { + ListRewrite listRewrite= rewrite.getListRewrite(ifParent, SwitchStatement.STATEMENTS_PROPERTY); + listRewrite.insertAfter(placeholder, ifStatement, null); + } else { + Block block= root.getAST().newBlock(); + rewrite.replace(ifStatement, block, null); + block.statements().add(rewrite.createCopyTarget(ifStatement)); + block.statements().add(placeholder); + } + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeelse_description; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_ELSE); + proposals.add(astRewriteCorrectionProposalToT(proposal, MOVE_ELSE_CLAUSE)); + } + + + public void getInterfaceExtendsClassProposalsBase(IInvocationContext context, IProblemLocation problem, Collection proposals) { + CompilationUnit root= context.getASTRoot(); + ASTNode selectedNode= problem.getCoveringNode(root); + if (selectedNode == null) { + return; + } + while (selectedNode.getParent() instanceof Type) { + selectedNode= selectedNode.getParent(); + } + + StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); + if (locationInParent != TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) { + return; + } + + TypeDeclaration typeDecl= (TypeDeclaration) selectedNode.getParent(); + { + ASTRewrite rewrite= ASTRewrite.create(root.getAST()); + ASTNode placeHolder= rewrite.createMoveTarget(selectedNode); + ListRewrite interfaces= rewrite.getListRewrite(typeDecl, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); + interfaces.insertFirst(placeHolder, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_extendstoimplements_description; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_EXTENDS_TO_IMPLEMENTS); + proposals.add(astRewriteCorrectionProposalToT(proposal, CHANGE_EXTENDS_TO_IMPLEMENTS)); + } + { + ASTRewrite rewrite= ASTRewrite.create(root.getAST()); + + rewrite.set(typeDecl, TypeDeclaration.INTERFACE_PROPERTY, Boolean.TRUE, null); + + String typeName= typeDecl.getName().getIdentifier(); + String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_classtointerface_description, BasicElementLabels.getJavaElementName(typeName)); + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_CLASS_TO_INTERFACE); + proposals.add(astRewriteCorrectionProposalToT(proposal, CHANGE_TO_INTERFACE)); + } + } + + public void getTypeAsPermittedSubTypeProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + SealedClassFixCore fix= SealedClassFixCore.addTypeAsPermittedSubTypeProposal(context.getASTRoot(), problem); + if (fix != null) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + IType sealedType= SealedClassFixCore.getSealedType(selectedNode); + ICompilationUnit unit= SealedClassFixCore.getCompilationUnitForSealedType(sealedType); + + CUCorrectionProposalCore proposal= createCorrectionProposalFromCURewriteOperation(unit, fix, fix.getDisplayString(), IProposalRelevance.DECLARE_SEALED_AS_DIRECT_SUPER_TYPE); + proposals.add(cuCorrectionProposalToT(proposal, ADD_PERMITTED_TYPE)); + } + } + + public void getSealedAsDirectSuperTypeProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + SealedClassFixCore fix= SealedClassFixCore.addSealedAsDirectSuperTypeProposal(context.getASTRoot(), problem); + if (fix != null) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + IType permittedType= SealedClassFixCore.getPermittedType(selectedNode); + ICompilationUnit unit= permittedType.getCompilationUnit(); + + CUCorrectionProposalCore proposal= createCorrectionProposalFromCURewriteOperation(unit, fix, fix.getDisplayString(), IProposalRelevance.DECLARE_SEALED_AS_DIRECT_SUPER_TYPE); + proposals.add(cuCorrectionProposalToT(proposal, ADD_SEALED_SUPERTYPE)); + } + } + + private CUCorrectionProposalCore createCorrectionProposalFromCURewriteOperation(ICompilationUnit unit, CompilationUnitRewriteOperationsFixCore fix, String label, int relevance) { + try { + CompilationUnitChange change= fix.createChange(null); + CUCorrectionProposalCore proposal= new CUCorrectionProposalCore(label, unit, change, relevance); + return proposal; + } catch (CoreException e) { + // do nothing + } + return null; + } + + public void getAssignmentHasNoEffectProposalsBase(IInvocationContext context, IProblemLocation problem, Collection proposals) { + CompilationUnit root= context.getASTRoot(); + ASTNode selectedNode= problem.getCoveringNode(root); + if (!(selectedNode instanceof Assignment)) { + return; + } + ASTNode assignedNode= ((Assignment) selectedNode).getLeftHandSide(); + ASTNode assignExpression= ((Assignment) selectedNode).getRightHandSide(); + if (!(assignedNode instanceof SimpleName) && !(assignExpression instanceof SimpleName)) { + return; + } + + IBinding binding= (assignedNode instanceof SimpleName) ? ((SimpleName) assignedNode).resolveBinding() : ((SimpleName) assignExpression).resolveBinding(); + if (!(binding instanceof IVariableBinding)) { + return; + } + ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); + if (typeBinding == null) { + return; + } + IVariableBinding fieldBinding= Bindings.findFieldInHierarchy(typeBinding, binding.getName()); + if (fieldBinding == null || fieldBinding.getDeclaringClass() != typeBinding && Modifier.isPrivate(fieldBinding.getModifiers())) { + return; + } + + if (binding != fieldBinding) { + if (assignedNode instanceof SimpleName) { + String label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_left_hand_side_description; + proposals.add(astRewriteCorrectionProposalToT(createNoSideEffectProposal(context, (SimpleName) assignedNode, fieldBinding, label, IProposalRelevance.QUALIFY_LHS), CHANGE_CODE)); + } + if (assignExpression instanceof SimpleName) { + String label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_right_hand_side_description; + proposals.add(astRewriteCorrectionProposalToT(createNoSideEffectProposal(context, (SimpleName) assignExpression, fieldBinding, label, IProposalRelevance.QUALIFY_RHS), CHANGE_CODE)); + } + } + + if (binding == fieldBinding && ASTResolving.findParentBodyDeclaration(selectedNode) instanceof MethodDeclaration) { + SimpleName simpleName= (SimpleName) ((assignedNode instanceof SimpleName) ? assignedNode : assignExpression); + String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, BasicElementLabels.getJavaElementName(simpleName.getIdentifier())); + NewVariableCorrectionProposalCore proposal= new NewVariableCorrectionProposalCore(label, context.getCompilationUnit(), NewVariableCorrectionProposalCore.PARAM, simpleName, null, IProposalRelevance.CREATE_PARAMETER, false); + proposals.add(newVariableCorrectionProposalToT(proposal, CREATE_PARAMETER)); + } + + } + + private ASTRewriteCorrectionProposalCore createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) { + AST ast= nodeToQualify.getAST(); + + Expression qualifier; + if (Modifier.isStatic(fieldBinding.getModifiers())) { + ITypeBinding declaringClass= fieldBinding.getDeclaringClass(); + qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName()); + } else { + qualifier= ast.newThisExpression(); + } + + ASTRewrite rewrite= ASTRewrite.create(ast); + FieldAccess access= ast.newFieldAccess(); + access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify)); + access.setExpression(qualifier); + rewrite.replace(nodeToQualify, access, null); + + +// Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + return new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, relevance); + } + + public void getValueForAnnotationProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ICompilationUnit cu= context.getCompilationUnit(); + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Annotation) { + Annotation annotation= (Annotation) selectedNode; + if (annotation.resolveTypeBinding() == null) { + return; + } + MissingAnnotationAttributesProposalCore proposal= new MissingAnnotationAttributesProposalCore(cu, annotation, 10); + proposals.add(missingAnnotationAttributesProposalToT(proposal, MISSING_ANNOTATION_ATTRIBUTES)); + } + } + + public void getFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof SwitchCase && selectedNode.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) { + AST ast= selectedNode.getAST(); + ASTNode parent= selectedNode.getParent(); + + // insert break: + ASTRewrite rewrite= ASTRewrite.create(ast); + ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_BREAK_STATEMENT); + proposals.add(astRewriteCorrectionProposalToT(proposal, INSERT_BREAK_STATEMENT)); + + if (problem.getProblemId() == IProblem.IllegalFallthroughToPattern) + return; + + // insert //$FALL-THROUGH$: + rewrite= ASTRewrite.create(ast); + rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); + listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + ASTNode fallThroughComment= rewrite.createStringPlaceholder("//$FALL-THROUGH$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ + listRewrite.insertBefore(fallThroughComment, selectedNode, null); + + label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_fall_through; + proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_FALL_THROUGH); + proposals.add(astRewriteCorrectionProposalToT(proposal, INSERT_FALL_THROUGH)); + } + } + + public void getCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { + AST ast= selectedNode.getAST(); + SwitchStatement parent= (SwitchStatement) selectedNode.getParent(); + + for (Statement statement : (List) parent.statements()) { + if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { + + // insert //$CASES-OMITTED$: + ASTRewrite rewrite= ASTRewrite.create(ast); + rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); + ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ + listRewrite.insertBefore(casesOmittedComment, statement, null); + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED); + proposals.add(astRewriteCorrectionProposalToT(proposal, INSERT_CASES_OMITTED)); + break; + } + } + } + } + + public void getDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Name) { + IBinding binding= ((Name) selectedNode).resolveBinding(); + if (binding instanceof IVariableBinding) { + IVariableBinding variableBinding= (IVariableBinding) binding; + if (variableBinding.isField()) { + String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName(); + String fieldName= variableBinding.getName(); + String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName)); + if (methodName != null) { + AST ast= selectedNode.getAST(); + ASTRewrite astRewrite= ASTRewrite.create(ast); + ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true); + + MethodInvocation method= ast.newMethodInvocation(); + String qfn= importRewrite.addImport(methodName[0]); + method.setExpression(ast.newName(qfn)); + method.setName(ast.newSimpleName(methodName[1])); + ASTNode parent= selectedNode.getParent(); + ICompilationUnit cu= context.getCompilationUnit(); + // add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works): + if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is1d8OrHigher(cu.getJavaProject())) { + IMethodBinding methodBinding= Invocations.resolveBinding(parent); + if (methodBinding != null) { + ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); + int i= Invocations.getArguments(parent).indexOf(selectedNode); + if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) { + ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments(); + for (ITypeBinding typeArgument : typeArguments) { + typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); + if (!TypeRules.isJavaLangObject(typeArgument)) { + // add all type arguments if at least one is found to be necessary: + List typeArgumentsList= method.typeArguments(); + for (ITypeBinding t : typeArguments) { + typeArgument= Bindings.normalizeForDeclarationUse(t, ast); + typeArgumentsList.add(importRewrite.addImport(typeArgument, ast)); + } + break; + } + } + } + } + } + + astRewrite.replace(selectedNode, method, null); + + String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, + BasicElementLabels.getJavaElementName(ASTNodes.asString(method))); + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD); + proposal.setImportRewrite(importRewrite); + proposals.add(astRewriteCorrectionProposalToT(proposal, REPLACE_FIELD_ACCESS)); + } + } + } + } + } + + private Map resolveMap; + + private String[] getMethod(String fieldName) { + if (resolveMap == null) { + resolveMap= new HashMap<>(); + resolveMap.put("java.util.Collections.EMPTY_MAP", new String[] { "java.util.Collections", "emptyMap" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + resolveMap.put("java.util.Collections.EMPTY_SET", new String[] { "java.util.Collections", "emptySet" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + resolveMap.put("java.util.Collections.EMPTY_LIST", new String[] { "java.util.Collections", "emptyList" });//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ + } + return resolveMap.get(fieldName); + } + + public void getMissingEnumConstantCaseProposalsBase(IInvocationContext context, IProblemLocation problem, Collection proposals) { + for (T proposal : proposals) { + if (proposal instanceof ChangeCorrectionProposalCore) { + if (CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description.equals(((ChangeCorrectionProposalCore) proposal).getName())) { + return; + } + } + } + + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Expression) { + StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); + ASTNode parent= selectedNode.getParent(); + ITypeBinding binding; + List statements; + + if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) { + SwitchStatement statement= (SwitchStatement) parent; + binding= statement.getExpression().resolveTypeBinding(); + statements= statement.statements(); + } else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) { + SwitchExpression switchExpression= (SwitchExpression) parent; + binding= switchExpression.getExpression().resolveTypeBinding(); + statements= switchExpression.statements(); + } else { + return; + } + + if (binding == null || !binding.isEnum()) { + return; + } + + ArrayList missingEnumCases= new ArrayList<>(); + boolean hasDefault= evaluateMissingSwitchCasesBase(binding, statements, missingEnumCases); + if (missingEnumCases.size() == 0 && hasDefault) + return; + + createMissingCaseProposalsBase(context, parent, missingEnumCases, proposals); + } + } + + @SuppressWarnings("deprecation") + public boolean evaluateMissingSwitchCasesBase(ITypeBinding enumBindings, List switchStatements, ArrayList enumConstNames) { + for (IVariableBinding field : enumBindings.getDeclaredFields()) { + if (field.isEnumConstant()) { + enumConstNames.add(field.getName()); + } + } + + boolean hasDefault= false; + for (Statement curr : switchStatements) { + if (curr instanceof SwitchCase) { + SwitchCase switchCase= (SwitchCase) curr; + if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(switchCase.getAST())) { + List expressions= switchCase.expressions(); + if (expressions.size() == 0) { + hasDefault= true; + } else { + for (Expression expression : expressions) { + if (expression instanceof SimpleName) { + enumConstNames.remove(((SimpleName) expression).getFullyQualifiedName()); + } + } + } + } else { + Expression expression= ((SwitchCase) curr).getExpression(); + if (expression instanceof SimpleName) { + enumConstNames.remove(((SimpleName) expression).getFullyQualifiedName()); + } else if (expression == null) { + hasDefault= true; + } + } + } + } + return hasDefault; + } + + @SuppressWarnings("deprecation") + public void createMissingCaseProposalsBase(IInvocationContext context, ASTNode parent, ArrayList enumConstNames, Collection proposals) { + List statements; + Expression expression; + if (parent instanceof SwitchStatement) { + SwitchStatement switchStatement= (SwitchStatement) parent; + statements= switchStatement.statements(); + expression= switchStatement.getExpression(); + } else if (parent instanceof SwitchExpression) { + SwitchExpression switchExpression= (SwitchExpression) parent; + statements= switchExpression.statements(); + expression= switchExpression.getExpression(); + } else { + return; + } + int defaultIndex= statements.size(); + for (int i= 0; i < statements.size(); i++) { + Statement curr= statements.get(i); + if (curr instanceof SwitchCase) { + SwitchCase switchCase= (SwitchCase) curr; + if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(switchCase.getAST())) { + if (switchCase.expressions().size() == 0) { + defaultIndex= i; + break; + } + } else if (switchCase.getExpression() == null) { + defaultIndex= i; + break; + } + } + } + boolean hasDefault= defaultIndex < statements.size(); + + AST ast= parent.getAST(); + + if (enumConstNames.size() > 0) { + ASTRewrite astRewrite= ASTRewrite.create(ast); + ListRewrite listRewrite; + if (parent instanceof SwitchStatement) { + listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + } else { + listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); + } + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description; + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_CASE_STATEMENTS); + + for (String enumConstName : enumConstNames) { + SwitchCase newSwitchCase= ast.newSwitchCase(); + Name newName= ast.newName(enumConstName); + if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(ast)) { + newSwitchCase.expressions().add(newName); + } else { + newSwitchCase.setExpression(newName); + } + listRewrite.insertAt(newSwitchCase, defaultIndex, null); + defaultIndex++; + if (!hasDefault) { + if (ASTHelper.isSwitchExpressionNodeSupportedInAST(ast)) { + if (statements.size() > 0) { + Statement firstStatement= statements.get(0); + SwitchCase switchCase= (SwitchCase) firstStatement; + boolean isArrow= switchCase.isSwitchLabeledRule(); + newSwitchCase.setSwitchLabeledRule(isArrow); + if (isArrow || parent instanceof SwitchExpression) { + ThrowStatement newThrowStatement= getThrowForUnsupportedCase(expression, ast, astRewrite); + listRewrite.insertLast(newThrowStatement, null); + proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, enumConstName); + } else { + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + } else { + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + } else { + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + + defaultIndex++; + } + } + if (!hasDefault) { + SwitchCase newSwitchCase= ast.newSwitchCase(); + listRewrite.insertAt(newSwitchCase, defaultIndex, null); + defaultIndex++; + + if (ASTHelper.isSwitchExpressionNodeSupportedInAST(ast)) { + if (statements.size() > 0) { + Statement firstStatement= statements.get(0); + SwitchCase switchCase= (SwitchCase) firstStatement; + boolean isArrow= switchCase.isSwitchLabeledRule(); + newSwitchCase.setSwitchLabeledRule(isArrow); + if (isArrow || parent instanceof SwitchExpression) { + ThrowStatement newThrowStatement= getThrowForUnexpectedDefault(expression, ast, astRewrite); + listRewrite.insertLast(newThrowStatement, null); + proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, "defaultCase"); //$NON-NLS-1$ + } else { + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + } else { + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + } else { + newSwitchCase.setExpression(null); + listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); + } + } + proposals.add(linkedCorrectionProposalToT(proposal, ADD_MISSING_CASE)); + } + if (!hasDefault) { + createMissingDefaultProposal(context, parent, proposals); + } + } + + private ThrowStatement getThrowForUnsupportedCase(Expression switchExpr, AST ast, ASTRewrite astRewrite) { + ThrowStatement newThrowStatement= ast.newThrowStatement(); + ClassInstanceCreation newCic= ast.newClassInstanceCreation(); + newCic.setType(ast.newSimpleType(ast.newSimpleName("UnsupportedOperationException"))); //$NON-NLS-1$ + InfixExpression newInfixExpr= ast.newInfixExpression(); + StringLiteral newStringLiteral= ast.newStringLiteral(); + newStringLiteral.setLiteralValue("Unimplemented case: "); //$NON-NLS-1$ + newInfixExpr.setLeftOperand(newStringLiteral); + newInfixExpr.setOperator(InfixExpression.Operator.PLUS); + newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpr)); + newCic.arguments().add(newInfixExpr); + newThrowStatement.setExpression(newCic); + return newThrowStatement; + } + + public void removeDefaultCaseProposalBase(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + + if (selectedNode instanceof SwitchCase && ((SwitchCase) selectedNode).isDefault()) { + ASTNode parent= selectedNode.getParent(); + List statements; + if (parent instanceof SwitchStatement) { + statements= ((SwitchStatement) parent).statements(); + } else if (parent instanceof SwitchExpression) { + statements= ((SwitchExpression) parent).statements(); + } else { + return; + } + + ASTRewrite astRewrite= ASTRewrite.create(parent.getAST()); + ListRewrite listRewrite; + if (parent instanceof SwitchStatement) { + listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + } else { + listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); + } + + int indexOfDefaultCase= statements.indexOf(selectedNode); + if (indexOfDefaultCase != -1) { + listRewrite.remove(statements.get(indexOfDefaultCase), null); + int indexOfDefaultStatement= indexOfDefaultCase + 1; + if (indexOfDefaultStatement < statements.size()) { + listRewrite.remove(statements.get(indexOfDefaultStatement), null); + } + } else { + return; + } + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_default_case_description; + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE); + proposals.add(astRewriteCorrectionProposalToT(proposal, REMOVE_DEFAULT)); + } + } + + public void getPermittedTypesProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Expression expression) { + StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); + ASTNode parent= selectedNode.getParent(); + List statements; + + if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) { + statements= ((SwitchStatement) parent).statements(); + } else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) { + statements= ((SwitchExpression) parent).statements(); + } else { + return; + } + + if (statements.size() != 0) { + return; + } + ITypeBinding typeBinding= expression.resolveTypeBinding(); + if (typeBinding == null) { + return; + } + IType type= (IType) typeBinding.getJavaElement(); + try { + if (type == null || type.getPermittedSubtypeNames().length == 0) { + return; + } + } catch (JavaModelException e) { + return; + } + + createPermittedTypeCasesProposal(context, parent, proposals); + } + } + + + private void createPermittedTypeCasesProposal(IInvocationContext context, ASTNode parent, Collection proposals) { + class TypeExtendsSearchRequestor extends SearchRequestor { + public List results= new ArrayList<>(); + + public List getResults() { + return results; + } + + @Override + public void acceptSearchMatch(SearchMatch match) throws CoreException { + if (match.getAccuracy() == SearchMatch.A_ACCURATE) { + results.add(match); + } + } + } + + Expression expression; + if (parent instanceof SwitchStatement) { + SwitchStatement switchStatement= (SwitchStatement) parent; + expression= switchStatement.getExpression(); + } else if (parent instanceof SwitchExpression) { + SwitchExpression switchExpression= (SwitchExpression) parent; + expression= switchExpression.getExpression(); + } else { + return; + } + AST ast= parent.getAST(); + ASTRewrite astRewrite= ASTRewrite.create(ast); + ListRewrite listRewrite; + String caseCode= "{}"; //$NON-NLS-1$ + if (parent instanceof SwitchStatement) { + listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + } else { + SwitchExpression switchExpression= (SwitchExpression)parent; + ASTNode swExpParent= switchExpression.getParent(); + ITypeBinding swExpTypeBinding= null; + if (swExpParent instanceof VariableDeclarationFragment fragment) { + IVariableBinding varBinding= fragment.resolveBinding(); + if (varBinding != null) { + swExpTypeBinding= varBinding.getType(); + } + } else if (swExpParent instanceof ReturnStatement retStatement) { + MethodDeclaration methodDecl= ASTNodes.getFirstAncestorOrNull(retStatement, MethodDeclaration.class); + if (methodDecl != null) { + Type t= methodDecl.getReturnType2(); + if (t != null) { + swExpTypeBinding= t.resolveBinding(); + } + } + } + if (swExpTypeBinding == null) { + return; + } + if (swExpTypeBinding.isPrimitive()) { + if (swExpTypeBinding.getName().equals("boolean")) { //$NON-NLS-1$ + caseCode= "false;"; //$NON-NLS-1$ + } else { + caseCode= "0;"; //$NON-NLS-1$ + } + } else { + caseCode= "null"; //$NON-NLS-1$ + } + listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); + } + ITypeBinding binding= expression.resolveTypeBinding(); + IType sealedType= (IType)binding.getJavaElement(); + Set excludedNames= new HashSet<>(); + CompilationUnit cu= context.getASTRoot(); + PackageDeclaration pkg= cu.getPackage(); + String pkgName= ""; //$NON-NLS-1$ + if (pkg != null) { + pkgName= pkg.getName().getFullyQualifiedName(); + } + try { + excludedNames.addAll(List.of(computeReservedIdentifiers(parent, cu))); + } catch (JavaModelException e) { + return; + } + String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_permitted_types_description; + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_PERMITTED_TYPES); + ImportRewrite importRewriter= proposal.createImportRewrite(cu); + + String[] permittedTypeNames; + try { + permittedTypeNames= sealedType.getPermittedSubtypeNames(); + for (String permittedTypeName : permittedTypeNames) { + boolean needImport= false; + String importName= ""; //$NON-NLS-1$ + String[][] resolvedName= sealedType.resolveType(permittedTypeName); + for (int i= 0; i < resolvedName.length; ++i) { + String[] inner= resolvedName[i]; + if (!inner[0].isEmpty()) { + importName= inner[0] + "." + inner[1]; //$NON-NLS-1$ + if (!inner[0].equals(pkgName)) { + needImport= true; + } + } else { + importName= inner[1]; + } + if (permittedTypeName.startsWith(sealedType.getTypeQualifiedName('.'))) { + needImport= false; + String name= permittedTypeName.substring(sealedType.getTypeQualifiedName('.').length() + 1); + IType innerType= sealedType.getType(name); + if (innerType.exists()) { + permittedTypeName= sealedType.getElementName() + "." + name; //$NON-NLS-1$ + if (innerType.isRecord()) { + permittedTypeName += "("; //$NON-NLS-1$ + String separator= ""; //$NON-NLS-1$ + for (IField field : innerType.getRecordComponents()) { + permittedTypeName += separator + Signature.toString(field.getTypeSignature()); + separator= ", "; //$NON-NLS-1$ + permittedTypeName += " " + field.getElementName(); //$NON-NLS-1$ + } + permittedTypeName += ")"; //$NON-NLS-1$ + } else { + String patternName= permittedTypeName.substring(0, 1).toLowerCase(); + String nameToUse= patternName; + int count= 1; + while (excludedNames.contains(nameToUse)) { + nameToUse= patternName + (++count); + } + excludedNames.add(nameToUse); + permittedTypeName += " " + nameToUse; //$NON-NLS-1$ + } + } + } else { + SearchPattern pattern = SearchPattern.createPattern(importName, IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE); + if (pattern == null) { + return; + } + TypeExtendsSearchRequestor requestor= new TypeExtendsSearchRequestor(); + try { + search(pattern, SearchEngine.createJavaSearchScope(new IJavaElement[] {sealedType.getJavaProject()}), requestor); + } catch (CoreException e) { + return; + } + List results= requestor.getResults(); + for (SearchMatch result : results) { + Object obj= result.getElement(); + if (obj instanceof IType resultType) { + try { + if (resultType.exists() && resultType.isRecord()) { + permittedTypeName= inner[1]; + permittedTypeName += "("; //$NON-NLS-1$ + String separator= ""; //$NON-NLS-1$ + for (IField field : resultType.getRecordComponents()) { + permittedTypeName += separator + Signature.toString(field.getTypeSignature()); + separator= ", "; //$NON-NLS-1$ + permittedTypeName += " " + field.getElementName(); //$NON-NLS-1$ + } + permittedTypeName += ")"; //$NON-NLS-1$ + } else { + permittedTypeName= inner[1]; + String patternName= permittedTypeName.substring(0, 1).toLowerCase(); + String nameToUse= patternName; + int count= 1; + while (excludedNames.contains(nameToUse)) { + nameToUse= patternName + (++count); + } + excludedNames.add(nameToUse); + permittedTypeName += " " + nameToUse; //$NON-NLS-1$ + } + } catch (JavaModelException e) { + // do nothing + } + } + } + + } + } + String caseName= "case " + permittedTypeName + " -> " + caseCode; //$NON-NLS-1$ //$NON-NLS-2$ + SwitchCase newSwitchCase= (SwitchCase) astRewrite.createStringPlaceholder(caseName, ASTNode.SWITCH_CASE); + listRewrite.insertLast(newSwitchCase, null); + if (needImport) { + importRewriter.addImport(importName); + } + } + SwitchCase newNullCase= (SwitchCase) astRewrite.createStringPlaceholder("case null -> " + caseCode, ASTNode.SWITCH_CASE); //$NON-NLS-1$ + listRewrite.insertLast(newNullCase, null); + SwitchCase defaultCase= (SwitchCase) astRewrite.createStringPlaceholder("default -> " + caseCode, ASTNode.SWITCH_CASE); //$NON-NLS-1$ + listRewrite.insertLast(defaultCase, null); + proposals.add(linkedCorrectionProposalToT(proposal, ADD_PERMITTED_TYPES)); + } catch (JavaModelException e) { + // should never occur + } + } + + private void search(SearchPattern searchPattern, IJavaSearchScope scope, SearchRequestor requestor) throws CoreException { + new SearchEngine().search( + searchPattern, + new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()}, + scope, + requestor, + null); + } + + /** + * Returns the reserved identifiers in the method to move. + * + * @param node - node to find previous variable names to exclude + * @return the reserved identifiers + * @throws JavaModelException + * if the method declaration could not be found + */ + private String[] computeReservedIdentifiers(ASTNode node, CompilationUnit cu) throws JavaModelException { + final List names= new ArrayList<>(); + final MethodDeclaration declaration= ASTNodes.getFirstAncestorOrNull(node, MethodDeclaration.class); + if (declaration != null) { + final List parameters= declaration.parameters(); + VariableDeclaration variable= null; + for (SingleVariableDeclaration parameter : parameters) { + variable= parameter; + names.add(variable.getName().getIdentifier()); + } + final Block body= declaration.getBody(); + if (body != null) { + for (IBinding binding : new ScopeAnalyzer(cu).getDeclarationsAfter(body.getStartPosition(), ScopeAnalyzer.VARIABLES)) + names.add(binding.getName()); + } + } + final String[] result= new String[names.size()]; + names.toArray(result); + return result; + } + + public void getMissingDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); + if (selectedNode instanceof Expression) { + StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); + ASTNode parent= selectedNode.getParent(); + List statements; + + if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) { + statements= ((SwitchStatement) parent).statements(); + } else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) { + statements= ((SwitchExpression) parent).statements(); + } else { + return; + } + + for (Statement statement : statements) { + if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { + return; + } + } + createMissingDefaultProposal(context, parent, proposals); + } + } + + private void createMissingDefaultProposal(IInvocationContext context, ASTNode parent, Collection proposals) { + List statements; + Expression expression; + if (parent instanceof SwitchStatement) { + SwitchStatement switchStatement= (SwitchStatement) parent; + statements= switchStatement.statements(); + expression= switchStatement.getExpression(); + } else if (parent instanceof SwitchExpression) { + SwitchExpression switchExpression= (SwitchExpression) parent; + statements= switchExpression.statements(); + expression= switchExpression.getExpression(); + } else { + return; + } + AST ast= parent.getAST(); + ASTRewrite astRewrite= ASTRewrite.create(ast); + ListRewrite listRewrite; + if (parent instanceof SwitchStatement) { + listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + } else { + listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); + } + String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_description; + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE); + + SwitchCase newSwitchCase= ast.newSwitchCase(); + listRewrite.insertLast(newSwitchCase, null); + boolean offerSwitchLabel= false; + + if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(ast)) { + boolean isArrow= false; + if (statements.size() > 0) { + Statement firstStatement= statements.get(0); + SwitchCase switchCase= (SwitchCase) firstStatement; + isArrow= switchCase.isSwitchLabeledRule(); + newSwitchCase.setSwitchLabeledRule(isArrow); + } + if (isArrow || parent instanceof SwitchExpression) { + ThrowStatement newThrowStatement= getThrowForUnexpectedDefault(expression, ast, astRewrite); + listRewrite.insertLast(newThrowStatement, null); + proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, null); + } else { + listRewrite.insertLast(ast.newBreakStatement(), null); + offerSwitchLabel= statements.size() == 0; + } + } else { + listRewrite.insertLast(ast.newBreakStatement(), null); + } + + proposals.add(linkedCorrectionProposalToT(proposal, CREATE_DEFAULT)); + + if (offerSwitchLabel) { + ASTRewrite astRewrite2= ASTRewrite.create(ast); + ListRewrite listRewrite2= astRewrite2.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); + String label2= CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_label_description; + LinkedCorrectionProposalCore proposal2= new LinkedCorrectionProposalCore(label2, context.getCompilationUnit(), astRewrite2, IProposalRelevance.ADD_MISSING_DEFAULT_CASE); + SwitchCase newSwitchCase2= ast.newSwitchCase(); + listRewrite2.insertLast(newSwitchCase2, null); + newSwitchCase2.setSwitchLabeledRule(true); + listRewrite2.insertLast(astRewrite2.createStringPlaceholder("{}", ASTNode.BLOCK), null); //$NON-NLS-1$ + proposals.add(linkedCorrectionProposalToT(proposal2, CREATE_DEFAULT)); + } + } + + private ThrowStatement getThrowForUnexpectedDefault(Expression switchExpression, AST ast, ASTRewrite astRewrite) { + ThrowStatement newThrowStatement= ast.newThrowStatement(); + ClassInstanceCreation newCic= ast.newClassInstanceCreation(); + newCic.setType(ast.newSimpleType(ast.newSimpleName("IllegalArgumentException"))); //$NON-NLS-1$ + InfixExpression newInfixExpr= ast.newInfixExpression(); + StringLiteral newStringLiteral= ast.newStringLiteral(); + newStringLiteral.setLiteralValue("Unexpected value: "); //$NON-NLS-1$ + newInfixExpr.setLeftOperand(newStringLiteral); + newInfixExpr.setOperator(InfixExpression.Operator.PLUS); + newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpression)); + newCic.arguments().add(newInfixExpr); + newThrowStatement.setExpression(newCic); + return newThrowStatement; + } + + public void getOverrideDefaultMethodProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + CompilationUnit astRoot= context.getASTRoot(); + + ASTNode selectedNode= problem.getCoveringNode(astRoot); + if (selectedNode == null) { + return; + } + + StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); + if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) { + return; + } + + ASTNode typeNode= selectedNode.getParent(); + if (typeNode == null) { + return; + } + + ITypeBinding typeBinding= ((AbstractTypeDeclaration) typeNode).resolveBinding(); + if (typeBinding == null) { + return; + } + + if (problem.getProblemId() == IProblem.DuplicateInheritedDefaultMethods) { + String[] args= problem.getProblemArguments(); + if (args.length < 5) { + return; + } + + String methodName= args[0]; + if (methodName == null) { + return; + } + + String[] parameters1= {}; + if (args[1] != null && args[1].length() != 0) { + parameters1= args[1].split(", "); //$NON-NLS-1$ + } + String[] parameters2= {}; + if (args[2] != null && args[2].length() != 0) { + parameters2= args[2].split(", "); //$NON-NLS-1$ + } + + addOverrideProposal(typeNode, typeBinding, methodName, parameters1, args[3], context, proposals); + addOverrideProposal(typeNode, typeBinding, methodName, parameters2, args[4], context, proposals); + + } else if (problem.getProblemId() == IProblem.InheritedDefaultMethodConflictsWithOtherInherited) { + String[] args= problem.getProblemArguments(); + if (args.length < 3) { + return; + } + + String arg0= args[0]; + if (arg0 == null) { + return; + } + int indexOfLParen= arg0.indexOf('('); + if (indexOfLParen == -1) { + return; + } + int indexOfRParen= arg0.indexOf(')'); + if (indexOfRParen == -1) { + return; + } + + String methodName= arg0.substring(0, indexOfLParen); + + String paramString= arg0.substring(indexOfLParen + 1, indexOfRParen); + String[] parameters= {}; + if (paramString != null && paramString.length() != 0) { + parameters= paramString.split(", "); //$NON-NLS-1$ + } + + addOverrideProposal(typeNode, typeBinding, methodName, parameters, args[1], context, proposals); + addOverrideProposal(typeNode, typeBinding, methodName, parameters, args[2], context, proposals); + } + } + + private void addOverrideProposal(ASTNode typeNode, ITypeBinding typeBinding, String methodName, String[] parameters, String superType, + IInvocationContext context, Collection proposals) { + ITypeBinding superTypeBinding= null; + if (superType != null) { + int i= superType.indexOf('<'); + if (i > 0) { + superType= superType.substring(0, i); + } + superTypeBinding= Bindings.findTypeInHierarchy(typeBinding, superType); + } + if (superTypeBinding == null) { + return; + } + + IMethodBinding methodToOverride= Bindings.findMethodWithDeclaredParameterTypesInType(superTypeBinding, methodName, parameters); + if (methodToOverride == null) { + return; + } + + String label; + int modifiers= methodToOverride.getModifiers(); + if (Modifier.isDefault(modifiers)) { + label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_override_default_method_description, superTypeBinding.getName()); + } else if (Modifier.isAbstract(modifiers)) { + label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_implement_method_description, superTypeBinding.getName()); + } else { + label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_override_method_description, superTypeBinding.getName()); + } +// Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); + + CompilationUnit astRoot= context.getASTRoot(); + ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); + ICompilationUnit cu= context.getCompilationUnit(); + LinkedCorrectionProposalCore proposal= new LinkedCorrectionProposalCore(label, cu, rewrite, IProposalRelevance.OVERRIDE_DEFAULT_METHOD); + + ImportRewrite importRewrite= proposal.createImportRewrite(astRoot); + ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(astRoot, typeNode.getStartPosition(), importRewrite); + CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu); + try { + MethodDeclaration stub= StubUtility2Core.createImplementationStub(cu, rewrite, importRewrite, importRewriteContext, methodToOverride, typeBinding, settings, + typeBinding.isInterface(), new NodeFinder(astRoot, typeNode.getStartPosition(), 0).getCoveringNode()); + BodyDeclarationRewrite.create(rewrite, typeNode).insert(stub, null); + + proposal.setEndPosition(rewrite.track(stub)); + } catch (CoreException e) { + JavaManipulationPlugin.log(e); + } + + proposals.add(linkedCorrectionProposalToT(proposal, ADD_OVERRIDE)); + } + + public void getServiceProviderConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode node= problem.getCoveredNode(context.getASTRoot()); + if (!(node instanceof Name) && !(node.getParent() instanceof ProvidesDirective)) { + return; + } + + Name name= (Name) node; + ITypeBinding targetBinding= name.resolveTypeBinding(); + + if (targetBinding != null && + !targetBinding.isInterface() + && !Modifier.isAbstract(targetBinding.getModifiers())) { + ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); + IJavaProject proj= targetCU.getJavaProject(); + + // Get the AST Root (CompilationUnit) for target class + ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); + parser.setKind(ASTParser.K_COMPILATION_UNIT); + parser.setSource(targetCU); + parser.setProject(proj); + parser.setUnitName(targetCU.getPath().toString()); + parser.setResolveBindings(true); + ASTNode targetRoot= parser.createAST(null); + + if (!(targetRoot instanceof CompilationUnit)) { + return; + } + + IType targetType= proj.findType(targetBinding.getQualifiedName()); + + // Locate the no-arg constructor binding for the type + List result= Arrays.asList(targetBinding.getDeclaredMethods()).stream() + .filter(m -> m.isConstructor() && m.getParameterTypes().length == 0) + .collect(Collectors.toList()); + + // no-arg constructor exists, need to change visibility + if (!result.isEmpty()) { + IMethodBinding targetMethodBinding= result.get(0); + IMethod targetMethod= null; + for (IMethod m : targetType.getMethods()) { + if (m.isConstructor() && m.getParameters().length == 0) { + targetMethod= m; + break; + } + } + + String label= CorrectionMessages.LocalCorrectionsSubProcessor_changeconstructor_public_description; + int include= Modifier.PUBLIC; + int exclude= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC; + + // Locate the constructor declaration node in the target AST Node + MethodDeclaration targetMethodDecl= ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod, (CompilationUnit) targetRoot); + + ModifierChangeCorrectionProposalCore proposal= new ModifierChangeCorrectionProposalCore(label, targetCU, targetMethodBinding, targetMethodDecl.getName(), + include, exclude, IProposalRelevance.CHANGE_VISIBILITY_TO_NON_PRIVATE); + proposals.add(modifierChangeCorrectionProposalToT(proposal, CHANGE_MODIFIER)); + } else { + // no-arg constructor does not exist, need to create it + String[] args= new String[] { ASTResolving + .getMethodSignature(ASTResolving.getTypeSignature(targetBinding), new ITypeBinding[0], false) }; + String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconstructor_description, args); + NewMethodCorrectionProposalCore proposal= new NewMethodCorrectionProposalCore(label, targetCU, targetRoot, new ArrayList<>(), targetBinding, IProposalRelevance.CREATE_CONSTRUCTOR); + proposals.add(newMethodCorrectionProposalToT(proposal, CREATE_CONSTRUCTOR)); + } + } + } + + protected LocalCorrectionsBaseSubProcessor() { + } + + protected abstract T refactoringCorrectionProposalToT(RefactoringCorrectionProposalCore core, int uid); + protected abstract T linkedCorrectionProposalToT(LinkedCorrectionProposalCore core, int uid); + protected abstract T changeMethodSignatureProposalToT(ChangeMethodSignatureProposalCore core, int uid); + protected abstract T fixCorrectionProposalToT(FixCorrectionProposalCore core, int uid); + protected abstract T constructorFromSuperClassProposalToT(ConstructorFromSuperclassProposalCore core, int uid); + protected abstract T createNewObjectProposalToT(CreateNewObjectProposalCore core, int uid); + protected abstract T createObjectReferenceProposalToT(CreateObjectReferenceProposalCore core, int uid); + protected abstract T createVariableReferenceProposalToT(CreateVariableReferenceProposalCore core, int uid); + protected abstract T astRewriteCorrectionProposalToT(ASTRewriteCorrectionProposalCore core, int uid); + protected abstract T replaceCorrectionProposalToT(ReplaceCorrectionProposalCore core, int uid); + protected abstract T cuCorrectionProposalToT(CUCorrectionProposalCore core, int uid); + protected abstract T newVariableCorrectionProposalToT(NewVariableCorrectionProposalCore core, int uid); + protected abstract T missingAnnotationAttributesProposalToT(MissingAnnotationAttributesProposalCore core, int uid); + protected abstract T newMethodCorrectionProposalToT(NewMethodCorrectionProposalCore core, int uid); + protected abstract T modifierChangeCorrectionProposalToT(ModifierChangeCorrectionProposalCore core, int uid); + +} diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessorUtil.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessorUtil.java index 4eadabc5f7e..44a46b1d1f9 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessorUtil.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessorUtil.java @@ -71,6 +71,7 @@ import org.eclipse.jdt.core.dom.VariableDeclarationStatement; 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.internal.core.manipulation.StubUtility; import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; @@ -710,4 +711,26 @@ public static CompilationUnit findCUForMethod(CompilationUnit compilationUnit, I return compilationUnit; } + public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) { + if (statement.getNodeType() == ASTNode.BLOCK) { + Block block= (Block) statement; + List innerStatements= block.statements(); + int nStatements= innerStatements.size(); + if (nStatements == 1) { + return rewrite.createCopyTarget(innerStatements.get(0)); + } else if (nStatements > 1) { + if (toControlStatementBody) { + return rewrite.createCopyTarget(block); + } + ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); + ASTNode first= innerStatements.get(0); + ASTNode last= innerStatements.get(nStatements - 1); + return listRewrite.createCopyTarget(first, last); + } + return null; + } else { + return rewrite.createCopyTarget(statement); + } + } + } diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsBaseSubProcessor.java index 232882f5c42..492c6264261 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsBaseSubProcessor.java @@ -301,9 +301,8 @@ public boolean addImportNotFoundProposals(IInvocationContext context, IProblemLo if (importDeclaration.isStatic() && name.isQualifiedName()) { name= ((QualifiedName) name).getQualifier(); } - int kind= JavaModelUtil.is50OrHigher(cu.getJavaProject()) ? TypeKinds.REF_TYPES : TypeKinds.CLASSES | TypeKinds.INTERFACES; unresolvedElements.collectRequiresModuleProposals(cu, name, IProposalRelevance.IMPORT_NOT_FOUND_ADD_REQUIRES_MODULE, proposals, false); - unresolvedElements.collectNewTypeProposals(cu, name, kind, IProposalRelevance.IMPORT_NOT_FOUND_NEW_TYPE, proposals); + unresolvedElements.collectNewTypeProposals(cu, name, TypeKinds.REF_TYPES, IProposalRelevance.IMPORT_NOT_FOUND_NEW_TYPE, proposals); } else { Name name= importDeclaration.getName(); unresolvedElements.collectRequiresModuleProposals(cu, name, IProposalRelevance.IMPORT_NOT_FOUND_ADD_REQUIRES_MODULE, proposals, true); diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchBaseSubProcessor.java index ac5341681e3..2f6b0654eda 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchBaseSubProcessor.java @@ -59,7 +59,6 @@ import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.text.java.IInvocationContext; @@ -177,7 +176,7 @@ public void collectTypeMismatchProposals(IInvocationContext context, IProblemLoc ITypeBinding castFixType= null; if (currBinding == null || castTypeBinding.isCastCompatible(currBinding) || nodeToCast instanceof CastExpression) { castFixType= castTypeBinding; - } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) { + } else { ITypeBinding boxUnboxedTypeBinding= boxOrUnboxPrimitives(castTypeBinding, currBinding, ast); if (boxUnboxedTypeBinding != castTypeBinding && boxUnboxedTypeBinding.isCastCompatible(currBinding)) { castFixType= boxUnboxedTypeBinding; diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsBaseSubProcessor.java index 71c658c5275..a50aa6c0ad9 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsBaseSubProcessor.java @@ -80,6 +80,8 @@ 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.InfixExpression; +import org.eclipse.jdt.core.dom.InfixExpression.Operator; import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.MemberValuePair; import org.eclipse.jdt.core.dom.MethodDeclaration; @@ -92,6 +94,7 @@ import org.eclipse.jdt.core.dom.ParenthesizedExpression; import org.eclipse.jdt.core.dom.ProvidesDirective; import org.eclipse.jdt.core.dom.QualifiedName; +import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleMemberAnnotation; @@ -211,6 +214,7 @@ protected UnresolvedElementsBaseSubProcessor() { private final String ADD_IMPORT_ID= "org.eclipse.jdt.ui.correction.addImport"; //$NON-NLS-1$ + @SuppressWarnings({ "deprecation" }) public void collectVariableProposals(IInvocationContext context, IProblemLocation problem, IVariableBinding resolvedField, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); @@ -330,10 +334,6 @@ public void collectVariableProposals(IInvocationContext context, IProblemLocatio // add type proposals if (typeKind != 0) { - if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) { - typeKind &= ~(TypeKinds.ANNOTATIONS | TypeKinds.ENUMS | TypeKinds.VARIABLES); - } - int relevance= Character.isUpperCase(ASTNodes.getSimpleNameIdentifier(node).charAt(0)) ? IProposalRelevance.VARIABLE_TYPE_PROPOSAL_1 : IProposalRelevance.VARIABLE_TYPE_PROPOSAL_2; addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals); @@ -450,44 +450,90 @@ private void addNewFieldForType(ICompilationUnit targetCU, ITypeBinding binding, String name= simpleName.getIdentifier(); String nameLabel= BasicElementLabels.getJavaElementName(name); String label; + boolean createEnumProposal= false; if (senderDeclBinding.isEnum() && !isWriteAccess) { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createenum_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) }); - NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.ENUM_CONST, simpleName, senderDeclBinding, 10, false); - T p1= newVariableCorrectionProposalToT(core, NewFieldForTypeProposal1); - if (p1 != null) - proposals.add(p1); - } else { - if (!mustBeConst) { - int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_FIELD_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_FIELD; - int uid; - if (binding == null) { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, nameLabel); - uid= NewFieldForTypeProposal2; - } else { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } ); - uid= NewFieldForTypeProposal3; + createEnumProposal= true; + if (simpleName.getParent() instanceof ReturnStatement retStmt) { + createEnumProposal= false; + MethodDeclaration methodDecl= ASTNodes.getFirstAncestorOrNull(retStmt, MethodDeclaration.class); + if (methodDecl != null) { + IMethodBinding methodBinding= methodDecl.resolveBinding(); + ITypeBinding retTypeBinding= methodBinding.getReturnType(); + if (senderDeclBinding.isEqualTo(retTypeBinding)) { + createEnumProposal= true; + } } - NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.FIELD, simpleName, senderDeclBinding, fieldRelevance, false); - T prop= newVariableCorrectionProposalToT(core, uid); - if (prop != null) - proposals.add(prop); + } else if (simpleName.getParent() instanceof InfixExpression infix) { + createEnumProposal= false; + if (infix.getOperator() == Operator.EQUALS || infix.getOperator() == Operator.NOT_EQUALS) { + Expression otherExp= null; + if (infix.getLeftOperand() == simpleName) { + otherExp= infix.getRightOperand(); + } else { + otherExp= infix.getLeftOperand(); + } + if (otherExp instanceof SimpleName otherIdent) { + IBinding otherBinding= otherIdent.resolveBinding(); + if (otherBinding instanceof IVariableBinding varBinding) { + if (!varBinding.isEnumConstant() && senderDeclBinding.isEqualTo(varBinding.getType())) { + createEnumProposal= true; + } + } + } + } + } else if (simpleName.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) { + createEnumProposal= false; + VariableDeclarationFragment fragment= (VariableDeclarationFragment)simpleName.getParent(); + IVariableBinding fragBinding= fragment.resolveBinding(); + if (fragBinding != null && senderDeclBinding.isEqualTo(fragBinding.getType())) { + createEnumProposal= true; + } + } else if (simpleName.getLocationInParent() == Assignment.RIGHT_HAND_SIDE_PROPERTY) { + createEnumProposal= false; + Assignment assignment= (Assignment) simpleName.getParent(); + Expression leftOperand= assignment.getLeftHandSide(); + if (senderDeclBinding.isEqualTo(leftOperand.resolveTypeBinding())) { + createEnumProposal= true; + } + } + if (createEnumProposal) { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createenum_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) }); + NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.ENUM_CONST, simpleName, senderDeclBinding, 10, false); + T p1= newVariableCorrectionProposalToT(core, NewFieldForTypeProposal1); + if (p1 != null) + proposals.add(p1); } + } + if (!createEnumProposal && !mustBeConst) { + int fieldRelevance= StubUtility.hasFieldName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_FIELD_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_FIELD; + int uid; + if (binding == null) { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_description, nameLabel); + uid= NewFieldForTypeProposal2; + } else { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createfield_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } ); + uid= NewFieldForTypeProposal3; + } + NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.FIELD, simpleName, senderDeclBinding, fieldRelevance, false); + T prop= newVariableCorrectionProposalToT(core, uid); + if (prop != null) + proposals.add(prop); + } - if (!isWriteAccess && !senderDeclBinding.isAnonymous()) { - int uid; - if (binding == null) { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, nameLabel); - uid= NewFieldForTypeProposal4; - } else { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } ); - uid= NewFieldForTypeProposal5; - } - int constRelevance= StubUtility.hasConstantName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_CONSTANT_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_CONSTANT; - NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.CONST_FIELD, simpleName, senderDeclBinding, constRelevance, false); - T prop= newVariableCorrectionProposalToT(core, uid); - if (prop != null) - proposals.add(prop); + if (!createEnumProposal && !isWriteAccess && !senderDeclBinding.isAnonymous()) { + int uid; + if (binding == null) { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_description, nameLabel); + uid= NewFieldForTypeProposal4; + } else { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconst_other_description, new Object[] { nameLabel, ASTResolving.getTypeSignature(senderDeclBinding) } ); + uid= NewFieldForTypeProposal5; } + int constRelevance= StubUtility.hasConstantName(targetCU.getJavaProject(), name) ? IProposalRelevance.CREATE_CONSTANT_PREFIX_OR_SUFFIX_MATCH : IProposalRelevance.CREATE_CONSTANT; + NewVariableCorrectionProposalCore core= new NewVariableCorrectionProposalCore(label, targetCU, NewVariableCorrectionProposalCore.CONST_FIELD, simpleName, senderDeclBinding, constRelevance, false); + T prop= newVariableCorrectionProposalToT(core, uid); + if (prop != null) + proposals.add(prop); } } @@ -656,12 +702,6 @@ private boolean hasFieldWithName(ITypeBinding typeBinding, String name) { return false; } - private int evauateTypeKind(ASTNode node, IJavaProject project) { - int kind= ASTResolving.getPossibleTypeKinds(node, JavaModelUtil.is50OrHigher(project)); - return kind; - } - - public void collectTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); @@ -675,7 +715,7 @@ public void collectTypeProposals(IInvocationContext context, IProblemLocation pr } IJavaProject javaProject= cu.getJavaProject(); - int kind= evauateTypeKind(selectedNode, javaProject); + int kind= ASTResolving.getPossibleTypeKinds(selectedNode); if (kind == TypeKinds.REF_TYPES) { SimpleName s= addEnhancedForWithoutTypeProposals(cu, selectedNode, proposals); @@ -780,7 +820,7 @@ public void collectTypeProposals(IInvocationContext context, IProblemLocation pr } if (selectedNode != node) { - kind= evauateTypeKind(node, javaProject); + kind= ASTResolving.getPossibleTypeKinds(node); } if ((kind & (TypeKinds.CLASSES | TypeKinds.INTERFACES)) != 0) { kind &= ~TypeKinds.ANNOTATIONS; // only propose annotations when there are no other suggestions @@ -1470,46 +1510,44 @@ public void collectMethodProposals(IInvocationContext context, IProblemLocation // 1300 private void addStaticImportFavoriteProposals(IInvocationContext context, SimpleName node, boolean isMethod, Collection proposals) throws JavaModelException { IJavaProject project= context.getCompilationUnit().getJavaProject(); - if (JavaModelUtil.is50OrHigher(project)) { - String pref= JavaManipulation.getPreference(JavaManipulationPlugin.CODEASSIST_FAVORITE_STATIC_MEMBERS, project); - if (pref == null || pref.isBlank()) { - return; - } - String[] favourites= pref.split(";"); //$NON-NLS-1$ - if (favourites.length == 0) { - return; - } + String pref= JavaManipulation.getPreference(JavaManipulationPlugin.CODEASSIST_FAVORITE_STATIC_MEMBERS, project); + if (pref == null || pref.isBlank()) { + return; + } + String[] favourites= pref.split(";"); //$NON-NLS-1$ + if (favourites.length == 0) { + return; + } - CompilationUnit root= context.getASTRoot(); - AST ast= root.getAST(); + CompilationUnit root= context.getASTRoot(); + AST ast= root.getAST(); - String name= node.getIdentifier(); - for (String curr : JavaModelUtil.getStaticImportFavorites(context.getCompilationUnit(), name, isMethod, favourites)) { - ImportRewrite importRewrite= StubUtility.createImportRewrite(root, true); - ASTRewrite astRewrite= ASTRewrite.create(ast); + String name= node.getIdentifier(); + for (String curr : JavaModelUtil.getStaticImportFavorites(context.getCompilationUnit(), name, isMethod, favourites)) { + ImportRewrite importRewrite= StubUtility.createImportRewrite(root, true); + ASTRewrite astRewrite= ASTRewrite.create(ast); - String label; - String qualifiedTypeName= Signature.getQualifier(Signature.getTypeErasure(curr)); - String elementLabel= BasicElementLabels.getJavaElementName(JavaModelUtil.concatenateName(Signature.getSimpleName(qualifiedTypeName), name)); - - String res= importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite)); - int dot= res.lastIndexOf('.'); - if (dot != -1) { - String usedTypeName= importRewrite.addImport(qualifiedTypeName); - Name newName= ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name)); - astRewrite.replace(node, newName, null); - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_to_static_import_description, elementLabel); - } else { - label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_static_import_description, elementLabel); - } - - //Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); - ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT); - proposal.setImportRewrite(importRewrite); - T t= rewriteProposalToT(proposal, StaticImportFavoriteProposal1); - if (t != null) - proposals.add(t); + String label; + String qualifiedTypeName= Signature.getQualifier(Signature.getTypeErasure(curr)); + String elementLabel= BasicElementLabels.getJavaElementName(JavaModelUtil.concatenateName(Signature.getSimpleName(qualifiedTypeName), name)); + + String res= importRewrite.addStaticImport(qualifiedTypeName, name, isMethod, new ContextSensitiveImportRewriteContext(root, node.getStartPosition(), importRewrite)); + int dot= res.lastIndexOf('.'); + if (dot != -1) { + String usedTypeName= importRewrite.addImport(qualifiedTypeName); + Name newName= ast.newQualifiedName(ast.newName(usedTypeName), ast.newSimpleName(name)); + astRewrite.replace(node, newName, null); + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_change_to_static_import_description, elementLabel); + } else { + label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_add_static_import_description, elementLabel); } + + //Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); + ASTRewriteCorrectionProposalCore proposal= new ASTRewriteCorrectionProposalCore(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_STATIC_IMPORT); + proposal.setImportRewrite(importRewrite); + T t= rewriteProposalToT(proposal, StaticImportFavoriteProposal1); + if (t != null) + proposals.add(t); } } @@ -1992,7 +2030,7 @@ private void doEqualNumberOfParameters(IInvocationContext context, ASTNode invoc ITypeBinding castFixType= null; if (binding == null || castType.isCastCompatible(binding)) { castFixType= castType; - } else if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) { + } else { ITypeBinding boxUnboxedTypeBinding= TypeMismatchBaseSubProcessor.boxOrUnboxPrimitives(castType, binding, nodeToCast.getAST()); if (boxUnboxedTypeBinding != castType && boxUnboxedTypeBinding.isCastCompatible(binding)) { castFixType= boxUnboxedTypeBinding; diff --git a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/VarargsWarningsBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/VarargsWarningsBaseSubProcessor.java index f66b2160eef..34ffb9083be 100644 --- a/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/VarargsWarningsBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/common/org/eclipse/jdt/internal/ui/text/correction/VarargsWarningsBaseSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2024 IBM Corporation and others. + * Copyright (c) 2024, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -32,7 +32,6 @@ import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.text.java.IInvocationContext; @@ -64,9 +63,6 @@ public void createAddSafeVarargsProposals(IInvocationContext context, IProblemLo } public void createAddSafeVarargsToDeclarationProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - if (!JavaModelUtil.is1d7OrHigher(context.getCompilationUnit().getJavaProject())) - return; - ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot()); IMethodBinding methodBinding; if (coveringNode instanceof MethodInvocation) { diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/core/manipulation/dom/ASTResolving.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/core/manipulation/dom/ASTResolving.java index 02f32390e1d..ea7bad05e9d 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/core/manipulation/dom/ASTResolving.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/core/manipulation/dom/ASTResolving.java @@ -1127,15 +1127,7 @@ public static CompilationUnit createQuickFixAST(ICompilationUnit compilationUnit return (CompilationUnit) astParser.createAST(monitor); } - public static int getPossibleTypeKinds(ASTNode node, boolean is50OrHigher) { - int kinds= internalGetPossibleTypeKinds(node); - if (!is50OrHigher) { - kinds &= (TypeKinds.INTERFACES | TypeKinds.CLASSES); - } - return kinds; - } - - private static int internalGetPossibleTypeKinds(ASTNode node) { + public static int getPossibleTypeKinds(ASTNode node) { int kind= TypeKinds.ALL_TYPES; int mask= TypeKinds.ALL_TYPES | TypeKinds.VOIDTYPE; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java index f0b08ac4f25..f470cee576b 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GenerateHashCodeEqualsOperation.java @@ -598,28 +598,13 @@ private Statement[] createAddSimpleHashCode(ITypeBinding type, IHashCodeAccessPr private Statement createAddArrayHashCode(IVariableBinding binding) { MethodInvocation invoc= fAst.newMethodInvocation(); - if (JavaModelUtil.is50OrHigher(fRewrite.getCu().getJavaProject())) { - if (needsDeepMethod(binding.getType())) { - invoc.setName(fAst.newSimpleName(METHODNAME_DEEP_HASH_CODE)); - } else { - invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE)); - } - invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); - invoc.arguments().add(getThisAccessForHashCode(binding.getName())); + if (needsDeepMethod(binding.getType())) { + invoc.setName(fAst.newSimpleName(METHODNAME_DEEP_HASH_CODE)); } else { invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE)); - final IJavaElement element= fType.getJavaElement(); - if (element != null && !"".equals(element.getElementName())) //$NON-NLS-1$ - invoc.setExpression(fAst.newSimpleName(element.getElementName())); - invoc.arguments().add(getThisAccessForHashCode(binding.getName())); - ITypeBinding type= binding.getType().getElementType(); - if (!Bindings.isVoidType(type)) { - if (!type.isPrimitive() || binding.getType().getDimensions() >= 2) - type= fAst.resolveWellKnownType(JAVA_LANG_OBJECT); - if (!fCustomHashCodeTypes.contains(type)) - fCustomHashCodeTypes.add(type); - } } + invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS)); + invoc.arguments().add(getThisAccessForHashCode(binding.getName())); return prepareAssignment(invoc); } @@ -923,8 +908,7 @@ private MethodDeclaration createEqualsMethod() throws CoreException { if (type.isPrimitive() || type.isEnum()) body.statements().add(createSimpleComparison(field)); else if (type.isArray()) { - IJavaProject project= fUnit.getJavaElement().getJavaProject(); - if (needsDeepMethod(type) && JavaModelUtil.is50OrHigher(project)) { + if (needsDeepMethod(type)) { body.statements().add(createMultiArrayComparison(field.getName())); } else { body.statements().add(createArrayComparison(field.getName())); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GetterSetterUtil.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GetterSetterUtil.java index 581f562e9b4..ea3755fb3a3 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GetterSetterUtil.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/GetterSetterUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -246,10 +246,9 @@ public static String getGetterStub(IField field, String getterName, boolean addC * @param astRewrite the astRewrite to use * @param getterExpression the expression to insert for read accesses or null if such an expression does not exist * @param variableType the type of the variable that the result will be assigned to - * @param is50OrHigher true if a 5.0 or higher environment can be used * @return an expression that can be assigned to the type variableType with node being replaced by a equivalent expression using the getter */ - public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType, boolean is50OrHigher) { + public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, Expression getterExpression, ITypeBinding variableType) { InfixExpression.Operator op= null; AST ast= astRewrite.getAST(); if (isNotInBlock(node)) @@ -260,7 +259,7 @@ public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, E Expression copiedRightOp= (Expression) astRewrite.createCopyTarget(rightHandSide); if (assignment.getOperator() == Operator.ASSIGN) { ITypeBinding rightHandSideType= rightHandSide.resolveTypeBinding(); - copiedRightOp= createNarrowCastIfNessecary(copiedRightOp, rightHandSideType, ast, variableType, is50OrHigher); + copiedRightOp= createNarrowCastIfNessecary(copiedRightOp, rightHandSideType, ast, variableType); return copiedRightOp; } if (getterExpression != null) { @@ -274,7 +273,7 @@ public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, E copiedRightOp= p; } infix.setRightOperand(copiedRightOp); - return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher); + return createNarrowCastIfNessecary(infix, infixType, ast, variableType); } } else if (node.getNodeType() == ASTNode.POSTFIX_EXPRESSION) { PostfixExpression po= (PostfixExpression) node; @@ -290,7 +289,7 @@ public static Expression getAssignedValue(ASTNode node, ASTRewrite astRewrite, E op= InfixExpression.Operator.MINUS; } if (op != null && getterExpression != null) { - return createInfixInvocationFromPostPrefixExpression(op, getterExpression, ast, variableType, is50OrHigher); + return createInfixInvocationFromPostPrefixExpression(op, getterExpression, ast, variableType); } return null; } @@ -307,7 +306,7 @@ private static boolean isNotInBlock(ASTNode parent) { return isStatement || (!isBlock && !isControlStatemenBody); } - private static Expression createInfixInvocationFromPostPrefixExpression(InfixExpression.Operator operator, Expression getterExpression, AST ast, ITypeBinding variableType, boolean is50OrHigher) { + private static Expression createInfixInvocationFromPostPrefixExpression(InfixExpression.Operator operator, Expression getterExpression, AST ast, ITypeBinding variableType) { InfixExpression infix= ast.newInfixExpression(); infix.setLeftOperand(getterExpression); infix.setOperator(operator); @@ -315,7 +314,7 @@ private static Expression createInfixInvocationFromPostPrefixExpression(InfixExp number.setToken("1"); //$NON-NLS-1$ infix.setRightOperand(number); ITypeBinding infixType= infix.resolveTypeBinding(); - return createNarrowCastIfNessecary(infix, infixType, ast, variableType, is50OrHigher); + return createNarrowCastIfNessecary(infix, infixType, ast, variableType); } /** @@ -325,21 +324,18 @@ private static Expression createInfixInvocationFromPostPrefixExpression(InfixExp * @param expressionType the type of the right hand-side. Can be null * @param ast the AST * @param variableType the Type of the variable the expression will be assigned to - * @param is50OrHigher if true java 5.0 code will be assumed * @return the casted expression if necessary */ - private static Expression createNarrowCastIfNessecary(Expression expression, ITypeBinding expressionType, AST ast, ITypeBinding variableType, boolean is50OrHigher) { + private static Expression createNarrowCastIfNessecary(Expression expression, ITypeBinding expressionType, AST ast, ITypeBinding variableType) { PrimitiveType castTo= null; if (variableType.isEqualTo(expressionType)) return expression; //no cast for same type - if (is50OrHigher) { - if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) //$NON-NLS-1$ - castTo= ast.newPrimitiveType(PrimitiveType.CHAR); - if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) //$NON-NLS-1$ - castTo= ast.newPrimitiveType(PrimitiveType.BYTE); - if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) //$NON-NLS-1$ - castTo= ast.newPrimitiveType(PrimitiveType.SHORT); - } + if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) //$NON-NLS-1$ + castTo= ast.newPrimitiveType(PrimitiveType.CHAR); + if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) //$NON-NLS-1$ + castTo= ast.newPrimitiveType(PrimitiveType.BYTE); + if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) //$NON-NLS-1$ + castTo= ast.newPrimitiveType(PrimitiveType.SHORT); if (ast.resolveWellKnownType("char").isEqualTo(variableType)) //$NON-NLS-1$ castTo= ast.newPrimitiveType(PrimitiveType.CHAR); if (ast.resolveWellKnownType("byte").isEqualTo(variableType)) //$NON-NLS-1$ diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2Core.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2Core.java index ae1f1de3f64..56cc0295eca 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2Core.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility2Core.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2018, 2023 IBM Corporation and others. + * Copyright (c) 2018, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -125,12 +125,7 @@ public static MethodDeclaration createImplementationStub(ICompilationUnit unit, ITypeBinding bindingReturnType= binding.getReturnType(); bindingReturnType = StubUtility2Core.replaceWildcardsAndCaptures(bindingReturnType); - if (JavaModelUtil.is50OrHigher(javaProject)) { - StubUtility2Core.createTypeParameters(imports, context, ast, binding, decl); - - } else { - bindingReturnType= bindingReturnType.getErasure(); - } + StubUtility2Core.createTypeParameters(imports, context, ast, binding, decl); decl.setReturnType2(imports.addImport(bindingReturnType, ast, context, TypeLocation.RETURN_TYPE)); @@ -467,12 +462,7 @@ public static MethodDeclaration createImplementationStubCore(ICompilationUnit un ITypeBinding bindingReturnType= binding.getReturnType(); bindingReturnType= StubUtility2Core.replaceWildcardsAndCaptures(bindingReturnType); - if (JavaModelUtil.is50OrHigher(javaProject)) { - StubUtility2Core.createTypeParameters(imports, context, ast, binding, decl); - - } else { - bindingReturnType= bindingReturnType.getErasure(); - } + StubUtility2Core.createTypeParameters(imports, context, ast, binding, decl); decl.setReturnType2(imports.addImport(bindingReturnType, ast, context, TypeLocation.RETURN_TYPE)); @@ -597,7 +587,6 @@ public static List createParameters(IJavaProject proj } public static List createParameters(IJavaProject project, ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, String[] paramNames, MethodDeclaration decl, EnumSet nullnessDefault) { - boolean is50OrHigher= JavaModelUtil.is50OrHigher(project); List parameters= decl.parameters(); ITypeBinding[] params= binding.getParameterTypes(); if (paramNames == null || paramNames.length < params.length) { @@ -607,10 +596,7 @@ public static List createParameters(IJavaProject proj SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); ITypeBinding type= params[i]; type=replaceWildcardsAndCaptures(type); - if (!is50OrHigher) { - type= type.getErasure(); - var.setType(imports.addImport(type, ast, context, TypeLocation.PARAMETER)); - } else if (binding.isVarargs() && type.isArray() && i == params.length - 1) { + if (binding.isVarargs() && type.isArray() && i == params.length - 1) { var.setVarargs(true); /* * Varargs annotations are special. @@ -1108,13 +1094,7 @@ public static ASTNode getNodeToInsertBefore(ListRewrite listRewrite, IJavaElemen */ public static void addOverrideAnnotation(CodeGenerationSettings settings, IJavaProject project, ASTRewrite rewrite, ImportRewrite imports, MethodDeclaration methodDecl, boolean isDeclaringTypeInterface, TextEditGroup group) { - if (!JavaModelUtil.is50OrHigher(project)) { - return; - } if (isDeclaringTypeInterface) { - String version= project.getOption(JavaCore.COMPILER_COMPLIANCE, true); - if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6)) - return; // not allowed in 1.5 if (JavaCore.DISABLED.equals(project.getOption(JavaCore.COMPILER_PB_MISSING_OVERRIDE_ANNOTATION_FOR_INTERFACE_METHOD_IMPLEMENTATION, true))) return; // user doesn't want to use 1.6 style } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/AbstractToStringGenerator.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/AbstractToStringGenerator.java index 63a73751bbe..fa0f83235b1 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/AbstractToStringGenerator.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/AbstractToStringGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -254,16 +254,9 @@ protected MethodDeclaration createHelperToStringMethod(boolean array) { final String lengthParamName= createNameSuggestion("len", NamingConventions.VK_PARAMETER); //$NON-NLS-1$ final String maxLenParamName= createNameSuggestion(MAX_LEN_VARIABLE_NAME, NamingConventions.VK_PARAMETER); String paramName; - String stringBuilderName; - String stringBuilderTypeName; - if (fContext.is50orHigher()) { - stringBuilderTypeName= "java.lang.StringBuilder"; //$NON-NLS-1$ - stringBuilderName= createNameSuggestion("builder", NamingConventions.VK_LOCAL); //$NON-NLS-1$ - } else { - stringBuilderTypeName= "java.lang.StringBuffer"; //$NON-NLS-1$ - stringBuilderName= createNameSuggestion("buffer", NamingConventions.VK_LOCAL); //$NON-NLS-1$ - } + String stringBuilderTypeName= "java.lang.StringBuilder"; //$NON-NLS-1$ + String stringBuilderName= createNameSuggestion("builder", NamingConventions.VK_LOCAL); //$NON-NLS-1$ //private arrayToString() { MethodDeclaration arrayToStringMethod= fAst.newMethodDeclaration(); @@ -288,13 +281,9 @@ protected MethodDeclaration createHelperToStringMethod(boolean array) { paramName= createNameSuggestion("collection", NamingConventions.VK_PARAMETER); //$NON-NLS-1$ SingleVariableDeclaration param= fAst.newSingleVariableDeclaration(); Type collectionType= fAst.newSimpleType(addImport("java.util.Collection")); //$NON-NLS-1$ - if (fContext.is50orHigher()) { - ParameterizedType genericType= fAst.newParameterizedType(collectionType); - genericType.typeArguments().add(fAst.newWildcardType()); - param.setType(genericType); - } else { - param.setType(collectionType); - } + ParameterizedType genericType= fAst.newParameterizedType(collectionType); + genericType.typeArguments().add(fAst.newWildcardType()); + param.setType(genericType); param.setName(fAst.newSimpleName(paramName)); arrayToStringMethod.parameters().add(param); } @@ -406,13 +395,9 @@ protected MethodDeclaration createHelperToStringMethod(boolean array) { fragment.setInitializer(createMethodInvocation(paramName, "iterator", null)); //$NON-NLS-1$ VariableDeclarationExpression vExpression= fAst.newVariableDeclarationExpression(fragment); SimpleType iteratorType= fAst.newSimpleType(addImport("java.util.Iterator")); //$NON-NLS-1$ - if (fContext.is50orHigher()) { - ParameterizedType pType= fAst.newParameterizedType(iteratorType); - pType.typeArguments().add(fAst.newWildcardType()); - vExpression.setType(pType); - } else { - vExpression.setType(iteratorType); - } + ParameterizedType pType= fAst.newParameterizedType(iteratorType); + pType.typeArguments().add(fAst.newWildcardType()); + vExpression.setType(pType); forStatement.initializers().add(vExpression); @@ -501,10 +486,7 @@ protected void checkNeedForHelperMethods() { } if (fContext.isCustomArray() && memberType.isArray()) { ITypeBinding componentType= memberType.getComponentType(); - if (componentType.isPrimitive() && (!fContext.is50orHigher() || (!fContext.is60orHigher() && fContext.isLimitItems()))) { - if (!typesThatNeedArrayToStringMethod.contains(componentType)) - typesThatNeedArrayToStringMethod.add(componentType); - } else if (!componentType.isPrimitive()) + if (!componentType.isPrimitive()) isNonPrimitive= true; } } @@ -731,55 +713,22 @@ protected Expression createMemberAccessExpression(Object member, boolean ignoreA MethodInvocation asListInvocation= createMethodInvocation(addImport("java.util.Arrays"), "asList", createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ //$NON-NLS-2$ accessExpression= createSubListInvocation(asListInvocation, lengthAccess); } else { - if (fContext.is60orHigher()) { - // Arrays.toString( Arrays.copyOf ( member, Math.min (maxLen, member.length) ) - Name arraysImport= addImport("java.util.Arrays"); //$NON-NLS-1$ - MethodInvocation minInvocation= createMethodInvocation(addImport("java.lang.Math"), "min", lengthAccess); //$NON-NLS-1$ //$NON-NLS-2$ - minInvocation.arguments().add(fAst.newSimpleName(fMaxLenVariableName)); - needMaxLenVariable= true; - MethodInvocation copyOfInvocation= createMethodInvocation(arraysImport, "copyOf", createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ - copyOfInvocation.arguments().add(minInvocation); - Name arraysImportCopy= (Name)ASTNode.copySubtree(fAst, arraysImport); - accessExpression= createMethodInvocation(arraysImportCopy, METHODNAME_TO_STRING, copyOfInvocation); - } else { - // arrayToString(member, member.length, maxLen) - MethodInvocation arrayToStringInvocation= fAst.newMethodInvocation(); - if (fContext.isKeywordThis()) - arrayToStringInvocation.setExpression(fAst.newThisExpression()); - arrayToStringInvocation.setName(fAst.newSimpleName(HELPER_ARRAYTOSTRING_METHOD_NAME)); - arrayToStringInvocation.arguments().add(createMemberAccessExpression(member, true, true)); - arrayToStringInvocation.arguments().add(lengthAccess); - arrayToStringInvocation.arguments().add(fAst.newSimpleName(fMaxLenVariableName)); - needMaxLenVariable= true; - accessExpression= arrayToStringInvocation; - } + // Arrays.toString( Arrays.copyOf ( member, Math.min (maxLen, member.length) ) + Name arraysImport= addImport("java.util.Arrays"); //$NON-NLS-1$ + MethodInvocation minInvocation= createMethodInvocation(addImport("java.lang.Math"), "min", lengthAccess); //$NON-NLS-1$ //$NON-NLS-2$ + minInvocation.arguments().add(fAst.newSimpleName(fMaxLenVariableName)); + needMaxLenVariable= true; + MethodInvocation copyOfInvocation= createMethodInvocation(arraysImport, "copyOf", createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ + copyOfInvocation.arguments().add(minInvocation); + Name arraysImportCopy= (Name)ASTNode.copySubtree(fAst, arraysImport); + accessExpression= createMethodInvocation(arraysImportCopy, METHODNAME_TO_STRING, copyOfInvocation); } } } } else { if (isArray && fContext.isCustomArray()) { - if (fContext.is50orHigher()) { - // Arrays.toString(member) - return createMethodInvocation(addImport("java.util.Arrays"), METHODNAME_TO_STRING, createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ - } else { - ITypeBinding arrayComponentType= memberType.getComponentType(); - if (!arrayComponentType.isPrimitive() && typesThatNeedArrayToStringMethod.isEmpty()) { - // Arrays.asList(member) - accessExpression= createMethodInvocation(addImport("java.util.Arrays"), "asList", createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ //$NON-NLS-2$ - } else { - // arrayToString(member, member.length, maxLen) - FieldAccess lengthAccess= fAst.newFieldAccess(); - lengthAccess.setExpression(createMemberAccessExpression(member, true, true)); - lengthAccess.setName(fAst.newSimpleName("length")); //$NON-NLS-1$ - MethodInvocation arrayToStringInvocation= fAst.newMethodInvocation(); - if (fContext.isKeywordThis()) - arrayToStringInvocation.setExpression(fAst.newThisExpression()); - arrayToStringInvocation.setName(fAst.newSimpleName(HELPER_ARRAYTOSTRING_METHOD_NAME)); - arrayToStringInvocation.arguments().add(createMemberAccessExpression(member, true, true)); - arrayToStringInvocation.arguments().add(lengthAccess); - accessExpression= arrayToStringInvocation; - } - } + // Arrays.toString(member) + return createMethodInvocation(addImport("java.util.Arrays"), METHODNAME_TO_STRING, createMemberAccessExpression(member, true, true)); //$NON-NLS-1$ } } if (accessExpression != null) { diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/CustomBuilderGenerator.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/CustomBuilderGenerator.java index b2d67080a27..4e6107fad8c 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/CustomBuilderGenerator.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/CustomBuilderGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -273,19 +273,11 @@ private MethodInvocation createAppendMethodForMember(Object member) { ITypeBinding memberType= getMemberType(member); String memberTypeName= memberType.getQualifiedName(); - Expression memberAccessExpression= null; - AppendMethodInformation ami= appendMethodSpecificTypes.get(memberTypeName); if (ami == null && memberType.isPrimitive()) { memberTypeName= wrapperTypes[primitiveTypes.indexOf(memberTypeName)]; memberType= fAst.resolveWellKnownType(memberTypeName); ami= appendMethodSpecificTypes.get(memberTypeName); - if (!getContext().is50orHigher()) { - ClassInstanceCreation classInstance= fAst.newClassInstanceCreation(); - classInstance.setType(fAst.newSimpleType(addImport(memberTypeName))); - classInstance.arguments().add(createMemberAccessExpression(member, true, true)); - memberAccessExpression= classInstance; - } } while (ami == null) { ITypeBinding oldMemberType= memberType; @@ -297,9 +289,7 @@ private MethodInvocation createAppendMethodForMember(Object member) { ami= appendMethodSpecificTypes.get(memberTypeName); } - if (memberAccessExpression == null) { - memberAccessExpression= createMemberAccessExpression(member, false, getContext().isSkipNulls()); - } + Expression memberAccessExpression= createMemberAccessExpression(member, false, getContext().isSkipNulls()); MethodInvocation appendInvocation= fAst.newMethodInvocation(); appendInvocation.setName(fAst.newSimpleName(getContext().getCustomBuilderAppendMethod())); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringBuilderGenerator.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringBuilderGenerator.java index 0ac76550b58..9116b23eda2 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringBuilderGenerator.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringBuilderGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -74,12 +74,12 @@ protected void flushBuffer(Block target) { @Override protected void initialize() { super.initialize(); - fBuilderVariableName= createNameSuggestion(getContext().is50orHigher() ? "builder" : "buffer", NamingConventions.VK_LOCAL); //$NON-NLS-1$ //$NON-NLS-2$ + fBuilderVariableName= createNameSuggestion("builder", NamingConventions.VK_LOCAL); //$NON-NLS-1$ fBuffer= new StringBuffer(); VariableDeclarationFragment fragment= fAst.newVariableDeclarationFragment(); fragment.setName(fAst.newSimpleName(fBuilderVariableName)); ClassInstanceCreation classInstance= fAst.newClassInstanceCreation(); - Name typeName= addImport(getContext().is50orHigher() ? "java.lang.StringBuilder" : "java.lang.StringBuffer"); //$NON-NLS-1$ //$NON-NLS-2$ + Name typeName= addImport("java.lang.StringBuilder"); //$NON-NLS-1$ classInstance.setType(fAst.newSimpleType(typeName)); fragment.setInitializer(classInstance); VariableDeclarationStatement vStatement= fAst.newVariableDeclarationStatement(fragment); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringFormatGenerator.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringFormatGenerator.java index b6e12f11af4..3152231952c 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringFormatGenerator.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/StringFormatGenerator.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -20,11 +20,7 @@ import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.dom.ArrayCreation; -import org.eclipse.jdt.core.dom.ArrayInitializer; -import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.Expression; -import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.StringLiteral; @@ -61,25 +57,12 @@ protected void initialize() { protected void complete() throws CoreException { super.complete(); ReturnStatement rStatement= fAst.newReturnStatement(); - String formatClass; - if (getContext().is50orHigher()) - formatClass= "java.lang.String"; //$NON-NLS-1$ - else - formatClass= "java.text.MessageFormat"; //$NON-NLS-1$ + String formatClass= "java.lang.String"; //$NON-NLS-1$ MethodInvocation formatInvocation= createMethodInvocation(addImport(formatClass), "format", null); //$NON-NLS-1$ StringLiteral literal= fAst.newStringLiteral(); literal.setLiteralValue(buffer.toString()); formatInvocation.arguments().add(literal); - if (getContext().is50orHigher()) { - formatInvocation.arguments().addAll(arguments); - } else { - ArrayCreation arrayCreation= fAst.newArrayCreation(); - arrayCreation.setType(fAst.newArrayType(fAst.newSimpleType(addImport("java.lang.Object")))); //$NON-NLS-1$ - ArrayInitializer initializer= fAst.newArrayInitializer(); - arrayCreation.setInitializer(initializer); - initializer.expressions().addAll(arguments); - formatInvocation.arguments().add(arrayCreation); - } + formatInvocation.arguments().addAll(arguments); rStatement.setExpression(formatInvocation); toStringMethod.getBody().statements().add(rStatement); } @@ -99,34 +82,8 @@ protected void addElement(Object element) { } if (element instanceof Expression) { arguments.add((Expression) element); - if (getContext().is50orHigher()) { - buffer.append("%s"); //$NON-NLS-1$ - } else { - buffer.append("{" + (arguments.size() - 1) + "}"); //$NON-NLS-1$ //$NON-NLS-2$ - } - } - } - - @Override - protected Expression createMemberAccessExpression(Object member, boolean ignoreArraysCollections, boolean ignoreNulls) { - ITypeBinding type= getMemberType(member); - if (!getContext().is50orHigher() && type.isPrimitive()) { - String nonPrimitiveType= null; - String typeName= type.getName(); - if ("byte".equals(typeName))nonPrimitiveType= "java.lang.Byte"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("short".equals(typeName))nonPrimitiveType= "java.lang.Short"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("char".equals(typeName))nonPrimitiveType= "java.lang.Character"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("int".equals(typeName))nonPrimitiveType= "java.lang.Integer"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("long".equals(typeName))nonPrimitiveType= "java.lang.Long"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("float".equals(typeName))nonPrimitiveType= "java.lang.Float"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("double".equals(typeName))nonPrimitiveType= "java.lang.Double"; //$NON-NLS-1$ //$NON-NLS-2$ - if ("boolean".equals(typeName))nonPrimitiveType= "java.lang.Boolean"; //$NON-NLS-1$ //$NON-NLS-2$ - ClassInstanceCreation classInstance= fAst.newClassInstanceCreation(); - classInstance.setType(fAst.newSimpleType(addImport(nonPrimitiveType))); - classInstance.arguments().add(super.createMemberAccessExpression(member, true, true)); - return classInstance; + buffer.append("%s"); //$NON-NLS-1$ } - return super.createMemberAccessExpression(member, ignoreArraysCollections, ignoreNulls); } } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationContext.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationContext.java index 7cd2a7d7262..e268d886b7b 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationContext.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationContext.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -81,14 +81,6 @@ public ITypeBinding getTypeBinding() { return fType; } - public boolean is50orHigher() { - return fSettings.is50orHigher; - } - - public boolean is60orHigher() { - return fSettings.is60orHigher; - } - public boolean isCreateComments() { return fSettings.createComments; } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationSettingsCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationSettingsCore.java index 2585fbd8e4f..a9183263976 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationSettingsCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/codemanipulation/tostringgeneration/ToStringGenerationSettingsCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019 Mateusz Matela and others. + * Copyright (c) 2019, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -99,12 +99,6 @@ public static class CustomBuilderSettings { /** should blocks be forced in if/for/while statements? */ public boolean useBlocks; - /** can generated code use jdk 1.5 API? **/ - public boolean is50orHigher; - - /** can generated code use jdk 1.6 API? **/ - public boolean is60orHigher; - /** settings specific for custom builder code style **/ public CustomBuilderSettings customBuilderSettings; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java index 1f3c272f991..6b886e49531 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java @@ -4275,6 +4275,27 @@ public static List getLeadingComments(ASTNode node) { return comments; } + /** + * Return a list of trailing line comments for a specified node and an offset from the start + * @param node - ASTNode in a CompilationUnit + * @param offset - offset to add from start of node to start search from + * @return list of Comment nodes + */ + public static List getTrailingLineComments(ASTNode node, int offset) { + List comments= new ArrayList<>(); + CompilationUnit cu= (CompilationUnit)node.getRoot(); + List commentList= cu.getCommentList(); + int nodeLine= cu.getLineNumber(node.getStartPosition() + offset); + for (Comment commentFromList : commentList) { + if (commentFromList.getStartPosition() >= (node.getStartPosition() + offset) && + cu.getLineNumber(commentFromList.getStartPosition()) == nodeLine) { + comments.add(commentFromList); + } else if (cu.getLineNumber(nodeLine) > nodeLine) { + break; + } + } + return comments; + } /** * Return a list of trailing comments for a specified node * diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/AbstractPrimitiveRatherThanWrapperFinder.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/AbstractPrimitiveRatherThanWrapperFinder.java index 8d0b4424396..38028a2c4d3 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/AbstractPrimitiveRatherThanWrapperFinder.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/AbstractPrimitiveRatherThanWrapperFinder.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021 Fabrice TIERCELIN and others. + * Copyright (c) 2021, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -23,7 +23,6 @@ import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.ClassInstanceCreation; -import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConditionalExpression; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; @@ -47,7 +46,6 @@ import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.InterruptibleVisitor; import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; public abstract class AbstractPrimitiveRatherThanWrapperFinder extends ASTVisitor { protected List fResult; @@ -187,7 +185,7 @@ public boolean visit(final VariableDeclarationStatement visited) { varOccurrenceVisitor.getToStringMethods(), varOccurrenceVisitor.getCompareToMethods(), varOccurrenceVisitor.getPrimitiveValueMethods(), - getParsingMethodName(getWrapperFullyQualifiedName(), (CompilationUnit) visited.getRoot()))); + getParsingMethodName(getWrapperFullyQualifiedName()))); return false; } } @@ -259,7 +257,7 @@ private boolean canReturnPrimitiveInstead(final Expression expression) { if (methodInvocation != null) { return ASTNodes.usesGivenSignature(methodInvocation, getWrapperFullyQualifiedName(), "valueOf", getPrimitiveTypeName()) //$NON-NLS-1$ - || getParsingMethodName(getWrapperFullyQualifiedName(), (CompilationUnit) expression.getRoot()) != null + || getParsingMethodName(getWrapperFullyQualifiedName()) != null && ( ASTNodes.usesGivenSignature(methodInvocation, getWrapperFullyQualifiedName(), "valueOf", String.class.getCanonicalName()) //$NON-NLS-1$ || ASTNodes.usesGivenSignature(methodInvocation, getWrapperFullyQualifiedName(), "valueOf", String.class.getCanonicalName(), int.class.getSimpleName()) //$NON-NLS-1$ @@ -280,8 +278,8 @@ private boolean canReturnPrimitiveInstead(final Expression expression) { return false; } - private String getParsingMethodName(final String wrapperFullyQualifiedName, final CompilationUnit compilationUnit) { - if (Boolean.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + private String getParsingMethodName(final String wrapperFullyQualifiedName) { + if (Boolean.class.getCanonicalName().equals(wrapperFullyQualifiedName)) { return "parseBoolean"; //$NON-NLS-1$ } @@ -293,11 +291,11 @@ private String getParsingMethodName(final String wrapperFullyQualifiedName, fina return "parseLong"; //$NON-NLS-1$ } - if (Double.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is1d2OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + if (Double.class.getCanonicalName().equals(wrapperFullyQualifiedName)) { return "parseDouble"; //$NON-NLS-1$ } - if (Float.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is1d2OrHigher(compilationUnit.getJavaElement().getJavaProject())) { + if (Float.class.getCanonicalName().equals(wrapperFullyQualifiedName)) { return "parseFloat"; //$NON-NLS-1$ } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertForLoopOperation.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertForLoopOperation.java index 062d48c7837..c2cd27d425e 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertForLoopOperation.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertForLoopOperation.java @@ -66,7 +66,6 @@ import org.eclipse.jdt.internal.corext.dom.JdtASTMatcher; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; public class ConvertForLoopOperation extends ConvertLoopOperation { private static final String LENGTH_QUERY= "length"; //$NON-NLS-1$ @@ -110,9 +109,6 @@ public IStatus satisfiesPreconditions() { if (javaElement == null) return ERROR_STATUS; - if (!JavaModelUtil.is50OrHigher(javaElement.getJavaProject())) - return ERROR_STATUS; - if (!validateInitializers(statement)) return ERROR_STATUS; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java index dc2922d8eff..b714d8e7c24 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertIterableLoopOperation.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2022 IBM Corporation and others. + * Copyright (c) 2005, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -68,7 +68,6 @@ import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; import org.eclipse.jdt.internal.corext.refactoring.structure.ImportRemover; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; @@ -417,71 +416,68 @@ public void setExpression(Expression exp) { */ @Override public IStatus satisfiesPreconditions() { - IStatus resultStatus= StatusInfo.OK_STATUS; - if (JavaModelUtil.is50OrHigher(getJavaProject())) { - resultStatus= checkExpressionCondition(); - if (resultStatus.getSeverity() == IStatus.ERROR) - return resultStatus; - - List updateExpressions= getForStatement().updaters(); - if (updateExpressions.size() == 1) { - resultStatus= new StatusInfo(IStatus.WARNING, Messages.format(FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpression_Warning, BasicElementLabels.getJavaCodeString(updateExpressions.get(0).toString()))); - } else if (updateExpressions.size() > 1) { - resultStatus= new StatusInfo(IStatus.WARNING, FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning); - } + IStatus resultStatus= checkExpressionCondition(); + if (resultStatus.getSeverity() == IStatus.ERROR) + return resultStatus; - for (final Object outer : getForStatement().initializers()) { - if (outer instanceof VariableDeclarationExpression) { - VariableDeclarationExpression declaration= (VariableDeclarationExpression) outer; - List fragments= declaration.fragments(); - if (fragments.size() != 1) { - return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$ - } - VariableDeclarationFragment fragment= fragments.get(0); - IVariableBinding binding= fragment.resolveBinding(); - if (binding != null) { - ITypeBinding type= binding.getType(); - if (type != null) { - ITypeBinding iterator= getSuperType(type, Iterator.class.getCanonicalName()); - - if (iterator == null) { - iterator= getSuperType(type, Enumeration.class.getCanonicalName()); - } + List updateExpressions= getForStatement().updaters(); + if (updateExpressions.size() == 1) { + resultStatus= new StatusInfo(IStatus.WARNING, Messages.format(FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpression_Warning, BasicElementLabels.getJavaCodeString(updateExpressions.get(0).toString()))); + } else if (updateExpressions.size() > 1) { + resultStatus= new StatusInfo(IStatus.WARNING, FixMessages.ConvertIterableLoopOperation_RemoveUpdateExpressions_Warning); + } - if (iterator != null) { - fIteratorVariable= binding; - - MethodInvocation method= ASTNodes.as(fragment.getInitializer(), MethodInvocation.class); - if (method != null && method.resolveMethodBinding() != null) { - IMethodBinding methodBinding= method.resolveMethodBinding(); - ITypeBinding returnType= methodBinding.getReturnType(); - if (returnType != null) { - String qualified= returnType.getErasure().getQualifiedName(); - ITypeBinding returnElementType= getElementType(returnType); - ITypeBinding variableElementType= getElementType(fIteratorVariable.getType()); - - if (returnElementType != null - && variableElementType != null - && returnElementType.isAssignmentCompatible(variableElementType) - && ("java.util.Iterator".equals(qualified) || "java.util.Enumeration".equals(qualified))) { //$NON-NLS-1$ //$NON-NLS-2$ - Expression qualifier= method.getExpression(); - if (qualifier != null) { - ITypeBinding resolved= qualifier.resolveTypeBinding(); - if (resolved != null) { - ITypeBinding iterable= getSuperType(resolved, Iterable.class.getCanonicalName()); - if (iterable != null) { - fExpression= qualifier; - fIterable= resolved; - } + for (final Object outer : getForStatement().initializers()) { + if (outer instanceof VariableDeclarationExpression) { + VariableDeclarationExpression declaration= (VariableDeclarationExpression) outer; + List fragments= declaration.fragments(); + if (fragments.size() != 1) { + return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$ + } + VariableDeclarationFragment fragment= fragments.get(0); + IVariableBinding binding= fragment.resolveBinding(); + if (binding != null) { + ITypeBinding type= binding.getType(); + if (type != null) { + ITypeBinding iterator= getSuperType(type, Iterator.class.getCanonicalName()); + + if (iterator == null) { + iterator= getSuperType(type, Enumeration.class.getCanonicalName()); + } + + if (iterator != null) { + fIteratorVariable= binding; + + MethodInvocation method= ASTNodes.as(fragment.getInitializer(), MethodInvocation.class); + if (method != null && method.resolveMethodBinding() != null) { + IMethodBinding methodBinding= method.resolveMethodBinding(); + ITypeBinding returnType= methodBinding.getReturnType(); + if (returnType != null) { + String qualified= returnType.getErasure().getQualifiedName(); + ITypeBinding returnElementType= getElementType(returnType); + ITypeBinding variableElementType= getElementType(fIteratorVariable.getType()); + + if (returnElementType != null + && variableElementType != null + && returnElementType.isAssignmentCompatible(variableElementType) + && ("java.util.Iterator".equals(qualified) || "java.util.Enumeration".equals(qualified))) { //$NON-NLS-1$ //$NON-NLS-2$ + Expression qualifier= method.getExpression(); + if (qualifier != null) { + ITypeBinding resolved= qualifier.resolveTypeBinding(); + if (resolved != null) { + ITypeBinding iterable= getSuperType(resolved, Iterable.class.getCanonicalName()); + if (iterable != null) { + fExpression= qualifier; + fIterable= resolved; } - } else { - ITypeBinding declaring= methodBinding.getDeclaringClass(); - if (declaring != null) { - ITypeBinding superBinding= getSuperType(declaring, Iterable.class.getCanonicalName()); - if (superBinding != null) { - fIterable= superBinding; - fThis= true; - } + } + } else { + ITypeBinding declaring= methodBinding.getDeclaringClass(); + if (declaring != null) { + ITypeBinding superBinding= getSuperType(declaring, Iterable.class.getCanonicalName()); + if (superBinding != null) { + fIterable= superBinding; + fThis= true; } } } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertLoopFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertLoopFixCore.java index 568780a43b2..137b4db2c55 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertLoopFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertLoopFixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019, 2020 IBM Corporation and others. + * Copyright (c) 2019, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -28,7 +28,6 @@ import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -122,9 +121,6 @@ public void endVisit(ForStatement node) { public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean convertForLoops, boolean convertIterableForLoops, boolean makeFinal, boolean checkIfLoopVarUsed) { - if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject())) - return null; - if (!convertForLoops && !convertIterableForLoops) return null; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToMessageFormatFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToMessageFormatFixCore.java index d7c3dec10e2..91c4785fecb 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToMessageFormatFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToMessageFormatFixCore.java @@ -46,7 +46,6 @@ import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.dom.ASTNodes; -import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner; @@ -97,7 +96,6 @@ public static ConvertToMessageFormatFixCore createConvertToMessageFormatFix(Comp return null; } - boolean is50OrHigher= JavaModelUtil.is50OrHigher(compilationUnit.getTypeRoot().getJavaProject()); // collect operands List operands= new ArrayList<>(); collectInfixPlusOperands(oldInfixExpression, operands); @@ -108,12 +106,6 @@ public static ConvertToMessageFormatFixCore createConvertToMessageFormatFix(Comp // we need to loop through all to exclude any null binding scenarios. for (Expression operand : operands) { if (!(operand instanceof StringLiteral)) { - if (!is50OrHigher) { - ITypeBinding binding= operand.resolveTypeBinding(); - if (binding == null) { - return null; - } - } foundNoneLiteralOperand= true; } else { // ensure either all string literals are nls-tagged or none are @@ -218,9 +210,7 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore final List fLiterals= new ArrayList<>(); String fIndent= ""; //$NON-NLS-1$ ICompilationUnit cu= cuRewrite.getCu(); - boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject()); boolean is15OrHigher= JavaModelUtil.is15OrHigher(cu.getJavaProject()); - AST fAst= cuRewrite.getAST(); ASTRewrite rewrite= cuRewrite.getASTRewrite(); CompilationUnit root= cuRewrite.getRoot(); @@ -280,26 +270,9 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore fLiterals.add("\"{" + Integer.toString(i) + "}\""); //$NON-NLS-1$ //$NON-NLS-2$ formatString.append("{").append(i).append("}"); //$NON-NLS-1$ //$NON-NLS-2$ - String argument; - if (is50OrHigher) { - int origStart= root.getExtendedStartPosition(operand); - int origLength= root.getExtendedLength(operand); - argument= cuContents.substring(origStart, origStart + origLength); - } else { - ITypeBinding binding= operand.resolveTypeBinding(); - int origStart= root.getExtendedStartPosition(operand); - int origLength= root.getExtendedLength(operand); - argument= cuContents.substring(origStart, origStart + origLength); - - if (binding.isPrimitive()) { - ITypeBinding boxedBinding= Bindings.getBoxedTypeBinding(binding, fAst); - if (boxedBinding != binding) { - importRewrite.addImport(boxedBinding, fAst, importContext); - String cic= "new " + boxedBinding.getName() + "(" + argument + ")"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ - argument= cic; - } - } - } + int origStart= root.getExtendedStartPosition(operand); + int origLength= root.getExtendedLength(operand); + String argument= cuContents.substring(origStart, origStart + origLength); formatArguments.add(argument); i++; @@ -370,19 +343,8 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore buffer.append("\"" + formatString.toString().replaceAll("\"", "\\\"") + "\""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } - if (is50OrHigher) { - for (String formatArgument : formatArguments) { - buffer.append(", " + formatArgument); //$NON-NLS-1$ - } - } else { - buffer.append(", new Object[]{"); //$NON-NLS-1$ - if (formatArguments.size() > 0) { - buffer.append(formatArguments.get(0)); - } - for (int i1= 1; i1 < formatArguments.size(); ++i1) { - buffer.append(", " + formatArguments.get(i1)); //$NON-NLS-1$ - } - buffer.append("}"); //$NON-NLS-1$ + for (String formatArgument : formatArguments) { + buffer.append(", " + formatArgument); //$NON-NLS-1$ } buffer.append(")"); //$NON-NLS-1$ diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringBufferFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringBufferFixCore.java index 22d2335db5c..a06a042bfa6 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringBufferFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringBufferFixCore.java @@ -58,7 +58,6 @@ import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; @@ -99,14 +98,9 @@ public static ConvertToStringBufferFixCore createConvertToStringBufferFix(Compil return null; } - String bufferOrBuilderName; SimpleName existingBuffer= getEnclosingAppendBuffer(oldInfixExpression); - if (JavaModelUtil.is50OrHigher(compilationUnit.getTypeRoot().getJavaProject())) { - bufferOrBuilderName= "StringBuilder"; //$NON-NLS-1$ - } else { - bufferOrBuilderName= "StringBuffer"; //$NON-NLS-1$ - } - var mechanismName= BasicElementLabels.getJavaElementName(existingBuffer == null ? bufferOrBuilderName : existingBuffer.getIdentifier()); + String builderName= "StringBuilder"; //$NON-NLS-1$ + var mechanismName= BasicElementLabels.getJavaElementName(existingBuffer == null ? builderName : existingBuffer.getIdentifier()); var label= Messages.format(CorrectionMessages.QuickAssistProcessor_convert_to_string_buffer_description, mechanismName); return new ConvertToStringBufferFixCore(label, compilationUnit, new ConvertToStringBufferProposalOperation(oldInfixExpression)); @@ -178,14 +172,9 @@ public ConvertToStringBufferProposalOperation(InfixExpression oldInfixExpression @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore linkedModel) throws CoreException { - String bufferOrBuilderName; ICompilationUnit cu= cuRewrite.getCu(); AST ast= cuRewrite.getAST(); - if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) { - bufferOrBuilderName= "StringBuilder"; //$NON-NLS-1$ - } else { - bufferOrBuilderName= "StringBuffer"; //$NON-NLS-1$ - } + String builderName= "StringBuilder"; //$NON-NLS-1$ ASTRewrite rewrite= cuRewrite.getASTRewrite(); @@ -218,10 +207,10 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore // check if name is already in use and provide alternative List fExcludedVariableNames= Arrays.asList(ASTResolving.getUsedVariableNames(oldInfixExpression)); - SimpleType bufferType= ast.newSimpleType(ast.newName(bufferOrBuilderName)); + SimpleType bufferType= ast.newSimpleType(ast.newName(builderName)); ClassInstanceCreation newBufferExpression= ast.newClassInstanceCreation(); - String[] newBufferNames= StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, cu.getJavaProject(), bufferOrBuilderName, 0, fExcludedVariableNames, true); + String[] newBufferNames= StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, cu.getJavaProject(), builderName, 0, fExcludedVariableNames, true); bufferName= newBufferNames[0]; SimpleName bufferNameDeclaration= ast.newSimpleName(bufferName); @@ -239,7 +228,7 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore VariableDeclarationStatement bufferDeclaration= ast.newVariableDeclarationStatement(frag); - bufferDeclaration.setType(ast.newSimpleType(ast.newName(bufferOrBuilderName))); + bufferDeclaration.setType(ast.newSimpleType(ast.newName(builderName))); insertAfter= bufferDeclaration; Statement statement= ASTResolving.findParentStatement(oldInfixExpression); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringFormatFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringFormatFixCore.java index 74395b248c0..152b9d94da4 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringFormatFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ConvertToStringFormatFixCore.java @@ -94,11 +94,6 @@ public static ConvertToStringFormatFixCore createConvertToStringFormatFix(Compil return null; } - boolean is50OrHigher= JavaModelUtil.is50OrHigher(compilationUnit.getTypeRoot().getJavaProject()); - if (!is50OrHigher) { - return null; - } - // collect operands List operands= new ArrayList<>(); collectInfixPlusOperands(oldInfixExpression, operands); @@ -109,12 +104,6 @@ public static ConvertToStringFormatFixCore createConvertToStringFormatFix(Compil // we need to loop through all to exclude any null binding scenarios. for (Expression operand : operands) { if (!(operand instanceof StringLiteral)) { - if (!is50OrHigher) { - ITypeBinding binding= operand.resolveTypeBinding(); - if (binding == null) { - return null; - } - } foundNoneLiteralOperand= true; } else { // ensure either all string literals are nls-tagged or none are diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/Java50FixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/Java50FixCore.java index ef6d02eb2c9..7fbd04f6cb8 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/Java50FixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/Java50FixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -21,7 +21,6 @@ import org.eclipse.text.edits.TextEditGroup; -import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.CategorizedProblem; import org.eclipse.jdt.core.compiler.IProblem; @@ -60,7 +59,6 @@ import org.eclipse.jdt.internal.corext.refactoring.generics.InferTypeArgumentsTCModel; import org.eclipse.jdt.internal.corext.refactoring.generics.InferTypeArgumentsUpdate; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -174,10 +172,6 @@ public static boolean isMissingDeprecationProblem(int id) { } private static Java50FixCore createFix(CompilationUnit compilationUnit, IProblemLocation problem, String annotation, String label) { - ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement(); - if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) - return null; - ASTNode selectedNode= problem.getCoveringNode(compilationUnit); if (selectedNode == null) return null; @@ -208,10 +202,6 @@ public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean addDeprecatedAnnotation, boolean rawTypeReference) { - ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement(); - if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) - return null; - if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReference) return null; @@ -252,10 +242,6 @@ public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, IProble boolean addDeprecatedAnnotation, boolean rawTypeReferences) { - ICompilationUnit cu= (ICompilationUnit)compilationUnit.getJavaElement(); - if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) - return null; - if (!addOverrideAnnotation && !addDeprecatedAnnotation && !rawTypeReferences) return null; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/JoinVariableFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/JoinVariableFixCore.java index 8f107565939..4b90f19d8bd 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/JoinVariableFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/JoinVariableFixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2023 Gayan Perera and others. + * Copyright (c) 2023, 2025 Gayan Perera and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -16,13 +16,12 @@ import java.util.List; import org.eclipse.core.runtime.CoreException; -import org.eclipse.jdt.core.IJavaProject; + import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTMatcher; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.CastExpression; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConditionalExpression; import org.eclipse.jdt.core.dom.Expression; @@ -45,13 +44,14 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.TypeLocation; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; + import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder; import org.eclipse.jdt.internal.corext.refactoring.code.Invocations; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; + import org.eclipse.jdt.internal.ui.text.correction.CorrectionMessages; public final class JoinVariableFixCore extends CompilationUnitRewriteOperationsFixCore { @@ -117,7 +117,6 @@ public static JoinVariableFixCore createJoinVariableFix(CompilationUnit compilat IfStatement ifStatement= null; Expression thenExpression= null; Expression elseExpression= null; - ITypeBinding exprBinding= null; ASTNode assignParentParent= assignParent.getParent(); if (assignParentParent instanceof IfStatement @@ -145,7 +144,6 @@ public static JoinVariableFixCore createJoinVariableFix(CompilationUnit compilat IBinding bind1= ((Name) left1).resolveBinding(); IBinding bind2= ((Name) left2).resolveBinding(); if (bind1 == bind2 && bind1 instanceof IVariableBinding) { - exprBinding= ((IVariableBinding) bind1).getType(); thenExpression= assign1.getRightHandSide(); elseExpression= assign2.getRightHandSide(); } @@ -174,7 +172,7 @@ public static JoinVariableFixCore createJoinVariableFix(CompilationUnit compilat return new JoinVariableFixCore(CorrectionMessages.QuickAssistProcessor_joindeclaration_description, compilationUnit, new CompilationUnitRewriteOperation[] { - new JoinVariableProposalOperation(statement, ifStatement, assignParent, thenExpression, elseExpression, exprBinding, fragment, onFirstAccess, assignment) }); + new JoinVariableProposalOperation(statement, ifStatement, assignParent, thenExpression, elseExpression, fragment, onFirstAccess, assignment) }); } private static Statement getSingleStatement(Statement statement) { @@ -199,8 +197,6 @@ private static class JoinVariableProposalOperation extends CompilationUnitRewrit private Expression elseExpression; - private ITypeBinding exprBinding; - private VariableDeclarationFragment fragment; private boolean onFirstAccess; @@ -208,13 +204,12 @@ private static class JoinVariableProposalOperation extends CompilationUnitRewrit private Assignment assignment; public JoinVariableProposalOperation(VariableDeclarationStatement statement, IfStatement ifStatement, ExpressionStatement assignParent, Expression thenExpression, Expression elseExpression, - ITypeBinding exprBinding, VariableDeclarationFragment fragment, boolean onFirstAccess, Assignment assignment) { + VariableDeclarationFragment fragment, boolean onFirstAccess, Assignment assignment) { this.statement= statement; this.ifStatement= ifStatement; this.assignParent= assignParent; this.thenExpression= thenExpression; this.elseExpression= elseExpression; - this.exprBinding= exprBinding; this.fragment= fragment; this.onFirstAccess= onFirstAccess; this.assignment= assignment; @@ -223,9 +218,7 @@ public JoinVariableProposalOperation(VariableDeclarationStatement statement, IfS @Override public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore linkedModel) throws CoreException { final ASTRewrite rewrite= cuRewrite.getASTRewrite(); - final CompilationUnit cup= (CompilationUnit) statement.getRoot(); final AST ast= cuRewrite.getAST(); - final IJavaProject project= cup.getTypeRoot().getJavaProject(); TightSourceRangeComputer sourceRangeComputer= new TightSourceRangeComputer(); sourceRangeComputer.addTightSourceNode(ifStatement != null ? ifStatement : assignParent); @@ -239,21 +232,8 @@ public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModelCore Expression thenCopy= (Expression) rewrite.createCopyTarget(thenExpression); Expression elseCopy= (Expression) rewrite.createCopyTarget(elseExpression); - if (!JavaModelUtil.is50OrHigher(project)) { - ITypeBinding thenBinding= thenExpression.resolveTypeBinding(); - ITypeBinding elseBinding= elseExpression.resolveTypeBinding(); - if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) { - CastExpression castException= ast.newCastExpression(); - ImportRewrite importRewrite= cuRewrite.getImportRewrite(); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(cup, importRewrite); - castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext, TypeLocation.CAST)); - castException.setExpression(elseCopy); - elseCopy= castException; - } - } else if (JavaModelUtil.is1d7OrHigher(project)) { - addExplicitTypeArgumentsIfNecessary(rewrite, cuRewrite, thenExpression); - addExplicitTypeArgumentsIfNecessary(rewrite, cuRewrite, elseExpression); - } + addExplicitTypeArgumentsIfNecessary(rewrite, cuRewrite, thenExpression); + addExplicitTypeArgumentsIfNecessary(rewrite, cuRewrite, elseExpression); conditionalExpression.setThenExpression(thenCopy); conditionalExpression.setElseExpression(elseCopy); rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, conditionalExpression, null); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StandardComparisonFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StandardComparisonFixCore.java index 5dd929dc762..8fa3855abbe 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StandardComparisonFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StandardComparisonFixCore.java @@ -15,7 +15,6 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Comparator; import java.util.List; import org.eclipse.core.runtime.CoreException; @@ -36,7 +35,6 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.OrderedInfixExpression; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -62,11 +60,7 @@ public boolean visit(final InfixExpression visited) { if (literalValue != null && literalValue.compareTo(0L) != 0 && comparisonMI.getExpression() != null - && !ASTNodes.is(comparisonMI.getExpression(), ThisExpression.class) - && (ASTNodes.usesGivenSignature(comparisonMI, Comparable.class.getCanonicalName(), "compareTo", Object.class.getCanonicalName()) //$NON-NLS-1$ - || ASTNodes.usesGivenSignature(comparisonMI, Comparator.class.getCanonicalName(), "compare", Object.class.getCanonicalName(), Object.class.getCanonicalName()) //$NON-NLS-1$ - || JavaModelUtil.is1d2OrHigher(((CompilationUnit) visited.getRoot()).getJavaElement().getJavaProject()) - && ASTNodes.usesGivenSignature(comparisonMI, String.class.getCanonicalName(), "compareToIgnoreCase", String.class.getCanonicalName()))) { //$NON-NLS-1$ + && !ASTNodes.is(comparisonMI.getExpression(), ThisExpression.class)) { if (literalValue.compareTo(0L) < 0) { if (InfixExpression.Operator.EQUALS.equals(orderedCondition.getOperator())) { fResult.add(new StandardComparisonFixOperation(visited, comparisonMI, InfixExpression.Operator.LESS)); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringBufferToStringBuilderFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringBufferToStringBuilderFixCore.java index c7be55808d6..d8efead69c9 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringBufferToStringBuilderFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringBufferToStringBuilderFixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021, 2023 Red Hat Inc. and others. + * Copyright (c) 2021, 2024 Red Hat Inc. and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -65,7 +65,6 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.AbortSearchException; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -866,9 +865,6 @@ public SourceRange computeSourceRange(final ASTNode nodeWithComment) { } public static ICleanUpFix createCleanUp(final CompilationUnit compilationUnit, boolean forLocalsOnly) { - if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject())) - return null; - List operations= new ArrayList<>(); if (forLocalsOnly) { diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringConcatToTextBlockFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringConcatToTextBlockFixCore.java index 52aee735b21..d02dd10adf2 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringConcatToTextBlockFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/StringConcatToTextBlockFixCore.java @@ -67,6 +67,7 @@ import org.eclipse.jdt.core.dom.VariableDeclarationStatement; 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.TargetSourceRangeComputer; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; @@ -509,6 +510,7 @@ private class CheckValidityVisitor extends ASTVisitor { private List toStringList= new ArrayList<>(); private List indexOfList= new ArrayList<>(); private List argList= new ArrayList<>(); + private boolean passedAsArgument= false; public CheckValidityVisitor(int lastStatementEnd, IBinding varBinding) { this.lastStatementEnd= lastStatementEnd; @@ -519,6 +521,10 @@ public boolean isValid() { return valid; } + public boolean isPassedAsArgument() { + return passedAsArgument; + } + public ExpressionStatement getNextAssignment() { return nextAssignment; } @@ -581,8 +587,11 @@ public boolean visit(SimpleName name) { paramType.getQualifiedName().equals("java.lang.CharSequence")) { //$NON-NLS-1$ argList.add(name); valid= true; + return true; } else { - valid= false; + passedAsArgument= true; + valid= true; + return true; } } } else { @@ -739,9 +748,22 @@ public boolean visit(SimpleName simpleName) { } catch (AbortSearchException e) { // do nothing } - if (!checkValidityVisitor.isValid() || (checkValidityVisitor.getToStringList().isEmpty() && checkValidityVisitor.getArgList().isEmpty())) { + + if (!checkValidityVisitor.isValid()) { + return failure(); + } else if (checkValidityVisitor.isPassedAsArgument()) { + List statements= new ArrayList<>(statementList); + List literals= new ArrayList<>(fLiterals); + ModifyStringBufferToUseTextBlock operation= new ModifyStringBufferToUseTextBlock(node, statements, + literals); + fOperations.add(operation); + statementList.clear(); + fLiterals.clear(); + return false; + } else if (checkValidityVisitor.getToStringList().isEmpty() && checkValidityVisitor.getArgList().isEmpty()) { return failure(); } + ExpressionStatement assignmentToConvert= checkValidityVisitor.getNextAssignment(); List statements= new ArrayList<>(statementList); List literals= new ArrayList<>(fLiterals); @@ -884,6 +906,47 @@ private static boolean hasNLSMarker(ASTNode node, ICompilationUnit cu) throws Ab return hasNLS; } + public static class ModifyStringBufferToUseTextBlock extends CompilationUnitRewriteOperation { + + private final List fStatements; + private final List fLiterals; + private final ClassInstanceCreation fConstructor; + + public ModifyStringBufferToUseTextBlock(final ClassInstanceCreation constructor, final List statements, final List literals) { + fStatements= statements; + fLiterals= literals; + fConstructor= constructor; + } + + @Override + public void rewriteAST(final CompilationUnitRewrite cuRewrite, final LinkedProposalModelCore linkedModel) throws CoreException { + ASTRewrite rewrite= cuRewrite.getASTRewrite(); + TextEditGroup group= createTextEditGroup(MultiFixMessages.StringConcatToTextBlockCleanUp_description, cuRewrite); + rewrite.setTargetSourceRangeComputer(new TargetSourceRangeComputer() { + @Override + public SourceRange computeSourceRange(final ASTNode nodeWithComment) { + if (Boolean.TRUE.equals(nodeWithComment.getProperty(ASTNodes.UNTOUCH_COMMENT))) { + return new SourceRange(nodeWithComment.getStartPosition(), nodeWithComment.getLength()); + } + + return super.computeSourceRange(nodeWithComment); + } + }); + + StringBuilder buf= createTextBlockBuffer(fLiterals, cuRewrite); + TextBlock textBlock= (TextBlock) rewrite.createStringPlaceholder(buf.toString(), ASTNode.TEXT_BLOCK); + ListRewrite argList= rewrite.getListRewrite(fConstructor, ClassInstanceCreation.ARGUMENTS_PROPERTY); + List original= argList.getOriginalList(); + for (ASTNode node : original) { + rewrite.remove(node, group); + } + argList.insertFirst(textBlock, group); + for (int i= 1; i < fStatements.size(); ++i) { + rewrite.remove(fStatements.get(i), group); + } + } + } + public static class ChangeStringBufferToTextBlock extends CompilationUnitRewriteOperation { private final List fToStringList; @@ -891,7 +954,6 @@ public static class ChangeStringBufferToTextBlock extends CompilationUnitRewrite private final List fArgList; private final List fStatements; private final List fLiterals; - private String fIndent; private final Set fExcludedNames; private final BodyDeclaration fLastBodyDecl; private final boolean fNonNLS; @@ -905,7 +967,6 @@ public ChangeStringBufferToTextBlock(final List toStringList, this.fStatements= statements; this.fLiterals= literals; this.fAssignmentToConvert= assignmentToConvert; - this.fIndent= "\t"; //$NON-NLS-1$ this.fExcludedNames= excludedNames; this.fLastBodyDecl= lastBodyDecl; this.fNonNLS= nonNLS; @@ -927,19 +988,6 @@ public void rewriteAST(final CompilationUnitRewrite cuRewrite, final LinkedPropo fExcludedNames.clear(); } ASTRewrite rewrite= cuRewrite.getASTRewrite(); - IJavaElement root= cuRewrite.getRoot().getJavaElement(); - if (root != null) { - IJavaProject project= root.getJavaProject(); - if (project != null) { - String tab_option= project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true); - if (JavaCore.SPACE.equals(tab_option)) { - fIndent= ""; //$NON-NLS-1$ - for (int i= 0; i < CodeFormatterUtil.getTabWidth(project); ++i) { - fIndent += " "; //$NON-NLS-1$ - } - } - } - } TextEditGroup group= createTextEditGroup(MultiFixMessages.StringConcatToTextBlockCleanUp_description, cuRewrite); rewrite.setTargetSourceRangeComputer(new TargetSourceRangeComputer() { @Override @@ -952,53 +1000,7 @@ public SourceRange computeSourceRange(final ASTNode nodeWithComment) { } }); - StringBuilder buf= new StringBuilder(); - - List parts= new ArrayList<>(); - fLiterals.stream().forEach((t) -> { String value= t.getEscapedValue(); parts.addAll(unescapeBlock(value.substring(1, value.length() - 1))); }); - - - buf.append("\"\"\"\n"); //$NON-NLS-1$ - boolean newLine= false; - boolean allWhiteSpaceStart= true; - boolean allEmpty= true; - for (String part : parts) { - if (buf.length() > 4) {// the first part has been added after the text block delimiter and newline - if (!newLine) { - // no line terminator in this part: merge the line by emitting a line continuation escape - buf.append("\\").append(System.lineSeparator()); //$NON-NLS-1$ - } - } - newLine= part.endsWith(System.lineSeparator()); - allWhiteSpaceStart= allWhiteSpaceStart && (part.isEmpty() || Character.isWhitespace(part.charAt(0))); - allEmpty= allEmpty && part.isEmpty(); - buf.append(fIndent).append(part); - } - - if (newLine || allEmpty) { - buf.append(fIndent); - } else if (allWhiteSpaceStart) { - buf.append("\\").append(System.lineSeparator()); //$NON-NLS-1$ - buf.append(fIndent); - } else { - // Replace trailing un-escaped quotes with escaped quotes before adding text block end - int readIndex= buf.length() - 1; - int count= 0; - while (readIndex >= 0 && buf.charAt(readIndex) == '"' && count <= 3) { - --readIndex; - ++count; - } - if (readIndex >= 0 && buf.charAt(readIndex) == '\\') { - --count; - } - for (int i= count; i > 0; --i) { - buf.deleteCharAt(buf.length() - 1); - } - for (int i= count; i > 0; --i) { - buf.append("\\\""); //$NON-NLS-1$ - } - } - buf.append("\"\"\""); //$NON-NLS-1$ + StringBuilder buf= createTextBlockBuffer(fLiterals, cuRewrite); AST ast= fStatements.get(0).getAST(); if (fToStringList.size() == 1 && fIndexOfList.isEmpty() && @@ -1146,6 +1148,71 @@ public static StringConcatToTextBlockFixCore createStringConcatToTextBlockFix(AS return new StringConcatToTextBlockFixCore(FixMessages.StringConcatToTextBlockFix_convert_msg, root, new CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation[] { operations.get(0) }); } + private static StringBuilder createTextBlockBuffer(List literals, CompilationUnitRewrite cuRewrite) { + IJavaElement root= cuRewrite.getRoot().getJavaElement(); + String fIndent= "\t"; //$NON-NLS-1$ + if (root != null) { + IJavaProject project= root.getJavaProject(); + if (project != null) { + String tab_option= project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true); + if (JavaCore.SPACE.equals(tab_option)) { + fIndent= ""; //$NON-NLS-1$ + for (int i= 0; i < CodeFormatterUtil.getTabWidth(project); ++i) { + fIndent += " "; //$NON-NLS-1$ + } + } + } + } + + StringBuilder buf= new StringBuilder(); + + List parts= new ArrayList<>(); + literals.stream().forEach((t) -> { String value= t.getEscapedValue(); parts.addAll(unescapeBlock(value.substring(1, value.length() - 1))); }); + + buf.append("\"\"\"\n"); //$NON-NLS-1$ + boolean newLine= false; + boolean allWhiteSpaceStart= true; + boolean allEmpty= true; + for (String part : parts) { + if (buf.length() > 4) {// the first part has been added after the text block delimiter and newline + if (!newLine) { + // no line terminator in this part: merge the line by emitting a line continuation escape + buf.append("\\").append(System.lineSeparator()); //$NON-NLS-1$ + } + } + newLine= part.endsWith(System.lineSeparator()); + allWhiteSpaceStart= allWhiteSpaceStart && (part.isEmpty() || Character.isWhitespace(part.charAt(0))); + allEmpty= allEmpty && part.isEmpty(); + buf.append(fIndent).append(part); + } + + if (newLine || allEmpty) { + buf.append(fIndent); + } else if (allWhiteSpaceStart) { + buf.append("\\").append(System.lineSeparator()); //$NON-NLS-1$ + buf.append(fIndent); + } else { + // Replace trailing un-escaped quotes with escaped quotes before adding text block end + int readIndex= buf.length() - 1; + int count= 0; + while (readIndex >= 0 && buf.charAt(readIndex) == '"' && count <= 3) { + --readIndex; + ++count; + } + if (readIndex >= 0 && buf.charAt(readIndex) == '\\') { + --count; + } + for (int i= count; i > 0; --i) { + buf.deleteCharAt(buf.length() - 1); + } + for (int i= count; i > 0; --i) { + buf.append("\\\""); //$NON-NLS-1$ + } + } + buf.append("\"\"\""); //$NON-NLS-1$ + return buf; + } + protected StringConcatToTextBlockFixCore(final String name, final CompilationUnit compilationUnit, final CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation[] fixRewriteOperations) { super(name, compilationUnit, fixRewriteOperations); } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UnnecessaryArrayCreationFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UnnecessaryArrayCreationFixCore.java index a336ca4f17a..6f9875a2bfd 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UnnecessaryArrayCreationFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UnnecessaryArrayCreationFixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019, 2021 Red Hat Inc. and others. + * Copyright (c) 2019, 2024 Red Hat Inc. and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -37,7 +37,6 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -135,9 +134,6 @@ private ITypeBinding[] getParameterTypesForConflictingMethod(List ar } public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean removeUnnecessaryArrayCreation) { - if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject())) - return null; - if (!removeUnnecessaryArrayCreation) return null; @@ -153,9 +149,6 @@ public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, boolean } public static UnnecessaryArrayCreationFixCore createUnnecessaryArrayCreationFix(CompilationUnit compilationUnit, Expression methodInvocation) { - if (!JavaModelUtil.is50OrHigher(compilationUnit.getJavaElement().getJavaProject())) - return null; - List operations= new ArrayList<>(); UnnecessaryArrayCreationFixCore.UnnecessaryArrayCreationFinder finder= new UnnecessaryArrayCreationFixCore.UnnecessaryArrayCreationFinder(true, operations); methodInvocation.accept(finder); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UpdateProperty.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UpdateProperty.java index 973932f310a..2ebb7f3aee8 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UpdateProperty.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/UpdateProperty.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021, 2024 IBM Corporation and others. + * Copyright (c) 2021, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -59,7 +59,6 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperation; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; public enum UpdateProperty { @@ -452,55 +451,29 @@ private static void defaultRewrite(UpdateProperty upp, final MethodInvocation vi ASTRewrite rewrite= cuRewrite.getASTRewrite(); AST ast= cuRewrite.getRoot().getAST(); ASTNode replace_with_Call; - if (JavaModelUtil.is1d7OrHigher(cuRewrite.getCu().getJavaProject())) { - /** - * Add import - */ - ImportRewrite importRewrite= cuRewrite.getImportRewrite(); - importRewrite.addImport(upp.cl.getCanonicalName()); - /** - * Add first method call - */ - MethodInvocation firstCall= ast.newMethodInvocation(); - firstCall.setExpression(ASTNodeFactory.newName(ast, upp.cl.getSimpleName())); - firstCall.setName(ast.newSimpleName(upp.simplename)); + /** + * Add import + */ + ImportRewrite importRewrite= cuRewrite.getImportRewrite(); + importRewrite.addImport(upp.cl.getCanonicalName()); + /** + * Add first method call + */ + MethodInvocation firstCall= ast.newMethodInvocation(); + firstCall.setExpression(ASTNodeFactory.newName(ast, upp.cl.getSimpleName())); + firstCall.setName(ast.newSimpleName(upp.simplename)); - if(upp.simplename2==null) { - replace_with_Call= firstCall; - } else { - /** - * Add second method call - */ - MethodInvocation secondCall= ast.newMethodInvocation(); - secondCall.setExpression(firstCall); - secondCall.setName(ast.newSimpleName(upp.simplename2)); - replace_with_Call= secondCall; - } + if(upp.simplename2==null) { + replace_with_Call= firstCall; } else { - if(upp.alternativecl==null) { - /** - * can be null for System.getProperty("file.encoding") on Java < 7 - */ - return; - } else { - /** - * fallback to File.pathSeparator for java < 7.0 - */ - - /** - * Add import - */ - ImportRewrite importRewrite= cuRewrite.getImportRewrite(); - importRewrite.addImport(upp.alternativecl.getCanonicalName()); - /** - * Add field access - */ - FieldAccess fieldaccess= ast.newFieldAccess(); - fieldaccess.setExpression(ASTNodeFactory.newName(ast, upp.alternativecl.getSimpleName())); - fieldaccess.setName(ast.newSimpleName(upp.constant)); - replace_with_Call= fieldaccess; - } + /** + * Add second method call + */ + MethodInvocation secondCall= ast.newMethodInvocation(); + secondCall.setExpression(firstCall); + secondCall.setName(ast.newSimpleName(upp.simplename2)); + replace_with_Call= secondCall; } ASTNodes.replaceAndRemoveNLS(rewrite, visited, replace_with_Call, group, cuRewrite); } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ValueOfRatherThanInstantiationFixCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ValueOfRatherThanInstantiationFixCore.java index bb76b10d61b..e0d4853a476 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ValueOfRatherThanInstantiationFixCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/fix/ValueOfRatherThanInstantiationFixCore.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021 Fabrice TIERCELIN and others. + * Copyright (c) 2021, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -37,7 +37,6 @@ import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; 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.ui.cleanup.ICleanUpFix; @@ -82,11 +81,8 @@ public boolean visit(final ClassInstanceCreation visited) { return false; } - if (JavaModelUtil.is50OrHigher(((CompilationUnit) visited.getRoot()).getJavaElement().getJavaProject()) - || ASTNodes.hasType(typeBinding, String.class.getCanonicalName())) { - fResult.add(new ValueOfRatherThanInstantiationWithValueOfFixOperation(visited, typeBinding, arg0)); - return false; - } + fResult.add(new ValueOfRatherThanInstantiationWithValueOfFixOperation(visited, typeBinding, arg0)); + return false; } } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java index fcf9febf578..d4fb6b1af00 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/RefactoringCoreMessages.java @@ -107,6 +107,8 @@ public final class RefactoringCoreMessages extends NLS { public static String ChangeSignatureRefactoring_method_name_will_shadow; + public static String ChangeSignatureRefactoring_method_name_will_shadow2; + public static String ChangeSignatureRefactoring_method_name_not_empty; public static String ChangeSignatureRefactoring_modify_Parameters; @@ -777,10 +779,6 @@ public final class RefactoringCoreMessages extends NLS { public static String InferTypeArgumentsRefactoring_name; - public static String InferTypeArgumentsRefactoring_not50; - - public static String InferTypeArgumentsRefactoring_not50Library; - public static String InferTypeArgumentsRefactoring_original_elements; public static String InferTypeArgumentsRefactoring_removeCast; @@ -2473,8 +2471,6 @@ public final class RefactoringCoreMessages extends NLS { public static String TypeContextChecker_invalid_type_syntax; - public static String TypeContextChecker_no_vararg_below_50; - public static String TypeContextChecker_not_unique; public static String TypeContextChecker_parameter_type; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java index fe946e42684..b870e041711 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -493,11 +493,6 @@ public static RefactoringStatus checkParameterTypeSyntax(String type, IJavaProje return RefactoringStatus.createFatalErrorStatus(msg); } - if (ParameterInfo.isVarargs(type) && ! JavaModelUtil.is50OrHigher(project)) { - String msg= Messages.format(RefactoringCoreMessages.TypeContextChecker_no_vararg_below_50, typeLabel); - return RefactoringStatus.createFatalErrorStatus(msg); - } - List problemsCollector= new ArrayList<>(0); Type parsedType= parseType(newTypeName, project, problemsCollector); boolean valid= parsedType != null; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java index f374cf87243..f3a6fccd7a1 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/InlineConstantRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2021 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -126,7 +126,6 @@ import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.util.Progress; @@ -459,7 +458,6 @@ private static ITypeBinding getDeclaringClassBinding(SimpleName memberName) { private final CompilationUnitRewrite fCuRewrite; private final TightSourceRangeComputer fSourceRangeComputer; private final HashSet fStaticImportsInInitializer; - private final boolean fIs15; private InlineTargetCompilationUnit(CompilationUnitRewrite cuRewrite, Name[] references, InlineConstantRefactoring refactoring, HashSet staticImportsInInitializer) { fInitializer= refactoring.getInitializer(); @@ -479,8 +477,7 @@ private InlineTargetCompilationUnit(CompilationUnitRewrite cuRewrite, Name[] ref for (int i= 0; i < references.length; i++) fReferences[i]= getQualifiedReference(references[i]); - fIs15= JavaModelUtil.is50OrHigher(cuRewrite.getCu().getJavaProject()); - fStaticImportsInInitializer= fIs15 ? staticImportsInInitializer : new HashSet<>(0); + fStaticImportsInInitializer= staticImportsInInitializer; } private static Expression getQualifiedReference(Name fieldName) { @@ -579,8 +576,7 @@ private void inlineReference(Expression reference) throws CoreException { private String prepareInitializerForLocation(Expression location) throws CoreException { HashSet staticImportsInReference= new HashSet<>(); final IJavaProject project= fCuRewrite.getCu().getJavaProject(); - if (fIs15) - ImportReferencesCollector.collect(location, project, null, new ArrayList<>(), staticImportsInReference); + ImportReferencesCollector.collect(location, project, null, new ArrayList<>(), staticImportsInReference); InitializerTraversal traversal= new InitializerTraversal(fInitializer, fStaticImportsInInitializer, location, staticImportsInReference, fCuRewrite); ASTRewrite initializerRewrite= traversal.getInitializerRewrite(); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java index 4c5d0103281..fdaea5e67d7 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java @@ -268,7 +268,7 @@ public boolean visit(ClassInstanceCreation node) { if (fTypeCounter == 0) { Expression receiver= node.getExpression(); if (receiver == null) { - if (node.resolveTypeBinding().isLocal()) + if (node.resolveTypeBinding().isLocal() && !node.resolveTypeBinding().isAnonymous()) fImplicitReceivers.add(node); } } @@ -327,6 +327,12 @@ public boolean visit(ThisExpression node) { if (fTypeCounter == 0) { fImplicitReceivers.add(node); } + if (node.getQualifier() instanceof Name qualifier) { + IBinding binding= qualifier.resolveBinding(); + if (binding instanceof ITypeBinding) { + fImplicitReceivers.add(node); + } + } return true; } private void addReferencesToName(SimpleName node) { diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/generics/InferTypeArgumentsRefactoring.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/generics/InferTypeArgumentsRefactoring.java index f0108588dd9..364c24e0997 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/generics/InferTypeArgumentsRefactoring.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/generics/InferTypeArgumentsRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -273,20 +273,13 @@ private HashMap> getJavaElementsPerProject return result; } - private RefactoringStatus check15() throws CoreException { + private RefactoringStatus check15() { RefactoringStatus result= new RefactoringStatus(); HashSet checkedProjects= new HashSet<>(); for (IJavaElement element : fElements) { IJavaProject javaProject= element.getJavaProject(); if (! checkedProjects.contains(javaProject)) { - if (! JavaModelUtil.is50OrHigher(javaProject)) { - String message= Messages.format(RefactoringCoreMessages.InferTypeArgumentsRefactoring_not50, BasicElementLabels.getJavaElementName(javaProject.getElementName())); - result.addFatalError(message); - } else if (! JavaModelUtil.is50OrHigherJRE(javaProject)) { - String message= Messages.format(RefactoringCoreMessages.InferTypeArgumentsRefactoring_not50Library, BasicElementLabels.getJavaElementName(javaProject.getElementName())); - result.addFatalError(message); - } checkedProjects.add(javaProject); } } diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties index 39686dbd695..4f07fdaf7a8 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/refactoring.properties @@ -809,6 +809,7 @@ ChangeSignatureRefactoring_native=Method ''{0}'' declared in type ''{1}'' is nat ChangeSignatureRefactoring_duplicate_name=Duplicate parameter name: ''{0}''. ChangeSignatureRefactoring_return_type_contains_type_variable=The return type ''{0}'' contains the type variable ''{1}'', which may not be available in related methods. ChangeSignatureRefactoring_method_name_will_shadow=Renaming method ''{0}'' to ''{1}'' causes potential logic change due to an existing ''{0}'' method accessible at a call location. +ChangeSignatureRefactoring_method_name_will_shadow2=Renaming method ''{0}'' to ''{1}'' causes potential logic change due to an existing ''{1}'' method accessible at a call location. ChangeSignatureRefactoring_method_name_not_empty=The method name cannot be empty. ChangeSignatureRefactoring_default_value=Enter the default value for parameter ''{0}''. ChangeSignatureRefactoring_default_visibility=(package) @@ -849,7 +850,6 @@ TypeContextChecker_couldNotResolveType=Could not resolve type ''{0}''. TypeContextChecker_ambiguous=Parameter type name ''{0}'' is ambiguous. There are {1} types with that name. TypeContextChecker_not_unique=Parameter type name ''{0}'' cannot be uniquely resolved or is not a valid type name. TypeContextChecker_parameter_type=Enter the type for parameter ''{0}''. -TypeContextChecker_no_vararg_below_50=''{0}'' is not a valid parameter type; variable arity parameters are only supported if the source level is 1.5. TypeContextChecker_invalid_type_name=''{0}'' is not a valid parameter type. TypeContextChecker_invalid_type_syntax=''{0}'' is not a valid parameter type: {1}. TypeContextChecker_return_type_not_empty=The return type cannot be empty. @@ -1398,7 +1398,6 @@ MakeStaticRefactoring_change_name=Change in ''{0}''. #--- Infer Type Arguments InferTypeArgumentsRefactoring_name=Infer Type Arguments -InferTypeArgumentsRefactoring_not50=Project ''{0}'' cannot be processed since its compiler source level is below 1.5. InferTypeArgumentsRefactoring_calculating_dependencies=Calculating dependencies... InferTypeArgumentsRefactoring_descriptor_description_project=Infer generic type arguments on ''{0}'' InferTypeArgumentsRefactoring_descriptor_description=Infer generic type arguments @@ -1409,7 +1408,6 @@ InferTypeArgumentsRefactoring_internal_error=Internal error while inferring type InferTypeArgumentsRefactoring_addTypeArguments=Add type arguments InferTypeArgumentsRefactoring_original_elements=Original elements: InferTypeArgumentsRefactoring_removeCast=Remove cast -InferTypeArgumentsRefactoring_not50Library=Project ''{0}'' cannot be processed since its JRE System Library version is below 1.5. InferTypeArgumentsRefactoring_assume_clone=Assume clone() returns an instance of the receiver type InferTypeArgumentsRefactoring_error_skipped=An unexpected error happened while processing ''{0}''. The rest of this compilation unit has been skipped. InferTypeArgumentsRefactoring_error_in_cu_skipped=Compile errors found in ''{0}''. The compilation unit has been skipped. diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java index fbadfe5f166..e42ef25cbbd 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureProcessor.java @@ -62,6 +62,7 @@ import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ASTParser; +import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.AbstractTypeDeclaration; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.Block; @@ -96,6 +97,7 @@ import org.eclipse.jdt.core.dom.TagElement; import org.eclipse.jdt.core.dom.TextElement; import org.eclipse.jdt.core.dom.Type; +import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; @@ -116,6 +118,7 @@ import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.core.search.SearchMatch; import org.eclipse.jdt.core.search.SearchPattern; +import org.eclipse.jdt.core.search.TypeReferenceMatch; import org.eclipse.jdt.internal.core.manipulation.JavaElementLabelsCore; import org.eclipse.jdt.internal.core.manipulation.JavaManipulationPlugin; @@ -127,6 +130,7 @@ import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; +import org.eclipse.jdt.internal.corext.dom.AbortSearchException; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; import org.eclipse.jdt.internal.corext.dom.ModifierRewrite; @@ -426,6 +430,8 @@ private RefactoringStatus checkSignature(boolean resolveBindings) { if (result.hasFatalError()) return result; checkShadowing(result); + if (!result.hasError()) + checkShadowing2(result); if (result.hasFatalError()) return result; checkParameterNamesAndValues(result); @@ -494,6 +500,99 @@ private void checkShadowing(RefactoringStatus result) { } } + private class ShadowedMethodVisitor extends ASTVisitor { + private MethodInvocation fMethodInvocation; + + public MethodInvocation getMethod() { + return fMethodInvocation; + } + + @Override + public boolean visit(MethodInvocation node) { + if (node.getName().getFullyQualifiedName().equals(fMethodName) && + node.getExpression() == null) { + IMethodBinding binding= node.resolveMethodBinding(); + if (binding.getParameterTypes().length == fParameterInfos.size()) { + for (int i= 0; i < binding.getParameterTypes().length; ++i) { + String simpleName= binding.getParameterTypes()[0].getName(); + String newTypeName= fParameterInfos.get(i).getNewTypeName(); + if (!simpleName.equals(newTypeName) && isKnownIncompatible(simpleName, newTypeName)) { + return true; + } + } + fMethodInvocation= node; + throw new AbortSearchException(); + } + } + return true; + } + } + + private void checkShadowing2(RefactoringStatus result) { + try { + if (!fMethodName.equals(fMethod.getElementName())) { + ICompilationUnit icu= fMethod.getCompilationUnit(); + CompilationUnit cu= Checks.convertICUtoCU(icu); + if (cu == null) { + return; + } + ShadowedMethodVisitor visitor= new ShadowedMethodVisitor(); + try { + AbstractTypeDeclaration methodTypeDecl= ASTNodeSearchUtil.getAbstractTypeDeclarationNode(fMethod.getDeclaringType(), cu); + if (methodTypeDecl != null) { + methodTypeDecl.accept(visitor); + } + } catch (AbortSearchException e) { + MethodInvocation method= visitor.getMethod(); + RefactoringStatusContext context= JavaStatusContext.create(icu, new SourceRange(method.getStartPosition(), method.getLength())); + String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_method_name_will_shadow2, new Object[] {fMethod.getElementName(), fMethodName}); + if (fMethod.getParameterNames().length == 0) { + result.addFatalError(msg, context); + } else { + result.addError(msg, context); + } + return; + } + if (!Modifier.isPrivate(fMethod.getFlags())) { + SearchResultGroup[] matches= findImplementors(fMethod.getDeclaringType(), new NullProgressMonitor()); + for (SearchResultGroup match : matches) { + icu= match.getCompilationUnit(); + cu= Checks.convertICUtoCU(icu); + if (cu == null) { + return; + } + for (SearchMatch matchResult : match.getSearchResults()) { + if (matchResult instanceof TypeReferenceMatch typeMatch && typeMatch.getElement() instanceof IType type) { + final TypeDeclaration typeDecl= ASTNodeSearchUtil.getTypeDeclarationNode(type, cu); + if (typeDecl != null) { + ITypeBinding typeBinding= typeDecl.resolveBinding(); + if (Modifier.isPublic(fMethod.getFlags()) || Modifier.isProtected(fMethod.getFlags()) || + typeBinding != null && typeBinding.getPackage().getName().equals(fMethod.getDeclaringType().getPackageFragment().getElementName())) { + visitor= new ShadowedMethodVisitor(); + try { + typeDecl.accept(visitor); + } catch (AbortSearchException e) { + MethodInvocation method= visitor.getMethod(); + RefactoringStatusContext context= JavaStatusContext.create(icu, new SourceRange(method.getStartPosition(), method.getLength())); + String msg= Messages.format(RefactoringCoreMessages.ChangeSignatureRefactoring_method_name_will_shadow2, new Object[] {fMethod.getElementName(), fMethodName}); + if (fMethod.getParameterNames().length == 0) { + result.addFatalError(msg, context); + } else { + result.addError(msg, context); + } + } + } + } + } + } + } + } + } + } catch (JavaModelException e) { + // ignore and exit + } + } + private boolean recursiveShadowCheck(ITypeBinding typeBinding, String origPackage, boolean allowPrivate) { if (typeBinding == null) { return false; @@ -503,6 +602,13 @@ private boolean recursiveShadowCheck(ITypeBinding typeBinding, String origPackag if (method.getName().equals(fMethodName) && method.getParameterNames().length == fParameterInfos.size() && (allowPrivate || Modifier.isPublic(method.getModifiers()) || Modifier.isProtected(method.getModifiers()) || !Modifier.isPrivate(method.getModifiers()) && typeBinding.getPackage().getName().equals(origPackage))) { + for (int i= 0; i < method.getParameterTypes().length; ++i) { + String simpleName= method.getParameterTypes()[0].getName(); + String newTypeName= fParameterInfos.get(i).getNewTypeName(); + if (!simpleName.equals(newTypeName) && isKnownIncompatible(simpleName, newTypeName)) { + return false; + } + } return true; } } @@ -523,6 +629,78 @@ private boolean recursiveShadowCheck(ITypeBinding typeBinding, String origPackag return false; } + private Set fIntSet= new HashSet<>(List.of("char", "int", "long", "short", "Integer", "Long", "Short")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ + private Set fFloatSet= new HashSet<>(List.of("float", "double", "Float", "Double")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ // + private Set fBooleanSet= new HashSet<>(List.of("boolean", "Boolean")); //$NON-NLS-1$ //$NON-NLS-2$ // + private Set fWellUsedSet= new HashSet<>(List.of( + "Date", //$NON-NLS-1$ + "String", //$NON-NLS-1$ + "Integer", //$NON-NLS-1$ + "Long", //$NON-NLS-1$ + "Short", //$NON-NLS-1$ + "Character", //$NON-NLS-1$ + "Float", //$NON-NLS-1$ + "Double", //$NON-NLS-1$ + "Boolean", //$NON-NLS-1$ + "List", //$NON-NLS-1$ + "Map", //$NON-NLS-1$ + "Set", //$NON-NLS-1$ + "Iterable", //$NON-NLS-1$ + "Byte", //$NON-NLS-1$ + "int", //$NON-NLS-1$ + "long", //$NON-NLS-1$ + "short", //$NON-NLS-1$ + "float", //$NON-NLS-1$ + "double", //$NON-NLS-1$ + "boolean", //$NON-NLS-1$ + "char" //$NON-NLS-1$ + )); + + + private boolean isKnownIncompatible(String simpleName, String newTypeName) { + if (simpleName.isEmpty() || newTypeName.isEmpty()) { + return true; + } + if (simpleName.endsWith("[]") || newTypeName.endsWith("[]")) { //$NON-NLS-1$ //$NON-NLS-2$ + return true; + } + if (simpleName.indexOf('<') >= 0) { + simpleName= simpleName.substring(0, simpleName.indexOf('<')); + } + if (newTypeName.indexOf('<') >= 0) { + newTypeName= newTypeName.substring(0, newTypeName.indexOf('<')); + } + if (fIntSet.contains(simpleName) && fIntSet.contains(newTypeName)) { + return false; + } + if (fFloatSet.contains(simpleName) && fFloatSet.contains(newTypeName)) { + return false; + } + if (fBooleanSet.contains(simpleName) && fBooleanSet.contains(newTypeName)) { + return false; + } + if (fWellUsedSet.contains(simpleName) && fWellUsedSet.contains(newTypeName)) { + return true; + } + if (Character.isLowerCase(simpleName.charAt(0)) != Character.isLowerCase(newTypeName.charAt(0))) { + return true; + } + return false; + } + + private SearchResultGroup[] findImplementors(final IType type, final IProgressMonitor monitor) throws JavaModelException { + SearchPattern pattern= SearchPattern.createPattern(type, IJavaSearchConstants.IMPLEMENTORS, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE); + if (pattern == null) { + return new SearchResultGroup[0]; + } + final RefactoringSearchEngine2 engine= new RefactoringSearchEngine2(pattern); + engine.setOwner(fOwner); + engine.setFiltering(true, true); + engine.setScope(RefactoringScopeFactory.create(type)); + engine.searchPattern(monitor); + return (SearchResultGroup[]) engine.getResults(); + } + private SearchResultGroup[] findReferences(final IMember member, final IProgressMonitor monitor) throws JavaModelException { SearchPattern pattern= SearchPattern.createPattern(member, IJavaSearchConstants.REFERENCES, SearchUtils.GENERICS_AGNOSTIC_MATCH_RULE); if (pattern == null) { diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java index f3641f9abe0..d281fab7b10 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -589,7 +589,6 @@ private void rewriteSourceMethods(final CompilationUnitRewrite sourceRewrite, fi Assert.isNotNull(replacements); if (fMembers.length > 0) { IJavaProject project= fSubType.getJavaProject(); - boolean annotations= fAnnotations && !JavaModelUtil.isVersionLessThan(project.getOption(JavaCore.COMPILER_SOURCE, true), JavaCore.VERSION_1_6); boolean inheritNullAnnotations= JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_INHERIT_NULL_ANNOTATIONS, true)); boolean javadoc= JavaCore.ENABLED.equals(project.getOption(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, true)); for (IMember member : fMembers) { @@ -619,7 +618,7 @@ private void rewriteSourceMethods(final CompilationUnitRewrite sourceRewrite, fi } } } - if (annotations) { + if (fAnnotations) { StubUtility2Core.createOverrideAnnotation(sourceRewrite.getASTRewrite(), sourceRewrite.getImportRewrite(), declaration, null); } if (fComments) diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java index c1e846aabc1..e2eef14c184 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/refactoring/structure/constraints/SuperTypeRefactoringProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -1137,9 +1137,6 @@ protected final void solveSuperTypeConstraints(final ICompilationUnit subUnit, f ICompilationUnit current= null; final Map groups= new HashMap<>(); for (Map.Entry> entry : firstPass.entrySet()) { - IJavaProject project = entry.getKey(); - if (level == 3 && !JavaModelUtil.is50OrHigher(project)) - level= 2; collection= entry.getValue(); if (collection != null) { for (SearchResultGroup group : collection) { @@ -1233,8 +1230,6 @@ public final void acceptBinding(final String key, final IBinding binding) { subMonitor.beginTask("", keySet.size() * 100); //$NON-NLS-1$ subMonitor.setTaskName(RefactoringCoreMessages.SuperTypeRefactoringProcessor_creating); for (IJavaProject project : keySet) { - if (level == 3 && !JavaModelUtil.is50OrHigher(project)) - level= 2; Collection cuCollection= secondPass.get(project); if (cuCollection != null) { parser.setWorkingCopyOwner(fOwner); diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContextCore.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContextCore.java index 31a4e755c2f..fe9eab997c0 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContextCore.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/template/java/JavaContextCore.java @@ -626,11 +626,9 @@ private CompilationUnit getASTRoot(ICompilationUnit compilationUnit) { * Finds a type by the simple name. From AddImportsOperation */ private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor, ICompilationUnit cu) throws JavaModelException { - boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject()); - int typeKinds= TypeKinds.ALL_TYPES; if (nameNode != null) { - typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher); + typeKinds= ASTResolving.getPossibleTypeKinds(nameNode); } ArrayList typeInfos= new ArrayList<>(); @@ -640,7 +638,7 @@ private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope sea ArrayList typeRefsFound= new ArrayList<>(typeInfos.size()); for (TypeNameMatch curr : typeInfos) { if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package - if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) { + if (isOfKind(curr, typeKinds) && isVisible(curr, cu)) { typeRefsFound.add(curr); } } @@ -665,13 +663,13 @@ private int getSearchForConstant(int typeKinds) { } } - private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) { + private boolean isOfKind(TypeNameMatch curr, int typeKinds) { int flags= curr.getModifiers(); if (Flags.isAnnotation(flags)) { - return is50OrHigher && ((typeKinds & TypeKinds.ANNOTATIONS) != 0); + return (typeKinds & TypeKinds.ANNOTATIONS) != 0; } if (Flags.isEnum(flags)) { - return is50OrHigher && ((typeKinds & TypeKinds.ENUMS) != 0); + return (typeKinds & TypeKinds.ENUMS) != 0; } if (Flags.isInterface(flags)) { return (typeKinds & TypeKinds.INTERFACES) != 0; diff --git a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java index c8eccf6ea08..e0549435efe 100644 --- a/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java +++ b/org.eclipse.jdt.core.manipulation/core extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2024 IBM Corporation and others. + * Copyright (c) 2000, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -65,9 +65,7 @@ import org.eclipse.jdt.internal.core.manipulation.JavaManipulationMessages; -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; /** @@ -793,23 +791,6 @@ public static boolean isVersionLessThan(String version1, String version2) { return JavaCore.compareJavaVersions(version1, version2) < 0; } - - public static boolean is1d2OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_2); - } - - public static boolean is40OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_4); - } - - public static boolean is50OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_5); - } - - public static boolean is1d6OrHigher(String compliance) { - return !isVersionLessThan(compliance, JavaCore.VERSION_1_6); - } - public static boolean is1d7OrHigher(String compliance) { return !isVersionLessThan(compliance, JavaCore.VERSION_1_7); } @@ -882,46 +863,6 @@ public static boolean is24OrHigher(String compliance) { return !isVersionLessThan(compliance, JavaCore.VERSION_24); } - /** - * Checks if the given project or workspace has source compliance 1.2 or greater. - * - * @param project the project to test or null to test the workspace settings - * @return true if the given project or workspace has source compliance 1.2 or greater. - */ - public static boolean is1d2OrHigher(IJavaProject project) { - return is1d2OrHigher(getSourceCompliance(project)); - } - - /** - * Checks if the given project or workspace has source compliance 1.4 or greater. - * - * @param project the project to test or null to test the workspace settings - * @return true if the given project or workspace has source compliance 1.4 or greater. - */ - public static boolean is1d4OrHigher(IJavaProject project) { - return is40OrHigher(getSourceCompliance(project)); - } - - /** - * Checks if the given project or workspace has source compliance 1.5 or greater. - * - * @param project the project to test or null to test the workspace settings - * @return true if the given project or workspace has source compliance 1.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 null to test the workspace settings - * @return true if the given project or workspace has source compliance 1.7 or greater. - */ - public static boolean is1d7OrHigher(IJavaProject project) { - return is1d7OrHigher(getSourceCompliance(project)); - } - /** * Checks if the given project or workspace has source compliance 1.8 or greater. * @@ -1120,31 +1061,6 @@ public static boolean isLatestOrHigherJavaVersion(String compliance) { return !isVersionLessThan(compliance, JavaCore.latestSupportedJavaVersion()); } - /** - * 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 null to test the workspace JRE - * @return true 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) { diff --git a/org.eclipse.jdt.core.manipulation/forceQualifierUpdate.txt b/org.eclipse.jdt.core.manipulation/forceQualifierUpdate.txt index 24d48ad135a..b69e5071f8f 100644 --- a/org.eclipse.jdt.core.manipulation/forceQualifierUpdate.txt +++ b/org.eclipse.jdt.core.manipulation/forceQualifierUpdate.txt @@ -1,2 +1,3 @@ https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/1979 -https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2044 \ No newline at end of file +https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2044 +https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2595 \ No newline at end of file diff --git a/org.eclipse.jdt.core.manipulation/proposals/org/eclipse/jdt/internal/ui/text/correction/SuppressWarningsBaseSubProcessor.java b/org.eclipse.jdt.core.manipulation/proposals/org/eclipse/jdt/internal/ui/text/correction/SuppressWarningsBaseSubProcessor.java index 5f49e8cf91e..4fcb074f591 100644 --- a/org.eclipse.jdt.core.manipulation/proposals/org/eclipse/jdt/internal/ui/text/correction/SuppressWarningsBaseSubProcessor.java +++ b/org.eclipse.jdt.core.manipulation/proposals/org/eclipse/jdt/internal/ui/text/correction/SuppressWarningsBaseSubProcessor.java @@ -53,7 +53,6 @@ import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.internal.corext.fix.IProposableFix; import org.eclipse.jdt.internal.corext.fix.UnusedSuppressWarningsFixCore; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.CleanUpOptions; @@ -68,7 +67,7 @@ public abstract class SuppressWarningsBaseSubProcessor { static final String ADD_SUPPRESSWARNINGS_ID= "org.eclipse.jdt.ui.correction.addSuppressWarnings"; //$NON-NLS-1$ public static final boolean hasSuppressWarningsProposal(IJavaProject javaProject, int problemId) { - if (CorrectionEngine.getWarningToken(problemId) != null && JavaModelUtil.is50OrHigher(javaProject)) { + if (CorrectionEngine.getWarningToken(problemId) != null) { String optionId= JavaCore.getOptionForConfigurableSeverity(problemId); if (optionId != null) { String optionValue= javaProject.getOption(optionId, true); diff --git a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHint.java b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHint.java index d60f27fa92d..e5ab4d6abc4 100644 --- a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHint.java +++ b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSHint.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -18,6 +18,7 @@ import java.util.Properties; import java.util.SortedMap; import java.util.TreeMap; +import java.util.regex.Pattern; import org.eclipse.osgi.util.NLS; @@ -51,7 +52,6 @@ import org.eclipse.jdt.internal.corext.util.JavaModelUtil; - /** * calculates hints for the nls-refactoring out of a compilation unit. * - package fragments of the accessor class and the resource bundle @@ -59,6 +59,13 @@ */ public class NLSHint { + /** + * A text block begins with three double-quote characters followed by zero or more white spaces followed by + * a line terminator. A text block cannot be on a single line, nor can the contents of the text block follow + * the three opening double-quotes (and maybe whitespace) immediately without a line terminator. + */ + private static final Pattern TEXT_BLOCK_START_PATTERN = Pattern.compile("^\"\"\"\\s*\r?\n"); //$NON-NLS-1$ + private String fAccessorName; private IPackageFragment fAccessorPackage; private String fResourceBundleName; @@ -159,7 +166,7 @@ public boolean visit(QualifiedName node) { } SimpleName name= node.getName(); NLSElement element= new NLSElement(node.getName().getIdentifier(), name.getStartPosition(), - name.getLength(), nlsLine.size() - 1, true); + name.getLength(), nlsLine.size() - 1, true); nlsLine.add(element); String bundleName; ICompilationUnit bundleCU= (ICompilationUnit)type.getJavaElement().getAncestor(IJavaElement.COMPILATION_UNIT); @@ -261,10 +268,11 @@ private static AccessorClassReference findFirstAccessorReference(NLSLine[] lines } public static String stripQuotes(String str, IJavaProject project) { - if (JavaModelUtil.is15OrHigher(project)) { - if (str.startsWith("\"\"\"") && str.endsWith("\"\"\"")) { //$NON-NLS-1$ //$NON-NLS-2$ - return getTextBlock(str.substring(3, str.length() - 3)); - } + // Test if the given string is a text block and start with the "cheapest" check + if (str.endsWith("\"\"\"") //$NON-NLS-1$ + && TEXT_BLOCK_START_PATTERN.matcher(str).find() + && JavaModelUtil.is15OrHigher(project)) { + return getTextBlock(str.substring(3, str.length() - 3)); } return str.substring(1, str.length() - 1); } @@ -277,15 +285,10 @@ private static NLSLine[] createRawLines(ICompilationUnit cu) { } } - public String getAccessorClassName() { return fAccessorName; } -// public boolean isEclipseNLS() { -// return fIsEclipseNLS; -// } - public IPackageFragment getAccessorClassPackage() { return fAccessorPackage; } @@ -559,5 +562,4 @@ private static int getHexadecimalValue(char c) { return -1; } } - } diff --git a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java index 279ea8fb4e5..bae2bfa94d3 100644 --- a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java +++ b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractClassRefactoring.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2018 IBM Corporation and others. + * Copyright (c) 2007, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -618,12 +618,11 @@ private RefactoringStatus replaceReferences(ParameterObjectFactory pof, SearchRe private Expression getAssignedValue(ParameterObjectFactory pof, String parameterName, IJavaProject javaProject, RefactoringStatus status, ASTRewrite rewrite, ParameterInfo pi, boolean useSuper, ITypeBinding typeBinding, Expression qualifier, ASTNode replaceNode, ITypeRoot typeRoot) { AST ast= rewrite.getAST(); - boolean is50OrHigher= JavaModelUtil.is50OrHigher(javaProject); Expression assignedValue= handleSimpleNameAssignment(replaceNode, pof, parameterName, ast, javaProject, useSuper); if (assignedValue == null) { NullLiteral marker= qualifier == null ? null : ast.newNullLiteral(); Expression fieldReadAccess= pof.createFieldReadAccess(pi, parameterName, ast, javaProject, useSuper, marker); - assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding, is50OrHigher); + assignedValue= GetterSetterUtil.getAssignedValue(replaceNode, rewrite, fieldReadAccess, typeBinding); boolean markerReplaced= replaceMarker(rewrite, qualifier, assignedValue, marker); if (markerReplaced && qualifier != null) { switch (qualifier.getNodeType()) { diff --git a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java index 70f05e11e02..c50983c59dc 100644 --- a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java +++ b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/HierarchyProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2023 IBM Corporation and others. + * Copyright (c) 2006, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -17,7 +17,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; @@ -98,7 +97,6 @@ import org.eclipse.jdt.internal.corext.refactoring.util.JavaStatusContext; import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser; import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.corext.util.SearchUtils; @@ -174,37 +172,8 @@ protected static boolean areAllFragmentsDeleted(final FieldDeclaration declarati return declarationNodes.containsAll(declaration.fragments()); } - protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite sourceRewriter, IType destination, IMember[] members) { + protected static RefactoringStatus checkProjectCompliance() { RefactoringStatus status= new RefactoringStatus(); - if (!JavaModelUtil.is50OrHigher(destination.getJavaProject())) { - for (IMember member : members) { - try { - BodyDeclaration decl= ASTNodeSearchUtil.getBodyDeclarationNode(member, sourceRewriter.getRoot()); - if (decl != null) { - for (final Iterator iterator= decl.modifiers().iterator(); iterator.hasNext();) { - boolean reported= false; - final IExtendedModifier modifier= iterator.next(); - if (!reported && modifier.isAnnotation()) { - status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.PullUpRefactoring_incompatible_langauge_constructs, new String[]{JavaElementLabelsCore.getTextLabel(member, JavaElementLabelsCore.ALL_FULLY_QUALIFIED), JavaElementLabelsCore.getTextLabel(destination, JavaElementLabelsCore.ALL_DEFAULT)}), JavaStatusContext.create(member))); - reported= true; - } - } - } - } catch (JavaModelException exception) { - JavaManipulationPlugin.log(exception); - } - if (member instanceof IMethod) { - final IMethod method= (IMethod) member; - try { - if (Flags.isVarargs(method.getFlags())) { - status.merge(RefactoringStatus.createErrorStatus(Messages.format(RefactoringCoreMessages.PullUpRefactoring_incompatible_language_constructs1, new String[]{JavaElementLabelsCore.getTextLabel(member, JavaElementLabelsCore.ALL_FULLY_QUALIFIED), JavaElementLabelsCore.getTextLabel(destination, JavaElementLabelsCore.ALL_DEFAULT)}), JavaStatusContext.create(member))); - } - } catch (JavaModelException exception) { - JavaManipulationPlugin.log(exception); - } - } - } - } return status; } diff --git a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java index 848be021875..73c30d1e13e 100644 --- a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java +++ b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoringProcessor.java @@ -1190,7 +1190,7 @@ public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, fi if (result.hasFatalError()) return result; fCompilationUnitRewrites= new HashMap<>(3); - result.merge(checkProjectCompliance(getCompilationUnitRewrite(fCompilationUnitRewrites, getDeclaringType().getCompilationUnit()), getDestinationType(), fMembersToMove)); + result.merge(checkProjectCompliance()); fChangeManager= createChangeManager(subMonitor.newChild(1), result); Checks.addModifiedFilesToChecker(ResourceUtil.getFiles(fChangeManager.getAllCompilationUnits()), context); @@ -1250,6 +1250,18 @@ public boolean visit(SimpleName node) { return true; } + @Override + public boolean visit(ThisExpression node) { + if (node.getLocationInParent() == MethodInvocation.ARGUMENTS_PROPERTY) { + ITypeBinding typeBinding= node.resolveTypeBinding(); + if (isChildTypeMember(typeBinding, fSourceType) && !isChildTypeMember(typeBinding, fTargetType)) { + fConflictBinding= typeBinding; + throw new AbortSearchException(); + } + } + return super.visit(node); + } + private boolean isChildTypeMember(ITypeBinding parentTypeBinding, IType type) { if (parentTypeBinding.getQualifiedName().equals(type.getFullyQualifiedName('.'))) { return true; diff --git a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java index dab26048b78..dcf1ed065b5 100644 --- a/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java +++ b/org.eclipse.jdt.core.manipulation/refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoringProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2006, 2023 IBM Corporation and others. + * Copyright (c) 2006, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -125,7 +125,6 @@ import org.eclipse.jdt.internal.corext.refactoring.util.JavaStatusContext; import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.corext.util.SearchUtils; @@ -859,7 +858,7 @@ private void copyMembers(Collection adjustors, Map org.eclipse.jdt org.eclipse.jdt.junit.runtime - 3.7.500-SNAPSHOT + 3.7.600-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.junit.runtime/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java b/org.eclipse.jdt.junit.runtime/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java index 8e9b6390cd7..d0429e9ce2e 100644 --- a/org.eclipse.jdt.junit.runtime/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java +++ b/org.eclipse.jdt.junit.runtime/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java @@ -386,15 +386,19 @@ public void setLoader(ITestLoader newInstance) { fLoader = newInstance; } - private void readPackageNames(String pkgNameFile) throws IOException { - try(BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(new File(pkgNameFile)), StandardCharsets.UTF_8))) { + private String[] readLines(String fileName) throws IOException { + try(BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(new File(fileName)), StandardCharsets.UTF_8))) { String line; Vector list= new Vector<>(); while ((line= br.readLine()) != null) { list.add(line); } - fPackageNames= list.toArray(new String[list.size()]); + return list.toArray(new String[list.size()]); } + } + + private void readPackageNames(String pkgNameFile) throws IOException { + fPackageNames= readLines(pkgNameFile); if (fDebugMode) { System.out.println("Packages:"); //$NON-NLS-1$ for (String fPackageName : fPackageNames) { @@ -404,14 +408,7 @@ private void readPackageNames(String pkgNameFile) throws IOException { } private void readTestNames(String testNameFile) throws IOException { - try(BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(new File(testNameFile)), StandardCharsets.UTF_8))) { - String line; - Vector list= new Vector<>(); - while ((line= br.readLine()) != null) { - list.add(line); - } - fTestClassNames= list.toArray(new String[list.size()]); - } + fTestClassNames= readLines(testNameFile); if (fDebugMode) { System.out.println("Tests:"); //$NON-NLS-1$ for (String fTestClassName : fTestClassNames) { @@ -421,14 +418,7 @@ private void readTestNames(String testNameFile) throws IOException { } private void readFailureNames(String testFailureFile) throws IOException { - try(BufferedReader br= new BufferedReader(new InputStreamReader(new FileInputStream(new File(testFailureFile)), StandardCharsets.UTF_8))) { - String line; - Vector list= new Vector<>(); - while ((line= br.readLine()) != null) { - list.add(line); - } - fFailureNames= list.toArray(new String[list.size()]); - } + fFailureNames = readLines(testFailureFile); if (fDebugMode) { System.out.println("Failures:"); //$NON-NLS-1$ for (String fFailureName : fFailureNames) { @@ -510,7 +500,7 @@ protected void notifyListenersOfTestEnd(TestExecution execution, * @param testName individual method to be run * @param execution executor */ - public void runTests(String[] testClassNames, String testName, TestExecution execution) { + private void runTests(String[] testClassNames, String testName, TestExecution execution) { ITestReference[] suites= fLoader.loadTests(loadClasses(testClassNames), testName, fFailureNames, fPackageNames, fIncludeExcludeTags, fUniqueId, this); // count all testMethods and inform ITestRunListeners @@ -754,7 +744,7 @@ public void flush() { fWriter.flush(); } - public void runTests(TestExecution execution) { + private void runTests(TestExecution execution) { runTests(fTestClassNames, fTestName, execution); } diff --git a/org.eclipse.jdt.junit/forceQualifierUpdate.txt b/org.eclipse.jdt.junit/forceQualifierUpdate.txt index fbac559a119..543e637bd78 100644 --- a/org.eclipse.jdt.junit/forceQualifierUpdate.txt +++ b/org.eclipse.jdt.junit/forceQualifierUpdate.txt @@ -15,4 +15,5 @@ Bug 527899 [9] Implement JEP 280: Indify String Concatenation https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/1659 https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/1781 https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/1923 -https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2044 \ No newline at end of file +https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2044 +https://github.com/eclipse-platform/eclipse.platform.releng.aggregator/issues/2595 \ No newline at end of file diff --git a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java index a982151d7b3..00c347c3133 100644 --- a/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java +++ b/org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestViewer.java @@ -450,14 +450,14 @@ private OpenTestAction getOpenTestAction(TestSuiteElement testSuite) { if (children.length > 0 && children[0] instanceof TestCaseElement tce && tce.isDynamicTest()) { // a group of parameterized tests - return new OpenTestAction(fTestRunnerPart, (TestCaseElement) children[0], null); + return new OpenTestAction(fTestRunnerPart, tce, tce.getParameterTypes()); } if (children.length == 0) { // check if we have applied the workaround for: https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/945 TestCaseElement child= testSuite.getSingleDynamicChild(); if (child != null) { // a parameterized test that ran only one test - return new OpenTestAction(fTestRunnerPart, child, null); + return new OpenTestAction(fTestRunnerPart, child, child.getParameterTypes()); } } diff --git a/org.eclipse.jdt.text.tests/META-INF/MANIFEST.MF b/org.eclipse.jdt.text.tests/META-INF/MANIFEST.MF index 5fa7dbb4710..b3b6d006ff1 100644 --- a/org.eclipse.jdt.text.tests/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.text.tests/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.text.tests Bundle-ManifestVersion: 2 Bundle-Name: %Plugin.name Bundle-SymbolicName: org.eclipse.jdt.text.tests;singleton:=true -Bundle-Version: 3.14.600.qualifier +Bundle-Version: 3.14.700.qualifier Bundle-Activator: org.eclipse.jdt.text.tests.JdtTextTestPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %Plugin.providerName diff --git a/org.eclipse.jdt.text.tests/plugin.xml b/org.eclipse.jdt.text.tests/plugin.xml index 49a78dccb84..22423af2496 100644 --- a/org.eclipse.jdt.text.tests/plugin.xml +++ b/org.eclipse.jdt.text.tests/plugin.xml @@ -47,4 +47,10 @@ + + + + diff --git a/org.eclipse.jdt.text.tests/pom.xml b/org.eclipse.jdt.text.tests/pom.xml index 67c19fdd529..e2192b08663 100644 --- a/org.eclipse.jdt.text.tests/pom.xml +++ b/org.eclipse.jdt.text.tests/pom.xml @@ -20,7 +20,7 @@ org.eclipse.jdt org.eclipse.jdt.text.tests - 3.14.600-SNAPSHOT + 3.14.700-SNAPSHOT eclipse-test-plugin diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java index d7e66edcd8d..3e733cd1b5d 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/AbstractForLoopJavaContextTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2014, 2020 IBM Corporation and others. + * Copyright (c) 2014, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -55,11 +55,11 @@ public abstract class AbstractForLoopJavaContextTest { private static final String CU_PREFIX= """ package test; - + import java.io.Serializable; import java.util.Collection; import java.util.List; - + public class A { """; @@ -84,13 +84,13 @@ public void setUp() throws Exception { // options.put(DefaultCodeFormatterConstants.FORMATTER_INDENTATION_SIZE, "4"); JavaCore.setOptions(options); } - setUpProject(JavaCore.VERSION_1_5); + setUpProject(); } - private void setUpProject(String sourceLevel) throws CoreException, JavaModelException { + private void setUpProject() throws CoreException, JavaModelException { fProject= JavaProjectHelper.createJavaProject(PROJECT, "bin"); JavaProjectHelper.addRTJar(fProject); - fProject.setOption(JavaCore.COMPILER_SOURCE, sourceLevel); + fProject.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); IPackageFragmentRoot fragmentRoot= JavaProjectHelper.addSourceContainer(fProject, SRC); IPackageFragment fragment= fragmentRoot.createPackageFragment("test", true, new NullProgressMonitor()); fCU= fragment.createCompilationUnit(CU_NAME, "", true, new NullProgressMonitor()); diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/BracketInserterTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/BracketInserterTest.java index 12457f35a3b..04208622a65 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/BracketInserterTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/BracketInserterTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -81,14 +81,14 @@ public class BracketInserterTest { private static final String CU_NAME= "PR75423.java"; private static final String CU_CONTENTS= """ package com.example.bugs; - + import java.lang.String; import java.lang.Integer; - + public class PR75423 { String string; Integer integer; - + public static void main(String[] args) { \s } @@ -119,6 +119,8 @@ void foo(String[] args) { public void setUp() throws Exception { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); + setUpProject(JavaCore.VERSION_1_8); + setUpEditor(); } private void setUpProject(String sourceLevel) throws CoreException, JavaModelException { @@ -147,7 +149,7 @@ private JavaEditor openJavaEditor(IPath path) { try { return (JavaEditor)EditorTestHelper.openInEditor(file, true); } catch (PartInitException e) { - fail(); + fail(e.getMessage()); return null; } } @@ -167,8 +169,7 @@ public void tearDown() throws Exception { } @Test - public void testInsertClosingParenthesis() throws BadLocationException, JavaModelException, CoreException, JavaModelException, CoreException { - use14(); + public void testInsertClosingParenthesis() throws BadLocationException { setCaret(BODY_OFFSET); type('('); @@ -177,8 +178,7 @@ public void testInsertClosingParenthesis() throws BadLocationException, JavaMode } @Test - public void testDeletingParenthesis() throws JavaModelException, CoreException { - use14(); + public void testDeletingParenthesis() { setCaret(BODY_OFFSET); type('('); type(SWT.BS); @@ -188,8 +188,7 @@ public void testDeletingParenthesis() throws JavaModelException, CoreException { } @Test - public void testMultipleParenthesisInsertion() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testMultipleParenthesisInsertion() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); @@ -200,8 +199,7 @@ public void testMultipleParenthesisInsertion() throws BadLocationException, Java } @Test - public void testDeletingMultipleParenthesisInertion() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testDeletingMultipleParenthesisInertion() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); @@ -227,8 +225,7 @@ public void testDeletingMultipleParenthesisInertion() throws BadLocationExceptio } @Test - public void testNoInsertInsideText() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testNoInsertInsideText() throws BadLocationException { setCaret(ARGS_OFFSET); type('('); @@ -238,8 +235,7 @@ public void testNoInsertInsideText() throws BadLocationException, JavaModelExcep } @Test - public void testInsertInsideBrackets() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testInsertInsideBrackets() throws BadLocationException { setCaret(BRACKETS_OFFSET); type('('); @@ -248,8 +244,7 @@ public void testInsertInsideBrackets() throws BadLocationException, JavaModelExc } @Test - public void testPeerEntry() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testPeerEntry() throws BadLocationException { setCaret(BODY_OFFSET); type("()"); @@ -259,17 +254,8 @@ public void testPeerEntry() throws BadLocationException, JavaModelException, Cor assertFalse(LinkedModeModel.hasInstalledModel(fDocument)); } -// public void testLoop() throws Exception { -// for (int i= 0; i < 50; i++) { -// setUp(); -// testExitOnTab(); -// tearDown(); -// } -// } -// @Test - public void testMultiplePeerEntry() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testMultiplePeerEntry() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); @@ -293,8 +279,7 @@ public void testMultiplePeerEntry() throws BadLocationException, JavaModelExcept } @Test - public void testExitOnTab() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testExitOnTab() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); linkedType('\t', true, ILinkedModeListener.NONE); @@ -317,8 +302,7 @@ public void testExitOnTab() throws BadLocationException, JavaModelException, Cor } @Test - public void testExitOnReturn() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testExitOnReturn() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); linkedType(SWT.CR, true, ILinkedModeListener.UPDATE_CARET | ILinkedModeListener.EXIT_ALL); @@ -330,8 +314,7 @@ public void testExitOnReturn() throws BadLocationException, JavaModelException, } @Test - public void testExitOnEsc() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testExitOnEsc() throws BadLocationException { setCaret(BODY_OFFSET); type("(((("); linkedType(SWT.ESC, true, ILinkedModeListener.EXIT_ALL); @@ -343,8 +326,7 @@ public void testExitOnEsc() throws BadLocationException, JavaModelException, Cor } @Test - public void testInsertClosingQuote() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testInsertClosingQuote() throws BadLocationException { setCaret(BODY_OFFSET); type('"'); @@ -354,8 +336,7 @@ public void testInsertClosingQuote() throws BadLocationException, JavaModelExcep } @Test - public void testPreferences() throws BadLocationException, JavaModelException, CoreException { - use14(); + public void testPreferences() throws BadLocationException { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.EDITOR_CLOSE_BRACKETS, false); @@ -370,7 +351,6 @@ public void testPreferences() throws BadLocationException, JavaModelException, C @Test public void testAngleBracketsAsOperator() throws Exception { - use15(); setCaret(BODY_OFFSET); type("test<"); @@ -381,23 +361,8 @@ public void testAngleBracketsAsOperator() throws Exception { assertFalse(LinkedModeModel.hasInstalledModel(fDocument)); } - @Test - public void testAngleBracketsIn14Project() throws BadLocationException, JavaModelException, CoreException { - use14(); - setCaret(BODY_OFFSET); - type("Test<"); - - assertEquals("Test<", fDocument.get(BODY_OFFSET, 5)); - assertNotEquals(">", fDocument.get(BODY_OFFSET + 5, 1)); - assertEquals(BODY_OFFSET + 5, getCaret()); - - assertFalse(LinkedModeModel.hasInstalledModel(fDocument)); - } - @Test public void testAngleBracketsIn15Project() throws Exception { - use15(); - setCaret(BODY_OFFSET); type("Test<"); @@ -407,8 +372,6 @@ public void testAngleBracketsIn15Project() throws Exception { @Test public void testAngleBracketsInFieldDecl15() throws Exception { - use15(); - setCaret(FIELD_OFFSET); type('<'); @@ -418,8 +381,6 @@ public void testAngleBracketsInFieldDecl15() throws Exception { @Test public void testAngleBracketsInsideMethodDecl15() throws Exception { - use15(); - setCaret(MAIN_VOID_OFFSET); type('<'); @@ -429,8 +390,6 @@ public void testAngleBracketsInsideMethodDecl15() throws Exception { @Test public void testAngleBracketsBeforeMethodDecl15() throws Exception { - use15(); - setCaret(FOO_VOID_OFFSET); type('<'); @@ -441,8 +400,6 @@ public void testAngleBracketsBeforeMethodDecl15() throws Exception { @Test public void testAngleBracketsBeforeTypeArgument15() throws Exception { - use15(); - String PRE= "new ArrayList"; String POST= "String>();"; @@ -457,8 +414,6 @@ public void testAngleBracketsBeforeTypeArgument15() throws Exception { @Test public void testAngleBracketsBeforeWildcard15() throws Exception { - use15(); - String PRE= "new ArrayList"; String POST= "? extends Number>();"; @@ -474,8 +429,6 @@ public void testAngleBracketsBeforeWildcard15() throws Exception { @Test public void testAngleBracketsAfterIdentifierOnFirstColumn1_15() throws Exception { //https://bugs.eclipse.org/bugs/show_bug.cgi?id=347734 - use15(); - String PRE= "x"; fDocument.replace(FIRST_COLUMN_OFFSET, 0, PRE); @@ -490,8 +443,6 @@ public void testAngleBracketsAfterIdentifierOnFirstColumn1_15() throws Exception @Test public void testAngleBracketsAfterIdentifierOnFirstColumn2_15() throws Exception { //https://bugs.eclipse.org/bugs/show_bug.cgi?id=347734 - use15(); - String PRE= "List"; fDocument.replace(FIRST_COLUMN_OFFSET, 0, PRE); @@ -514,16 +465,6 @@ private void assertSingleLinkedPosition(int offset) { assertEquals(0, position.getLength()); } - private void use15() throws CoreException, JavaModelException { - setUpProject(JavaCore.VERSION_1_5); - setUpEditor(); - } - - private void use14() throws CoreException, JavaModelException { - setUpProject(JavaCore.VERSION_1_4); - setUpEditor(); - } - /** * Type characters into the styled text. * diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaDoubleClickSelectorTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaDoubleClickSelectorTest.java index 96d34c951aa..81ef3acb396 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaDoubleClickSelectorTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaDoubleClickSelectorTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -22,8 +22,6 @@ import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; -import org.eclipse.jdt.core.JavaCore; - import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector; /** @@ -37,150 +35,110 @@ public IRegion findWord(IDocument document, int anchor) { } } - private void assert14Selection(String content, int offset, int selOffset, int selLength) { - IDocument document= new Document(content); - PublicSelector selector= new PublicSelector(); - selector.setSourceVersion(JavaCore.VERSION_1_4); - IRegion selection= selector.findWord(document, offset); - assertEquals(new Region(selOffset, selLength), selection); - } - - private void assert15Selection(String content, int offset, int selOffset, int selLength) { + private void assertSelection(String content, int offset, int selOffset, int selLength) { IDocument document= new Document(content); PublicSelector selector= new PublicSelector(); - selector.setSourceVersion(JavaCore.VERSION_1_5); IRegion selection= selector.findWord(document, offset); assertEquals(new Region(selOffset, selLength), selection); } @Test public void testIdentifierBefore() throws Exception { - assert14Selection(" foobar ", 2, 2, 6); + assertSelection(" foobar ", 2, 2, 6); } @Test public void testIdentifierInside() throws Exception { - assert14Selection(" foobar ", 3, 2, 6); + assertSelection(" foobar ", 3, 2, 6); } @Test public void testIdentifierBehind() throws Exception { - assert14Selection(" foobar ", 8, 8, 0); + assertSelection(" foobar ", 8, 8, 0); } @Test public void testWhitespaceBefore() throws Exception { - assert14Selection(" foobar ", 1, 1, 0); + assertSelection(" foobar ", 1, 1, 7); } @Test public void testWhitespaceBehind() throws Exception { - assert14Selection(" foobar ", 9, 9, 0); - } - - @Test - public void test14AnnotationBefore() throws Exception { - assert14Selection(" @ Deprecated ", 2, 2, 0); - } - - @Test - public void test14AnnotationInside1() throws Exception { - assert14Selection(" @ Deprecated ", 3, 3, 0); - } - - @Test - public void test14AnnotationInside2() throws Exception { - assert14Selection(" @ Deprecated ", 4, 4, 0); - } - - @Test - public void test14AnnotationInside3() throws Exception { - assert14Selection(" @ Deprecated ", 5, 5, 10); - } - - @Test - public void test14AnnotationInside4() throws Exception { - assert14Selection(" @ Deprecated ", 6, 5, 10); - } - - @Test - public void test14AnnotationBehind() throws Exception { - assert14Selection(" @ Deprecated ", 15, 15, 0); + assertSelection(" foobar ", 9, 9, 0); } @Test public void test15AnnotationBefore() throws Exception { - assert15Selection(" @ Deprecated ", 2, 2, 13); + assertSelection(" @ Deprecated ", 2, 2, 13); } @Test public void test15AnnotationInside1() throws Exception { - assert15Selection(" @ Deprecated ", 3, 2, 13); + assertSelection(" @ Deprecated ", 3, 2, 13); } @Test public void test15AnnotationInside2() throws Exception { - assert15Selection(" @ Deprecated ", 4, 2, 13); + assertSelection(" @ Deprecated ", 4, 2, 13); } @Test public void test15AnnotationInside3() throws Exception { - assert15Selection(" @ Deprecated ", 5, 2, 13); + assertSelection(" @ Deprecated ", 5, 2, 13); } @Test public void test15AnnotationInside4() throws Exception { - assert15Selection(" @ Deprecated ", 6, 2, 13); + assertSelection(" @ Deprecated ", 6, 2, 13); } @Test public void test15AnnotationBehind() throws Exception { - assert15Selection(" @ Deprecated ", 15, 15, 0); + assertSelection(" @ Deprecated ", 15, 15, 0); } @Test public void test15AnnotationNoSpaceBefore() throws Exception { - assert15Selection(" @Deprecated ", 2, 2, 11); + assertSelection(" @Deprecated ", 2, 2, 11); } @Test public void test15AnnotationNoSpaceInside1() throws Exception { - assert15Selection(" @Deprecated ", 3, 2, 11); + assertSelection(" @Deprecated ", 3, 2, 11); } @Test public void test15AnnotationNoSpaceInside2() throws Exception { - assert15Selection(" @Deprecated ", 4, 2, 11); + assertSelection(" @Deprecated ", 4, 2, 11); } @Test public void test15AnnotationNoSpaceBehind() throws Exception { - assert15Selection(" @Deprecated ", 13, 13, 0); + assertSelection(" @Deprecated ", 13, 13, 0); } @Test public void testAnnotationNoIdStartBefore() { - assert15Selection(" @2foobar ", 2, 2, 0); + assertSelection(" @2foobar ", 2, 2, 0); } @Test public void testAnnotationNoIdStartInside1() { - assert15Selection(" @2foobar ", 3, 3, 7); + assertSelection(" @2foobar ", 3, 3, 7); } @Test public void testAnnotationNoIdStartInside2() { - assert15Selection(" @2foobar ", 4, 3, 7); + assertSelection(" @2foobar ", 4, 3, 7); } @Test public void testAnnotationNoIdStartBehind() { - assert15Selection(" @2foobar ", 10, 10, 0); + assertSelection(" @2foobar ", 10, 10, 0); } @Test public void testBackwardsOnDot() { - assert14Selection("Systen.out", 6, 0, 6); - assert15Selection("Systen.out", 6, 0, 6); + assertSelection("Systen.out", 6, 0, 6); } } diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaModelOpCompundUndoTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaModelOpCompundUndoTest.java index 127f80a60e4..a24c894c274 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaModelOpCompundUndoTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaModelOpCompundUndoTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2009 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -74,9 +74,9 @@ public class JavaModelOpCompundUndoTest { private static final String CU_NAME= "Bug75423.java"; private static final String CU_CONTENTS= """ package com.example.bugs; - + public class Bug75423 { - + void foo() { \s } @@ -94,9 +94,9 @@ void bar() { private ICompilationUnit fCompilationUnit; private IUndoManager fUndoManager; - private void setUpProject(String sourceLevel) throws CoreException, JavaModelException { + private void setUpProject() throws CoreException, JavaModelException { fProject= JavaProjectHelper.createJavaProject(tn.getMethodName(), "bin"); - fProject.setOption(JavaCore.COMPILER_SOURCE, sourceLevel); + fProject.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); JavaProjectHelper.addSourceContainer(fProject, SRC); IPackageFragment fragment= fProject.findPackageFragment(new Path(SEP + tn.getMethodName() + SEP + SRC)); fCompilationUnit= fragment.createCompilationUnit(CU_NAME, CU_CONTENTS, true, new NullProgressMonitor()); @@ -104,7 +104,7 @@ private void setUpProject(String sourceLevel) throws CoreException, JavaModelExc @Before public void setUp() throws Exception { - setUpProject(JavaCore.VERSION_1_5); + setUpProject(); setUpEditor(); } @@ -161,9 +161,6 @@ public void test1() throws Exception { @Test public void test2() throws Exception { - setUpProject(JavaCore.VERSION_1_5); - setUpEditor(); - assertEquals(CU_CONTENTS, fDocument.get()); fUndoManager.beginCompoundChange(); diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaPairMatcherTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaPairMatcherTest.java index d6add473bef..af11c98d5aa 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaPairMatcherTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JavaPairMatcherTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -14,9 +14,12 @@ *******************************************************************************/ package org.eclipse.jdt.text.tests; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import org.junit.After; import org.junit.Before; -import static org.junit.Assert.*; +import org.junit.Test; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; @@ -25,8 +28,6 @@ import org.eclipse.jface.text.source.ICharacterPairMatcher; import org.eclipse.jface.text.tests.AbstractPairMatcherTest; -import org.eclipse.jdt.core.JavaCore; - import org.eclipse.jdt.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner; @@ -81,6 +82,7 @@ public void tearDown () { fPairMatcher= null; } + @Test public void testBeforeOpeningMatch() { IRegion match= fPairMatcher.match(fDocument, 2); assertNotNull(match); @@ -91,6 +93,7 @@ public void testBeforeOpeningMatch() { assertTrue(match.getOffset() == 5 && match.getLength() == 4); } + @Test public void testAfterOpeningMatch() { IRegion match= fPairMatcher.match(fDocument, 3); assertNotNull(match); @@ -100,7 +103,7 @@ public void testAfterOpeningMatch() { assertNotNull(match); assertTrue(match.getOffset() == 5 && match.getLength() == 4); } - + @Test public void testBeforeClosingMatch() { IRegion match= fPairMatcher.match(fDocument, 11); assertNotNull(match); @@ -111,7 +114,7 @@ public void testBeforeClosingMatch() { assertTrue(match.getOffset() == 5 && match.getLength() == 4); } - + @Test public void testAfterClosingMatch() { IRegion match= fPairMatcher.match(fDocument, 12); assertNotNull(match); @@ -121,35 +124,35 @@ public void testAfterClosingMatch() { assertNotNull(match); assertTrue(match.getOffset() == 5 && match.getLength() == 4); } - + @Test public void testBeforeClosingMatchWithNL() { fDocument.set("x(y\ny)x"); IRegion match= fPairMatcher.match(fDocument, 5); assertNotNull(match); assertTrue(match.getOffset() == 1 && match.getLength() == 5); } - + @Test public void testAfterClosingMatchWithNL() { fDocument.set("x(y\ny)x"); IRegion match= fPairMatcher.match(fDocument, 6); assertNotNull(match); assertTrue(match.getOffset() == 1 && match.getLength() == 5); } - + @Test public void testBeforeClosingMatchWithNLAndSingleLineComment() { fDocument.set("x\nx(y\nx //(x\ny)x"); IRegion match= fPairMatcher.match(fDocument, 14); assertNotNull(match); assertTrue(match.getOffset() == 3 && match.getLength() == 12); } - + @Test public void testAfterClosingMatchWithNLAndSingleLineComment() { fDocument.set("x\nx(y\nx //(x\ny)x"); IRegion match= fPairMatcher.match(fDocument, 15); assertNotNull(match); assertTrue(match.getOffset() == 3 && match.getLength() == 12); } - + @Test public void testEnclosingMatch() { IRegion match= fPairMatcher.findEnclosingPeerCharacters(fDocument, 4, 0); assertNotNull(match); @@ -159,25 +162,9 @@ public void testEnclosingMatch() { assertNotNull(match); assertTrue(match.getOffset() == 5 && match.getLength() == 4); } - - public void testAngleBrackets1_4() { - final JavaPairMatcher matcher= (JavaPairMatcher) createMatcher("(){}[]<>"); - matcher.setSourceVersion(JavaCore.VERSION_1_4); - performMatch(matcher, " <>% "); - performMatch(matcher, " <%> "); - performMatch(matcher, " 2 < 3 || 4 >% 5 "); - performMatch(matcher, " 2 <% 3 || 4 > 5 "); - performMatch(matcher, " List% "); - performMatch(matcher, " foo < T >% "); - performMatch(matcher, " foo <% T > "); - performMatch(matcher, " foo < T >% "); - performMatch(matcher, " final <% T > "); - matcher.dispose(); - } - + @Test public void testAngleBrackets1_5() { final JavaPairMatcher matcher= (JavaPairMatcher) createMatcher("(){}[]<>"); - matcher.setSourceVersion(JavaCore.VERSION_1_5); performMatch(matcher, " #< %> "); performMatch(matcher, " <%># "); performMatch(matcher, " 2 < 3 || 4 >% 5 "); @@ -189,7 +176,7 @@ public void testAngleBrackets1_5() { performMatch(matcher, " final <% T ># "); matcher.dispose(); } - + @Test public void testBug209505() { fDocument.set("(xny)/* */"); IRegion match= fPairMatcher.match(fDocument, 4); diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java index 8f02b18f676..96bb66735d3 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/JdtTextTestSuite.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -20,6 +20,7 @@ import org.eclipse.jdt.text.tests.codemining.CodeMiningTriggerTest; import org.eclipse.jdt.text.tests.codemining.ParameterNamesCodeMiningTest; import org.eclipse.jdt.text.tests.contentassist.ContentAssistTestSuite; +import org.eclipse.jdt.text.tests.semantictokens.SemanticTokensProviderTest; import org.eclipse.jdt.text.tests.spelling.SpellCheckEngineTestCase; import org.eclipse.jdt.text.tests.templates.TemplatesTestSuite; @@ -52,6 +53,7 @@ BracketInserterTest.class, SpellCheckEngineTestCase.class, SemanticHighlightingTest.class, + SemanticTokensProviderTest.class, AutoboxingSemanticHighlightingTest.class, Java23SemanticHighlightingTest.class, NewForLoopJavaContextTest.class, diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/codemining/ParameterNamesCodeMiningTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/codemining/ParameterNamesCodeMiningTest.java index 26326152458..ad06b5a681c 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/codemining/ParameterNamesCodeMiningTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/codemining/ParameterNamesCodeMiningTest.java @@ -19,6 +19,7 @@ import java.util.Arrays; import java.util.Map; +import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.LongSupplier; @@ -46,6 +47,7 @@ import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.intro.IIntroManager; import org.eclipse.ui.intro.IIntroPart; @@ -54,6 +56,7 @@ import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; +import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.PreferenceConstants; @@ -380,6 +383,37 @@ public void testBug549126() throws Exception { assertEquals(2, fParameterNameCodeMiningProvider.provideCodeMinings(viewer, new NullProgressMonitor()).get().size()); } + @Test + public void testRecordConstructorOneParameterPreferenceFalse() throws Exception { + assertParameterNamesShown(false, 0); + } + + @Test + public void testRecordConstructorOneParameterPreferenceTrue() throws Exception { + assertParameterNamesShown(true, 1); + } + + private void assertParameterNamesShown(boolean preferenceValue, int expectedShownNames) throws JavaModelException, PartInitException, InterruptedException, ExecutionException { + PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG, preferenceValue); + String contents= """ + public class Ant { + record Ca (int size){ + + } + + Ca c = new Ca(0); + + } + """; + ICompilationUnit compilationUnit= fPackage.createCompilationUnit("Ant.java", contents, true, new NullProgressMonitor()); + JavaEditor editor= (JavaEditor) EditorUtility.openInEditor(compilationUnit); + fParameterNameCodeMiningProvider.setContext(editor); + JavaSourceViewer viewer= (JavaSourceViewer)editor.getViewer(); + waitReconciled(viewer); + + assertEquals(expectedShownNames, fParameterNameCodeMiningProvider.provideCodeMinings(viewer, new NullProgressMonitor()).get().size()); + } + @Test public void testRecordConstructorOK() throws Exception { String contents= "import java.util.Map;\n" diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContinuousTypingCompletionTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContinuousTypingCompletionTest.java index 4f80505889a..10e2a70927f 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContinuousTypingCompletionTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/contentassist/ContinuousTypingCompletionTest.java @@ -39,11 +39,13 @@ public class ContinuousTypingCompletionTest extends AbstractCompletionTest { private final static class CompletionSelectionTracker implements ICompletionListener { - private ICompletionProposal fSelectedProposal; + private AbstractJavaCompletionProposal fSelectedProposal; @Override public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) { - this.fSelectedProposal= proposal; + if (proposal instanceof AbstractJavaCompletionProposal p) { + this.setSelectedProposal(p); + } } @Override @@ -56,8 +58,12 @@ public void assistSessionEnded(ContentAssistEvent event) { // not used } - public AbstractJavaCompletionProposal getSelectedProposal() { - return (AbstractJavaCompletionProposal) this.fSelectedProposal; + public synchronized AbstractJavaCompletionProposal getSelectedProposal() { + return this.fSelectedProposal; + } + + public synchronized void setSelectedProposal(AbstractJavaCompletionProposal selectedProposal) { + fSelectedProposal = selectedProposal; } } @@ -84,11 +90,23 @@ public void testContinousTypingSelectsTopProposal() throws Exception { CompletionSelectionTracker selectionTracker= new CompletionSelectionTracker(); ((JavaSourceViewer) fEditor.getViewer()).getContentAssistantFacade().addCompletionListener(selectionTracker); fEditor.getAction(ITextEditorActionConstants.CONTENT_ASSIST).run(); + new DisplayHelper() { + @Override + public boolean condition() { + return selectionTracker.getSelectedProposal()!=null; + } + }.waitForCondition(display, 10000); assertEquals("ab", selectionTracker.getSelectedProposal().getJavaElement().getElementName()); IDocument document= fEditor.getViewer().getDocument(); document.replace(completionOffset, 0, "b"); + selectionTracker.setSelectedProposal(null); fEditor.getViewer().setSelectedRange(completionOffset + 1, 0); - DisplayHelper.sleep(display, 500); + new DisplayHelper() { + @Override + public boolean condition() { + return selectionTracker.getSelectedProposal()!=null; + } + }.waitForCondition(display, 10000); assertEquals("ba", selectionTracker.getSelectedProposal().getJavaElement().getElementName()); } diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SampleSqlSemanticTokensProvider.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SampleSqlSemanticTokensProvider.java new file mode 100644 index 00000000000..2f976dd568b --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SampleSqlSemanticTokensProvider.java @@ -0,0 +1,137 @@ +/******************************************************************************* + * Copyright (c) 2024 Broadcom Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Alex Boyko (Broadcom Inc.) - Initial implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests.semantictokens; + +import java.text.NumberFormat; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.eclipse.jdt.core.dom.ASTVisitor; +import org.eclipse.jdt.core.dom.CompilationUnit; +import org.eclipse.jdt.core.dom.Expression; +import org.eclipse.jdt.core.dom.StringLiteral; +import org.eclipse.jdt.core.dom.TextBlock; + +import org.eclipse.jdt.ui.text.java.ISemanticTokensProvider; + +/** + * Semantic tokens are computed for string literals or text blocks starting with "SQL:" prefix. + *
    + *
  • SELECT, WHERE, IN, FROM are KEYWORD
  • + *
  • *, <, >, ==, != etc are OPEARATOR
  • + *
  • Words starting from capital are CLASS
  • + *
  • Numbers are NUMBER
  • + *
  • all other lower case starting words are LOCAL_VARIABLE
  • + *
+ */ +public class SampleSqlSemanticTokensProvider implements ISemanticTokensProvider { + + private static final String SQL_PREFIX = "SQL:"; + + @Override + public Collection computeSemanticTokens(CompilationUnit ast) { + List tokens = new ArrayList<>(); + ast.accept(new ASTVisitor() { + + @Override + public boolean visit(StringLiteral node) { + tokens.addAll(reconileEmbeddedExpression(node)); + return super.visit(node); + } + + @Override + public boolean visit(TextBlock node) { + tokens.addAll(reconileEmbeddedExpression(node)); + return super.visit(node); + } + + }); + return tokens; + } + + private List reconileEmbeddedExpression(Expression valueExp) { + String text = null; + int offset = 0; + if (valueExp instanceof StringLiteral sl && sl.getLiteralValue().startsWith(SQL_PREFIX)) { + text = sl.getEscapedValue(); + int skip = 1 + SQL_PREFIX.length(); + text = text.substring(skip, text.length() - 1); + offset = sl.getStartPosition() + skip; // +1 to skip over opening " and over "SQL:" + } else if (valueExp instanceof TextBlock tb && tb.getLiteralValue().startsWith(SQL_PREFIX)) { + text = tb.getEscapedValue(); + int skip = 3 + SQL_PREFIX.length(); + text = text.substring(skip, text.length() - 3); + offset = tb.getStartPosition() + skip; // +3 to skip over opening """ and over "SQL:" + } + return compute(text, offset); + } + + private List compute(String text, int offset) { + if (text == null) { + return Collections.emptyList(); + } + List tokens = new ArrayList<>(); + Matcher matcher= Pattern.compile("[\\w*=>": + case "<": + case ">=": + case "<=": + case "==": + case "!=": + return TokenType.OPERATOR; + default: + if (token.length() > 0 && Character.isUpperCase(token.charAt(0))) { + return TokenType.CLASS; + } + return TokenType.LOCAL_VARIABLE; + } + } + } + + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SemanticTokensProviderTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SemanticTokensProviderTest.java new file mode 100644 index 00000000000..3e3d0740178 --- /dev/null +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/semantictokens/SemanticTokensProviderTest.java @@ -0,0 +1,50 @@ +/******************************************************************************* + * Copyright (c) 2024 Broadcom Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Alex Boyko (Broadcom Inc.) - Initial implementation + *******************************************************************************/ +package org.eclipse.jdt.text.tests.semantictokens; + +import org.junit.Rule; +import org.junit.Test; + +import org.eclipse.jdt.text.tests.AbstractSemanticHighlightingTest; + +import org.eclipse.jface.text.Position; + +import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightings; + +public class SemanticTokensProviderTest extends AbstractSemanticHighlightingTest { + + @Rule + public SemanticHighlightingTestSetup shts= new SemanticHighlightingTestSetup( "/SHTest/src/STTest.java"); + + @Test + public void contributedHighlighting() throws Exception { + setUpSemanticHighlighting(SemanticHighlightings.CLASS); + setUpSemanticHighlighting(SemanticHighlightings.NUMBER); + setUpSemanticHighlighting(SemanticHighlightings.LOCAL_VARIABLE); + Position[] actual= getSemanticHighlightingPositions(); + Position[] expected= new Position[] { + createPosition(0, 6, 1), + createPosition(1, 1, 6), + createPosition(1, 20, 6), + createPosition(1, 27, 1), + createPosition(1, 29, 4), + createPosition(1, 34, 1), + createPosition(1, 36, 5), + createPosition(1, 42, 1), + createPosition(1, 44, 2), + createPosition(1, 47, 3), + }; + assertEqualPositions(expected, actual); + } + + +} diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/spelling/SpellCheckEngineTestCase.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/spelling/SpellCheckEngineTestCase.java index 7f2aea74b76..08d4bc8532a 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/spelling/SpellCheckEngineTestCase.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/spelling/SpellCheckEngineTestCase.java @@ -13,10 +13,10 @@ *******************************************************************************/ package org.eclipse.jdt.text.tests.spelling; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.net.MalformedURLException; import java.net.URL; @@ -25,9 +25,9 @@ import java.util.Locale; import java.util.Set; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jface.preference.IPreferenceStore; @@ -83,7 +83,7 @@ protected final boolean contains(Set words, String word) { return false; } - @Before + @BeforeEach public void setUp() throws Exception { fUSDictionary.addWord(TRUCK); @@ -97,7 +97,7 @@ public void setUp() throws Exception { fEngine.registerGlobalDictionary(fGlobalDictionary); } - @After + @AfterEach public void tearDown() throws Exception { fUSDictionary.unload(); diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateCompletionTests.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateCompletionTests.java index cafb90b4d60..410a9c69cd9 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateCompletionTests.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateCompletionTests.java @@ -12,16 +12,16 @@ *******************************************************************************/ package org.eclipse.jdt.text.tests.templates; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -54,7 +54,7 @@ public class TemplateCompletionTests { private IPackageFragment pkg; - @Before + @BeforeEach public void setUp() throws Exception { fJProject= JavaProjectHelper.createJavaProject("TestProject", "bin"); JavaProjectHelper.addRTJar18(fJProject); @@ -62,7 +62,7 @@ public void setUp() throws Exception { pkg= javaSrc.createPackageFragment("test", false, null); } - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject); } @@ -102,7 +102,7 @@ public void testExepectNoProposals() throws Exception { List proposals= computeCompletionProposals(cu, completionIndex); boolean fail= proposals.stream().anyMatch(p -> "new_class - create new class".equals(p.getDisplayString())); - assertFalse("Proposal '" + propDisplay + "' should not exist", fail); + assertFalse(fail, "Proposal '" + propDisplay + "' should not exist"); } @Test diff --git a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateContributionTest.java b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateContributionTest.java index 499eccae24c..a005d4da48d 100644 --- a/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateContributionTest.java +++ b/org.eclipse.jdt.text.tests/src/org/eclipse/jdt/text/tests/templates/TemplateContributionTest.java @@ -17,7 +17,7 @@ import java.util.Iterator; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jface.text.templates.ContextTypeRegistry; import org.eclipse.jface.text.templates.Template; diff --git a/org.eclipse.jdt.text.tests/testResources/semanticHighlightingTest1/STTest.java b/org.eclipse.jdt.text.tests/testResources/semanticHighlightingTest1/STTest.java new file mode 100644 index 00000000000..c62403820c3 --- /dev/null +++ b/org.eclipse.jdt.text.tests/testResources/semanticHighlightingTest1/STTest.java @@ -0,0 +1,3 @@ +class A { + String sql = "SQL: SELECT * FROM T WHERE a == 567"; +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF b/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF index a24eba260ed..2efd1cf0d36 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ui.tests.refactoring/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.ui.tests.refactoring Bundle-ManifestVersion: 2 Bundle-Name: %Plugin.name Bundle-SymbolicName: org.eclipse.jdt.ui.tests.refactoring; singleton:=true -Bundle-Version: 3.15.700.qualifier +Bundle-Version: 3.15.800.qualifier Bundle-Activator: org.eclipse.jdt.ui.tests.refactoring.infra.RefactoringTestPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %Plugin.providerName diff --git a/org.eclipse.jdt.ui.tests.refactoring/pom.xml b/org.eclipse.jdt.ui.tests.refactoring/pom.xml index ea744d4d55d..d1e37608421 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/pom.xml +++ b/org.eclipse.jdt.ui.tests.refactoring/pom.xml @@ -19,11 +19,11 @@ org.eclipse.jdt org.eclipse.jdt.ui.tests.refactoring - 3.15.700-SNAPSHOT + 3.15.800-SNAPSHOT eclipse-test-plugin ${project.artifactId} - org.eclipse.jdt.ui.tests.refactoring.all.AllAllRefactoringTests + org.eclipse.jdt.ui.tests.refactoring.all.AllRefactoringTestsSuite diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/cannotModify/A_testFailIssue1750.java b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/cannotModify/A_testFailIssue1750.java new file mode 100644 index 00000000000..e003f63ecec --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/cannotModify/A_testFailIssue1750.java @@ -0,0 +1,16 @@ +package p; + +class A_testFailIssue1750 { + public void k(Number x) { + } + // change method signature 'm' to 'k' + public void m(Long x) { + } + + class B { + void foo() { + long i = 1; + k(i); + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_in/TestQualifiedAnonymousReceiver.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_in/TestQualifiedAnonymousReceiver.java new file mode 100644 index 00000000000..258c9d748f1 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_in/TestQualifiedAnonymousReceiver.java @@ -0,0 +1,22 @@ +package receiver_in; + +public class TestQualifiedAnonymousReceiver { + int x = 10; + + void superClassMethod() { + System.out.println(x); + } + + static void callingMethod(TestQualifiedAnonymousReceiver instance) { + /*]*/instance.methodToBeInlined();/*[*/ + } + + void methodToBeInlined() { + int k = 0; + new Object() { + void execute() { + TestQualifiedAnonymousReceiver.this.superClassMethod(); + } + }.execute(); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_out/TestQualifiedAnonymousReceiver.java b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_out/TestQualifiedAnonymousReceiver.java new file mode 100644 index 00000000000..f2f64ae3108 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_out/TestQualifiedAnonymousReceiver.java @@ -0,0 +1,27 @@ +package receiver_out; + +public class TestQualifiedAnonymousReceiver { + int x = 10; + + void superClassMethod() { + System.out.println(x); + } + + static void callingMethod(TestQualifiedAnonymousReceiver instance) { + /*]*/int k = 0; + new Object() { + void execute() { + instance.superClassMethod(); + } + }.execute();/*[*/ + } + + void methodToBeInlined() { + int k = 0; + new Object() { + void execute() { + TestQualifiedAnonymousReceiver.this.superClassMethod(); + } + }.execute(); + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail36/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail36/in/A.java new file mode 100644 index 00000000000..b099bf3b832 --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail36/in/A.java @@ -0,0 +1,24 @@ +package p; + +public class A { + public class BaseTargetClass {} + + public class OriginalClass { + public int data = 60; + public void memberMethod() {} + + public class NestedOriginalClass extends BaseTargetClass { + void setup() { + new BaseTargetClass() { + void method() { + methodHelper(); + } + + void methodHelper() { + System.out.println("Helper Method in Anonymous Class: " + data); + } + }; + } + } + } +} diff --git a/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail37/in/A.java b/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail37/in/A.java new file mode 100644 index 00000000000..9723ddbfaae --- /dev/null +++ b/org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail37/in/A.java @@ -0,0 +1,24 @@ +package p; + +public class A { + public class BaseInner { + void innerMethodLambda(Outer outer) { + Runnable r = () -> { + System.out.println(outer.x); + outer.foo(); + }; + r.run(); + } + } + + public class Outer { + public int x = 0; + public void foo(){}; + + public class Inner extends BaseInner { + void innerMethod() { // Pull this method up to class BaseInner + innerMethodLambda(Outer.this); + } + } + } +} \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java index ffc8edf4513..063c1bfaf28 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java @@ -607,6 +607,12 @@ public void testFail1() throws Exception{ helperFail(new String[0], new String[0], RefactoringStatus.FATAL); } + @Test + public void testFailIssue1750() throws Exception { + String[] signature= {"QLong;"}; + helperRenameMethodFail(signature, "k", RefactoringStatus.ERROR, false, true, "A_testFailIssue1750"); + } + @Test public void testFailIssue1751() throws Exception { String[] signature= {}; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java index f8dcdede751..0b859a2a073 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java @@ -955,6 +955,11 @@ public void testExplicitThisMethodReceiver() throws Exception { performReceiverTest(); } + @Test + public void testQualifiedAnonymousReceiver() throws Exception { + performReceiverTest(); + } + @Test public void testThisReceiver() throws Exception { performReceiverTestInlineMethod(); diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java index 2da48de7d33..43dce80462b 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java @@ -1862,6 +1862,48 @@ public void testFail35() throws Exception { helper2(new String[] { "method" }, new String[][] { new String[0] }, true, false, 0); } + @Test + public void testFail36() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IJavaElement element= cu.getElementAt(322); + assertTrue("element is method", element instanceof IMethod); + IMethod[] methods= new IMethod[] { (IMethod)element }; + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + FussyProgressMonitor testMonitor= new FussyProgressMonitor(); + assertTrue("activation", ref.checkInitialConditions(testMonitor).isOK()); + testMonitor.assertUsedUp(); + testMonitor.prepare(); + setTargetClass(processor, 0); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(testMonitor); + testMonitor.assertUsedUp(); + testMonitor.prepare(); + assertFalse("precondition was supposed to fail", checkInputResult.isOK()); + } + @Test + public void testFail37() throws Exception { + ICompilationUnit cu= createCUfromTestFile(getPackageP(), "A"); + IJavaElement element= cu.getElementAt(409); + assertTrue("element is method", element instanceof IMethod); + IMethod[] methods= new IMethod[] { (IMethod)element }; + + PullUpRefactoringProcessor processor= createRefactoringProcessor(methods); + Refactoring ref= processor.getRefactoring(); + + FussyProgressMonitor testMonitor= new FussyProgressMonitor(); + assertTrue("activation", ref.checkInitialConditions(testMonitor).isOK()); + testMonitor.assertUsedUp(); + testMonitor.prepare(); + setTargetClass(processor, 0); + + RefactoringStatus checkInputResult= ref.checkFinalConditions(testMonitor); + testMonitor.assertUsedUp(); + testMonitor.prepare(); + assertFalse("precondition was supposed to fail", checkInputResult.isOK()); + } //---------------------------------------------------------- @Test public void testField0() throws Exception { diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSuite.java similarity index 96% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSuite.java index 708c4a6c071..206a7bb7c99 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTestSuite.java @@ -29,5 +29,5 @@ SurroundWithTests16.class, SurroundWithResourcesTests1d8.class, }) -public class AllTests { +public class RefactoringTestSuite { } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java index a86c3cd784e..df2c40f8274 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java @@ -299,7 +299,7 @@ public void testIllegalTypeName8() throws Exception { @Test public void testIllegalTypeName9() throws Exception { - if (Platform.OS_WIN32.equals(Platform.getOS())) + if (Platform.OS.isWindows()) helper1_0("A", "aux"); } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/RefactoringActionsTestSuite.java similarity index 95% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/RefactoringActionsTestSuite.java index 3089874537f..a98617b3cd1 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/actions/RefactoringActionsTestSuite.java @@ -21,7 +21,7 @@ StructureSelectionActionTests.class, GoToNextPreviousMemberActionTests.class }) -public class AllTests { +public class RefactoringActionsTestSuite { } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringTestsSuite.java similarity index 60% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringTestsSuite.java index 1ea15a794a1..e2d304cfe67 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllAllRefactoringTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/all/AllRefactoringTestsSuite.java @@ -18,14 +18,14 @@ @Suite @SelectClasses({ - org.eclipse.jdt.ui.tests.refactoring.actions.AllTests.class, + org.eclipse.jdt.ui.tests.refactoring.actions.RefactoringActionsTestSuite.class, org.eclipse.jdt.ui.tests.refactoring.nls.NLSTestSuite.class, - org.eclipse.jdt.ui.tests.refactoring.AllTests.class, - org.eclipse.jdt.ui.tests.refactoring.extensions.AllTests.class, - org.eclipse.jdt.ui.tests.refactoring.changes.AllTests.class, - org.eclipse.jdt.ui.tests.refactoring.ccp.AllTests.class, - org.eclipse.jdt.ui.tests.refactoring.typeconstraints.AllTests.class + org.eclipse.jdt.ui.tests.refactoring.RefactoringTestSuite.class, + org.eclipse.jdt.ui.tests.refactoring.extensions.RefactoringExtensionPointTestSuite.class, + org.eclipse.jdt.ui.tests.refactoring.changes.RefactoringChangesTestSuite.class, + org.eclipse.jdt.ui.tests.refactoring.ccp.RefactoringCCPTestSuite.class, + org.eclipse.jdt.ui.tests.refactoring.typeconstraints.RefactoringTypeContraintTestSuite.class }) -public class AllAllRefactoringTests { +public class AllRefactoringTestsSuite { } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/RefactoringCCPTestSuite.java similarity index 95% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/RefactoringCCPTestSuite.java index 2f2860662c9..89d2226197d 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/ccp/RefactoringCCPTestSuite.java @@ -27,5 +27,5 @@ //------old reorg tests CopyResourcesToClipboardActionTest.class }) -public class AllTests { +public class RefactoringCCPTestSuite { } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/RefactoringChangesTestSuite.java similarity index 94% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/RefactoringChangesTestSuite.java index 7e23904d442..7e49a9e3412 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/RefactoringChangesTestSuite.java @@ -21,5 +21,5 @@ TrackPositionTest.class, TextDiffContentTest.class }) -public class AllTests { +public class RefactoringChangesTestSuite { } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java index 5d7e982b37e..d7b9b7f7ab7 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TextDiffContentTest.java @@ -15,10 +15,10 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.changes; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; @@ -72,7 +72,7 @@ public class TextDiffContentTest { private TextEditChangeGroup fChange3; - @Before + @BeforeEach public void setUp() throws Exception { fDocument = new Document(MODIFIED_SOURCE_CONTENTS); fDocumentChange = new DocumentChange("Changes to document", fDocument); diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java index 96bb6871f6c..eb2ec6c6e20 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/changes/TrackPositionTest.java @@ -13,12 +13,12 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.changes; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.core.runtime.NullProgressMonitor; @@ -39,7 +39,7 @@ public class TrackPositionTest { private IDocument fDocument; private DocumentChange fChange; - @Before + @BeforeEach public void setUp() throws Exception { fDocument= new Document("0123456789"); fChange= new DocumentChange(NN, fDocument); @@ -47,7 +47,7 @@ public void setUp() throws Exception { fChange.initializeValidationData(new NullProgressMonitor()); } - @After + @AfterEach public void tearDown() throws Exception { fChange= null; } @@ -65,8 +65,8 @@ public void test2() throws Exception { TextEdit edit= new ReplaceEdit(5, 3, "xy"); TextChangeCompatibility.addTextEdit(fChange, NN, edit); IDocument preview= fChange.getPreviewDocument(new NullProgressMonitor()); - Assert.assertEquals("0123456789", fDocument.get()); - Assert.assertEquals("01234xy89", preview.get()); + Assertions.assertEquals("0123456789", fDocument.get()); + Assertions.assertEquals("01234xy89", preview.get()); assertEquals(fChange.getPreviewEdit(edit).getRegion(), 5, 2); } @@ -80,7 +80,7 @@ private void executeChange() throws Exception { } private static void assertEquals(IRegion r, int offset, int length) { - Assert.assertEquals("Offset", offset, r.getOffset()); - Assert.assertEquals("Length", length, r.getLength()); + Assertions.assertEquals(offset, r.getOffset(), "Offset"); + Assertions.assertEquals(length, r.getLength(), "Length"); } } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/RefactoringExtensionPointTestSuite.java similarity index 93% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/RefactoringExtensionPointTestSuite.java index 4886e23c676..558d295cae9 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/extensions/RefactoringExtensionPointTestSuite.java @@ -20,5 +20,5 @@ @SelectClasses({ ExtensionPointTests.class }) -public class AllTests { +public class RefactoringExtensionPointTestSuite { } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java deleted file mode 100644 index eae4f668a7d..00000000000 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/infra/AbstractRefactoringTestSetup.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. - * - * This program and the accompanying materials - * are made available under the terms of the Eclipse Public License 2.0 - * which accompanies this distribution, and is available at - * https://www.eclipse.org/legal/epl-2.0/ - * - * SPDX-License-Identifier: EPL-2.0 - * - * Contributors: - * IBM Corporation - initial API and implementation - *******************************************************************************/ -package org.eclipse.jdt.ui.tests.refactoring.infra; - -import java.util.Hashtable; - -import junit.extensions.TestSetup; -import junit.framework.Test; - -import org.eclipse.jdt.testplugin.TestOptions; - -import org.eclipse.jdt.core.JavaCore; -import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; - -import org.eclipse.jdt.internal.core.manipulation.CodeTemplateContextType; -import org.eclipse.jdt.internal.core.manipulation.StubUtility; - -import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.util.CoreUtility; - - -public class AbstractRefactoringTestSetup extends TestSetup { - - private boolean fWasAutobuild; - - public AbstractRefactoringTestSetup(Test test) { - super(test); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - fWasAutobuild= CoreUtility.setAutoBuilding(false); - if (JavaPlugin.getActivePage() != null) - JavaPlugin.getActivePage().close(); - - Hashtable options= TestOptions.getDefaultOptions(); - options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, JavaCore.TAB); - options.put(DefaultCodeFormatterConstants.FORMATTER_NUMBER_OF_EMPTY_LINES_TO_PRESERVE, "0"); - options.put(DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, "4"); - options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, String.valueOf(9999)); - - JavaCore.setOptions(options); - TestOptions.initializeCodeGenerationOptions(); - JavaPlugin.getDefault().getCodeTemplateStore().load(); - - String str= """ - /** - * ${tags} - */"""; - StubUtility.setCodeTemplate(CodeTemplateContextType.CONSTRUCTORCOMMENT_ID, str, null); - } - - @Override - protected void tearDown() throws Exception { - CoreUtility.setAutoBuilding(fWasAutobuild); - /* - * ensure the workbench state gets saved when running with the Automated Testing Framework - * TODO: remove when https://bugs.eclipse.org/bugs/show_bug.cgi?id=71362 is fixed - */ - /* Not needed for JDT/UI tests right now. - StackTraceElement[] elements= new Throwable().getStackTrace(); - for (int i= 0; i < elements.length; i++) { - StackTraceElement element= elements[i]; - if (element.getClassName().equals("org.eclipse.test.EclipseTestRunner")) { - PlatformUI.getWorkbench().close(); - break; - } - } - */ - super.tearDown(); - } -} diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java index a04b2557199..1a1ae8a362c 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/CellEditorTester.java @@ -13,9 +13,9 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.internal.ui.refactoring.nls.MultiStateCellEditor; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java index 16abe0f51d9..6b101da5ada 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSElementTester.java @@ -13,13 +13,13 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; @@ -28,7 +28,7 @@ public class NLSElementTester{ private int fOff, fLen; private String fVal; - @Before + @BeforeEach public void setUp(){ fOff= 3; fLen= 5; @@ -38,40 +38,40 @@ public void setUp(){ @Test public void test0() { - assertEquals("Position offset", fOff, fEl.getPosition().getOffset()); //$NON-NLS-1$ + assertEquals(fOff, fEl.getPosition().getOffset(), "Position offset"); //$NON-NLS-1$ } @Test public void test1() { - assertEquals("Position length", fLen, fEl.getPosition().getLength()); //$NON-NLS-1$ + assertEquals(fLen, fEl.getPosition().getLength(), "Position length"); //$NON-NLS-1$ } @Test public void test2() { - assertEquals("value", fVal, fEl.getValue()); //$NON-NLS-1$ + assertEquals(fVal, fEl.getValue(), "value"); //$NON-NLS-1$ } @Test public void test3() { - assertNull("tagposition", fEl.getTagPosition()); //$NON-NLS-1$ + assertNull(fEl.getTagPosition(), "tagposition"); //$NON-NLS-1$ } @Test public void test3a() { fEl.setTagPosition(1, 2); - assertEquals("tagposition.length", 2, fEl.getTagPosition().getLength()); //$NON-NLS-1$ - assertEquals("tagposition.offset", 1, fEl.getTagPosition().getOffset()); //$NON-NLS-1$ + assertEquals(2, fEl.getTagPosition().getLength(), "tagposition.length"); //$NON-NLS-1$ + assertEquals(1, fEl.getTagPosition().getOffset(), "tagposition.offset"); //$NON-NLS-1$ } @Test public void test4() { - assertFalse("hastag", fEl.hasTag()); //$NON-NLS-1$ + assertFalse(fEl.hasTag(), "hastag"); //$NON-NLS-1$ } @Test public void test4a() { fEl.setTagPosition(1, 2); - assertTrue("hastag", fEl.hasTag()); //$NON-NLS-1$ + assertTrue(fEl.hasTag(), "hastag"); //$NON-NLS-1$ } } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintStripQuotesTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintStripQuotesTest.java index 254d0c50c62..80daee09ded 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintStripQuotesTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSHintStripQuotesTest.java @@ -109,4 +109,12 @@ public void test08() throws Exception { String expected= " abc\ndef\n"; assertEquals(expected, y); } + + @Test + public void test09() throws Exception { + String x = "\"\"\""; + String y = NLSHint.stripQuotes(x, javaProject15.getJavaProject()); + String expected = "\""; + assertEquals(expected, y); + } } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java index 457f7399fb3..8587445a514 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSScannerTester.java @@ -14,11 +14,11 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine; @@ -29,42 +29,42 @@ public class NLSScannerTester { public void test0() throws Exception{ String text= "fred"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); - assertEquals("empty", 0, l.length); //$NON-NLS-1$ + assertEquals(0, l.length, "empty"); //$NON-NLS-1$ } @Test public void test1() throws Exception{ String text= "fred\"x\""; NLSLine[] l= NLSScanner.scan(text); - assertEquals("1 line", 1, l.length); + assertEquals(1, l.length, "1 line"); } @Test public void test1a() throws Exception{ String text= "fred\n\"x\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); - assertEquals("1 line", 1, l.length); //$NON-NLS-1$ + assertEquals(1, l.length, "1 line"); //$NON-NLS-1$ } @Test public void test2() throws Exception{ String text= "fred\"x\"\n\"xx\""; NLSLine[] l= NLSScanner.scan(text); - assertEquals("2 line", 2, l.length); + assertEquals(2, l.length, "2 line"); } @Test public void test2a() throws Exception{ String text= "fred\n\"x\" \"xx\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); - assertEquals("1 lines", 1, l.length); //$NON-NLS-1$ + assertEquals(1, l.length, "1 lines"); //$NON-NLS-1$ } @Test public void test3() throws Exception{ String text= "fred\"x\"\n \"xx\""; NLSLine[] l= NLSScanner.scan(text); - assertEquals("2 lines", 2, l.length); + assertEquals(2, l.length, "2 lines"); } @@ -72,7 +72,7 @@ public void test3() throws Exception{ public void test4() throws Exception{ String text= "fred\n \"xx\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); - assertEquals("1 line", 1, l.length); //$NON-NLS-1$ + assertEquals(1, l.length, "1 line"); //$NON-NLS-1$ } @Test @@ -80,7 +80,7 @@ public void test5() throws Exception{ String text= "\n \"xx\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("1 string", 1, line.size()); //$NON-NLS-1$ + assertEquals(1, line.size(), "1 string"); //$NON-NLS-1$ } @Test @@ -88,7 +88,7 @@ public void test6() throws Exception{ String text= "\n \"xx\" \"dff\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("2 string", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 string"); //$NON-NLS-1$ } @Test @@ -96,10 +96,10 @@ public void test7() throws Exception{ String text= "\n \"xx\" \n\"dff\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("1 string A", 1, line.size()); //$NON-NLS-1$ + assertEquals(1, line.size(), "1 string A"); //$NON-NLS-1$ line= l[1]; - assertEquals("1 string B", 1, line.size()); //$NON-NLS-1$ + assertEquals(1, line.size(), "1 string B"); //$NON-NLS-1$ } @@ -108,10 +108,10 @@ public void test8() throws Exception{ String text= "\n \"xx\" \n\"dff\" \"ccc\""; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("1 string A", 1, line.size()); //$NON-NLS-1$ + assertEquals(1, line.size(), "1 string A"); //$NON-NLS-1$ line= l[1]; - assertEquals("2 strings B", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 strings B"); //$NON-NLS-1$ } @Test @@ -120,7 +120,7 @@ public void test9() throws Exception{ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; NLSElement el= line.get(0); - assertTrue("has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "has tag"); //$NON-NLS-1$ } @@ -130,7 +130,7 @@ public void test10() throws Exception{ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; NLSElement el= line.get(0); - assertFalse("has tag", el.hasTag()); //$NON-NLS-1$ + assertFalse(el.hasTag(), "has tag"); //$NON-NLS-1$ } @Test @@ -142,13 +142,13 @@ public void test11() throws Exception{ + "\n"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 strings"); //$NON-NLS-1$ NLSElement el= line.get(0); - assertTrue("0 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "0 has tag"); //$NON-NLS-1$ el= line.get(1); - assertTrue("1 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "1 has tag"); //$NON-NLS-1$ } @Test @@ -160,13 +160,13 @@ public void test12() throws Exception{ + "\n"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 strings"); //$NON-NLS-1$ NLSElement el= line.get(0); - assertTrue("0 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "0 has tag"); //$NON-NLS-1$ el= line.get(1); - assertTrue("1 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "1 has tag"); //$NON-NLS-1$ } @Test @@ -177,13 +177,13 @@ public void test13() throws Exception{ + "\n"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 strings"); //$NON-NLS-1$ NLSElement el= line.get(0); - assertTrue("0 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "0 has tag"); //$NON-NLS-1$ el= line.get(1); - assertFalse("1 has no tag", el.hasTag()); //$NON-NLS-1$ + assertFalse(el.hasTag(), "1 has no tag"); //$NON-NLS-1$ } @Test @@ -194,13 +194,13 @@ public void test14() throws Exception{ + "\n"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("2 strings", 2, line.size()); //$NON-NLS-1$ + assertEquals(2, line.size(), "2 strings"); //$NON-NLS-1$ NLSElement el= line.get(0); - assertFalse("0 has no tag", el.hasTag()); //$NON-NLS-1$ + assertFalse(el.hasTag(), "0 has no tag"); //$NON-NLS-1$ el= line.get(1); - assertTrue("1 has tag", el.hasTag()); //$NON-NLS-1$ + assertTrue(el.hasTag(), "1 has tag"); //$NON-NLS-1$ } // test for bug 102132 @@ -433,9 +433,9 @@ public void test54() throws Exception{ + "\n"; //$NON-NLS-1$ NLSLine[] l= NLSScanner.scan(text); NLSLine line=l[0]; - assertEquals("1 strings", 1, line.size()); //$NON-NLS-1$ + assertEquals(1, line.size(), "1 strings"); //$NON-NLS-1$ NLSElement el= line.get(0); - assertFalse("0 has no tag", el.hasTag()); //$NON-NLS-1$ + assertFalse(el.hasTag(), "0 has no tag"); //$NON-NLS-1$ } } diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java index af01bd3db3e..32f787238ab 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/NLSSubstitutionTest.java @@ -13,11 +13,11 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Properties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSSubstitution; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java index 32c0cc70464..884b44ffdf2 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/PropertyFileDocumentModellTest.java @@ -13,9 +13,9 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.NullProgressMonitor; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java index 391ff752af4..054abb9dd9e 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/nls/SimpleLineReaderTest.java @@ -13,10 +13,10 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring.nls; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jface.text.Document; diff --git a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/RefactoringTypeContraintTestSuite.java similarity index 94% rename from org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java rename to org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/RefactoringTypeContraintTestSuite.java index 00e2c44de41..0bc5ab68384 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/AllTests.java +++ b/org.eclipse.jdt.ui.tests.refactoring/test cases/org/eclipse/jdt/ui/tests/refactoring/typeconstraints/RefactoringTypeContraintTestSuite.java @@ -21,5 +21,5 @@ TypeConstraintTests.class, TypeEnvironmentTests.class }) -public class AllTests { +public class RefactoringTypeContraintTestSuite { } \ No newline at end of file diff --git a/org.eclipse.jdt.ui.tests.refactoring/test.xml b/org.eclipse.jdt.ui.tests.refactoring/test.xml index 73e95952c2d..ee961cd2b62 100644 --- a/org.eclipse.jdt.ui.tests.refactoring/test.xml +++ b/org.eclipse.jdt.ui.tests.refactoring/test.xml @@ -29,7 +29,7 @@ + value="org.eclipse.jdt.ui.tests.refactoring.all.AllRefactoringTestsSuite"/> diff --git a/org.eclipse.jdt.ui.tests/META-INF/MANIFEST.MF b/org.eclipse.jdt.ui.tests/META-INF/MANIFEST.MF index d45cf11af60..05d3c9025ce 100644 --- a/org.eclipse.jdt.ui.tests/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ui.tests/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.ui.tests Bundle-ManifestVersion: 2 Bundle-Name: %Plugin.name Bundle-SymbolicName: org.eclipse.jdt.ui.tests; singleton:=true -Bundle-Version: 3.15.700.qualifier +Bundle-Version: 3.15.800.qualifier Bundle-Activator: org.eclipse.jdt.testplugin.JavaTestPlugin Bundle-Vendor: %Plugin.providerName Bundle-Localization: plugin diff --git a/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ChkpiiTests.java b/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ChkpiiTests.java index ace41d22317..00c7dd27910 100644 --- a/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ChkpiiTests.java +++ b/org.eclipse.jdt.ui.tests/chkpii/org/eclipse/jdt/ui/tests/chkpii/ChkpiiTests.java @@ -33,8 +33,6 @@ import org.junit.Test; import org.junit.rules.TestName; -import org.eclipse.osgi.service.environment.Constants; - import org.eclipse.core.runtime.FileLocator; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; @@ -255,14 +253,7 @@ private String getExec() { } private String getExcludeErrors() { - - String fileName; - - if (Constants.OS_WIN32.equals(Platform.getOS())) - fileName= "ignoreErrorsWindows.txt"; //$NON-NLS-1$ - else - fileName= "ignoreErrorsUnix.txt"; //$NON-NLS-1$ - + String fileName= Platform.OS.isWindows() ? "ignoreErrorsWindows.txt" : "ignoreErrorsUnix.txt"; //$NON-NLS-1$ //$NON-NLS-2$ return toLocation(getClass().getResource(fileName)); } diff --git a/org.eclipse.jdt.ui.tests/pom.xml b/org.eclipse.jdt.ui.tests/pom.xml index a08ead2af49..b9769c520e8 100644 --- a/org.eclipse.jdt.ui.tests/pom.xml +++ b/org.eclipse.jdt.ui.tests/pom.xml @@ -20,7 +20,7 @@ org.eclipse.jdt org.eclipse.jdt.ui.tests - 3.15.700-SNAPSHOT + 3.15.800-SNAPSHOT eclipse-test-plugin true diff --git a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java index 6a8eebd3022..e8980bb816c 100644 --- a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java +++ b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/JavaProjectHelper.java @@ -14,8 +14,8 @@ *******************************************************************************/ package org.eclipse.jdt.testplugin; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.File; import java.io.FileInputStream; diff --git a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/MixedLineDelimiterDetector.java b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/MixedLineDelimiterDetector.java index 34e1e614767..250a8ca7161 100644 --- a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/MixedLineDelimiterDetector.java +++ b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/MixedLineDelimiterDetector.java @@ -13,7 +13,7 @@ *******************************************************************************/ package org.eclipse.jdt.testplugin; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.eclipse.core.resources.IResource; @@ -169,7 +169,7 @@ public static void assertNoMixedLineDelimiters(IJavaElement elem) { } public static void assertNoMixedLineDelimiters(IResource resource) { IResource[] mixedResources= findFilesWithMixedLineDelimiters(resource); - Assert.assertTrue(mixedResources == null || mixedResources.length == 0); + Assertions.assertTrue(mixedResources == null || mixedResources.length == 0); } /** @@ -186,7 +186,7 @@ private static IResource[] findFilesWithMixedLineDelimiters(final IResource reso // engine.search(scope, false, collector, new LineDelimiterLocator(MIXED_LD)); // return (IResource[])result.toArray(new IResource[result.size()]); - Assert.fail("support currently disabled"); + Assertions.fail("support currently disabled"); return new IResource[0]; } diff --git a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/StringAsserts.java b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/StringAsserts.java index ce9238de987..dd3baa9453f 100644 --- a/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/StringAsserts.java +++ b/org.eclipse.jdt.ui.tests/test plugin/org/eclipse/jdt/testplugin/StringAsserts.java @@ -19,7 +19,7 @@ import java.util.ArrayList; import java.util.Arrays; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; public class StringAsserts { @@ -51,9 +51,9 @@ public static void assertEqualString(String actual, String expected) { return; } if (actual == null) { - Assert.fail("Content not as expected: is 'null' expected: " + expected); + Assertions.fail("Content not as expected: is 'null' expected: " + expected); } else { - Assert.fail("Content not as expected: expected 'null' is: " + actual); + Assertions.fail("Content not as expected: expected 'null' is: " + actual); } } @@ -67,7 +67,7 @@ public static void assertEqualString(String actual, String expected) { // use detailed message String message= "Content not as expected: is\n" + actual + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + expected; //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ - Assert.assertEquals(message, expected, actual); + Assertions.assertEquals(expected, actual, message); } } @@ -77,9 +77,9 @@ public static void assertEqualStringIgnoreDelim(String actual, String expected) return; } if (actual == null) { - Assert.fail("Content not as expected: is 'null' expected: " + expected); + Assertions.fail("Content not as expected: is 'null' expected: " + expected); } else { - Assert.fail("Content not as expected: expected 'null' is: " + actual); + Assertions.fail("Content not as expected: expected 'null' is: " + actual); } } @@ -98,7 +98,7 @@ public static void assertEqualStringIgnoreDelim(String actual, String expected) String diffStr= (s1 == null) ? s2 : s1; String message= "Content not as expected: Content is: \n" + actual + "\nDiffers at line " + line + ": " + diffStr + "\nExpected contents: \n" + expected; - Assert.assertEquals(message, expected, actual); + Assertions.assertEquals(expected, actual, message); } line++; } while (true); @@ -143,7 +143,7 @@ public static void assertEqualStringsIgnoreOrder(String[] actuals, String[] expe String expected= buf.toString(); String message= "Content not as expected: Content is: \n" + actual + "\nExpected contents: \n" + expected; - Assert.assertEquals(message, expected, actual); + Assertions.assertEquals(expected, actual, message); } } @@ -186,7 +186,7 @@ public static void assertExpectedExistInProposals(String[] actuals, String[] exp String expected= buf.toString(); String message= "Content not as expected: Content is: \n" + actual + "\nExpected contents: \n" + expected; - Assert.assertEquals(message, expected, actual); + Assertions.assertEquals(expected, actual, message); } } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaIgnoreWhitespaceContributorTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaIgnoreWhitespaceContributorTest.java index 75cdcbb7152..8bf008999a0 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaIgnoreWhitespaceContributorTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaIgnoreWhitespaceContributorTest.java @@ -22,7 +22,7 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaTokenComparatorTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaTokenComparatorTest.java index a549a048e65..714bc92f53c 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaTokenComparatorTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/internal/ui/compare/JavaTokenComparatorTest.java @@ -13,11 +13,11 @@ *******************************************************************************/ package org.eclipse.jdt.internal.ui.compare; -import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class JavaTokenComparatorTest { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/launcher/AdvancedJUnitLaunchConfigurationDelegateTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/launcher/AdvancedJUnitLaunchConfigurationDelegateTest.java index 7f340d50589..bd340fae95a 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/launcher/AdvancedJUnitLaunchConfigurationDelegateTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/launcher/AdvancedJUnitLaunchConfigurationDelegateTest.java @@ -20,8 +20,8 @@ import java.nio.file.Paths; import java.util.List; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.junit.JUnitCore; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -47,7 +47,7 @@ public class AdvancedJUnitLaunchConfigurationDelegateTest { private IJavaProject fJavaProject; - @After + @AfterEach public void deleteProject() throws CoreException { if (fJavaProject != null) { JavaProjectHelper.delete(fJavaProject); @@ -200,7 +200,7 @@ private List showCommandLineAndExtractContentOfTestNameFile(String proje private String extractPathForArgumentFile(String showCommandLine, String firstSearchStr, int indexTestNameFile) { String filePath= showCommandLine.substring(indexTestNameFile + firstSearchStr.length() + 1); - if (Platform.OS_WIN32.equals(Platform.getOS())) { + if (Platform.OS.isWindows()) { filePath = removeQuotationMarks(filePath); } return filePath; diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/tests/TestEnableAssertions.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/tests/TestEnableAssertions.java index 5e637563684..3246ccd652b 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/tests/TestEnableAssertions.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/junit/tests/TestEnableAssertions.java @@ -14,10 +14,10 @@ *******************************************************************************/ package org.eclipse.jdt.junit.tests; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.util.DialogCheck; @@ -99,12 +99,12 @@ protected void tabGroupSetDefaultTester(ILaunchConfigurationTabGroup testSubject ILaunchConfigurationWorkingCopy wcFalse= getNewConfigWorkingCopy(); testSubject.createTabs(null, null); testSubject.setDefaults(wcFalse); - assertFalse("Enable assertions argument should not be enabled", getAssertArgEnabled(wcFalse)); + assertFalse(getAssertArgEnabled(wcFalse), "Enable assertions argument should not be enabled"); AssertionVMArg.setEnableAssertionsPreference(true); ILaunchConfigurationWorkingCopy wcTrue= getNewConfigWorkingCopy(); testSubject.setDefaults(wcTrue); - assertTrue("Enable assertions argument should be enabled", getAssertArgEnabled(wcTrue)); + assertTrue(getAssertArgEnabled(wcTrue), "Enable assertions argument should be enabled"); } catch (CoreException err) { throw new RuntimeException(err); } finally { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests.java index dbb545d795e..d0fcc8a3ee1 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.browsing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -110,7 +110,7 @@ public void testGetChildrenProjectWithSourceFolders() throws Exception { Object[] expectedChildren= new Object[]{fPack21, fPack12, cp, defaultCp}; Object[] children= fProvider.getChildren(fJProject2); - assertTrue("Wrong children found for project", compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for project");//$NON-NLS-1$ } @@ -121,14 +121,14 @@ public void testGetChildrentMidLevelFragmentNotLogicalPackage() throws Exception Object[] expectedChildren= new Object[]{fPack17}; Object[] actualChildren= fProvider.getChildren(fPack12); - assertTrue("Wrong children found for PackageFragment", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragment");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment() throws Exception { Object[] expectedChildren= new Object[]{}; Object[] actualChildren= fProvider.getChildren(fPack21); - assertTrue("Wrong children found for PackageFragment", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragment");//$NON-NLS-1$ } @Test @@ -153,7 +153,7 @@ public void testGetChildrenLogicalPackage() throws Exception { Object[] expectedChildren= new Object[]{fPack81, childCp1, childCp2}; Object[] actualChildren= fProvider.getChildren(cp); - assertTrue("Wrong children found for project", compareArrays(actualChildren, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for project"); //$NON-NLS-1$ } @Test @@ -173,7 +173,7 @@ public void testGetChildrenLogicalPackage2() throws Exception { Object[] expectedChildren= new Object[]{fPack91, fInternalPack10}; Object[] actualChildren= fProvider.getChildren(cp); - assertTrue("Wrong children found for project", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for project");//$NON-NLS-1$ } @Test @@ -184,28 +184,28 @@ public void testGetChildrenMidLevelFragmentInArchive() throws Exception { Object[] expectedChildren= new Object[]{fPackJunitSamplesMoney}; Object[] actualChildren= fProvider.getChildren(fPackJunitSamples); - assertTrue("wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Archive", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Archive");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentInArchive() throws Exception { Object[] expectedChildren= new Object[]{}; Object[] actualChildren= fProvider.getChildren(fPackJunitSamplesMoney); - assertTrue("wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive", compareArrays(actualChildren, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive"); //$NON-NLS-1$ } @Test public void testGetChildrenSourceFolder() throws Exception { Object[] expectedChildren = new Object[] {fPack21, fPack31, fPackDefault1}; Object[] actualChildren = fProvider.getChildren(fRoot1); - assertTrue("Wrong children found for PackageFragmentRoot", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragmentRoot");//$NON-NLS-1$ } @Test public void testGetChildrenArchive() { Object[] expectedChildren= new Object[] {fPackJunit, fArchiveFragmentRoot.getPackageFragment("")};//$NON-NLS-1$ Object[] actualChildren= fProvider.getChildren(fArchiveFragmentRoot); - assertTrue("Wrong child found for PackageFragmentRoot Archive", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong child found for PackageFragmentRoot Archive");//$NON-NLS-1$ } //---------------Get Parent Tests----------------------------- @@ -213,7 +213,7 @@ public void testGetChildrenArchive() { @Test public void testGetParentArchive() throws Exception { Object actualParent= fProvider.getParent(fArchiveFragmentRoot); - assertNull("Wrong parent found for PackageFragmentRoot Archive", actualParent);//$NON-NLS-1$ + assertNull(actualParent, "Wrong parent found for PackageFragmentRoot Archive");//$NON-NLS-1$ } @Test @@ -225,14 +225,14 @@ public void testGetParentMidLevelFragmentInArchive() throws Exception { Object expectedParent= fPackJunitSamples; Object actualParent= fProvider.getParent(fPackJunitSamplesMoney); - assertEquals("Wrong parent found for a NON top level PackageFragment in an Archive", expectedParent, actualParent);//$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a NON top level PackageFragment in an Archive");//$NON-NLS-1$ } @Test public void testGetParentTopLevelFragmentInArchive() throws Exception { Object expectedParent= fPackJunit; Object actualParent= fProvider.getParent(fPackJunitSamples); - assertEquals("Wrong parent found for a top level PackageFragment in an Archive", expectedParent, actualParent); //$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a top level PackageFragment in an Archive"); //$NON-NLS-1$ } @Test @@ -242,7 +242,7 @@ public void testGetParentTopLevelLogicalPackage() throws Exception { cp.add(fInternalPack3); Object actualParent= fProvider.getParent(cp); - assertEquals("Wrong parent found for a top level LogicalPackage", fJProject2, actualParent);//$NON-NLS-1$ + assertEquals(fJProject2, actualParent, "Wrong parent found for a top level LogicalPackage");//$NON-NLS-1$ } @Test @@ -255,7 +255,7 @@ public void testGetParentPackageFragmentWithLogicalPackageParent() throws Except fProvider.getChildren(fJProject2); Object parent= fProvider.getParent(fPack81); - assertEquals("Wrong parent found for a top level LogicalPackage", cp, parent);//$NON-NLS-1$ + assertEquals(cp, parent, "Wrong parent found for a top level LogicalPackage");//$NON-NLS-1$ } @Test @@ -272,7 +272,7 @@ public void testGetParentOfLogicalPackagetWithLogicalPackageParent() throws Exce fProvider.getChildren(fJProject2); Object parent= fProvider.getParent(cp); - assertEquals("Wrong parent found for a top level LogicalPackage", parentCp, parent);//$NON-NLS-1$ + assertEquals(parentCp, parent, "Wrong parent found for a top level LogicalPackage");//$NON-NLS-1$ } // public void testGetParentWithPFRootFocus(){ @@ -299,7 +299,7 @@ public void testGetParentPFwithProjectFocus(){ cp.add(fInternalPack3); Object parent= fProvider.getParent(fPack41); - assertEquals("Wrong parent found for a mid level Fragment with Root Focus", cp, parent); //$NON-NLS-1$ + assertEquals(cp, parent, "Wrong parent found for a mid level Fragment with Root Focus"); //$NON-NLS-1$ } @Test @@ -321,7 +321,7 @@ public void testGetParentWithRootFocusAfterProjectFocus(){ Object[] expectedChildren= new Object[]{fPack21, fPack12, cp, defaultCp}; - assertTrue("expected children of project with focus", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "expected children of project with focus");//$NON-NLS-1$ //set up map with root focus for (Object object : fProvider.getChildren(fRoot1)) { @@ -335,7 +335,7 @@ public void testGetParentWithRootFocusAfterProjectFocus(){ public void testGetParentTopLevelFragment() throws Exception { Object actualParent= fProvider.getParent(fPack21); Object expectedParent= fRoot1; - assertEquals("Wrong parent found for a top level PackageFragment", expectedParent, actualParent); //$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a top level PackageFragment"); //$NON-NLS-1$ } @@ -343,7 +343,7 @@ public void testGetParentTopLevelFragment() throws Exception { public void testGetParentMidLevelFragment() throws Exception { Object expectedParent= fPack12; Object actualParent= fProvider.getParent(fPack17); - assertEquals("Wrong parent found for a NON top level PackageFragment", expectedParent, actualParent); //$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a NON top level PackageFragment"); //$NON-NLS-1$ } @@ -356,7 +356,7 @@ public void testBug123424_1() throws Exception { fJProject2.setRawClasspath(new IClasspathEntry[] {rawClasspath[0], element.getClasspathEntry(), rawClasspath[2]}, null); Object[] expectedChildren= new Object[]{fPack12.getResource(), fPack32.getResource()}; Object[] actualChildren= fProvider.getChildren(fRoot2); - assertTrue("Wrong children found for project", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for project");//$NON-NLS-1$ } @Test @@ -368,13 +368,13 @@ public void testBug123424_2() throws Exception { fJProject2.setRawClasspath(new IClasspathEntry[] {rawClasspath[0], element.getClasspathEntry(), rawClasspath[2]}, null); Object[] expectedChildren= new Object[]{fPack42.getResource(), fPack52}; Object[] actualChildren= fProvider.getChildren(fPack32.getResource()); - assertTrue("Wrong children found for project", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for project");//$NON-NLS-1$ } /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); assertNotNull(fWorkspace); @@ -387,22 +387,22 @@ public void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");//$NON-NLS-1$//$NON-NLS-2$ fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project1 null", fJProject1);//$NON-NLS-1$ - assertNotNull("project2 null", fJProject2);//$NON-NLS-1$ + assertNotNull(fJProject1, "project1 null");//$NON-NLS-1$ + assertNotNull(fJProject2, "project2 null");//$NON-NLS-1$ //------------set up project #1 : External Jar and zip file------- IPackageFragmentRoot jdk= JavaProjectHelper.addVariableRTJar(fJProject1, "JRE_LIB_TEST", null, null);//$NON-NLS-1$ - assertNotNull("jdk not found", jdk);//$NON-NLS-1$ + assertNotNull(jdk, "jdk not found");//$NON-NLS-1$ //---Create zip file------------------- java.io.File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); - assertNotNull("junit src not found", junitSrcArchive);//$NON-NLS-1$ - assertTrue("junit src not found", junitSrcArchive.exists());//$NON-NLS-1$ + assertNotNull(junitSrcArchive, "junit src not found");//$NON-NLS-1$ + assertTrue(junitSrcArchive.exists(), "junit src not found");//$NON-NLS-1$ fArchiveFragmentRoot= JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);//$NON-NLS-1$ @@ -410,9 +410,9 @@ public void setUp() throws Exception { fPackJunitSamples= fArchiveFragmentRoot.getPackageFragment("junit.samples");//$NON-NLS-1$ fPackJunitSamplesMoney= fArchiveFragmentRoot.getPackageFragment("junit.samples.money");//$NON-NLS-1$ - assertNotNull("creating fPackJunit", fPackJunit);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamples", fPackJunitSamples);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamplesMoney",fPackJunitSamplesMoney);//$NON-NLS-1$ + assertNotNull(fPackJunit, "creating fPackJunit");//$NON-NLS-1$ + assertNotNull(fPackJunitSamples, "creating fPackJunitSamples");//$NON-NLS-1$ + assertNotNull(fPackJunitSamplesMoney,"creating fPackJunitSamplesMoney");//$NON-NLS-1$ fPackJunitSamplesMoney.getCompilationUnit("IMoney.java");//$NON-NLS-1$ fPackJunitSamplesMoney.getCompilationUnit("Money.java");//$NON-NLS-1$ @@ -425,8 +425,8 @@ public void setUp() throws Exception { //----------------Set up internal jar---------------------------- File myInternalJar= JavaTestPlugin.getDefault().getFileInPlugin(new Path("testresources/compoundtest.jar"));//$NON-NLS-1$ - assertNotNull("lib not found", myInternalJar);//$NON-NLS-1$ - assertTrue("lib not found", myInternalJar.exists());//$NON-NLS-1$ + assertNotNull(myInternalJar, "lib not found");//$NON-NLS-1$ + assertTrue(myInternalJar.exists(), "lib not found");//$NON-NLS-1$ fInternalJarRoot= JavaProjectHelper.addLibraryWithImport(fJProject2, Path.fromOSString(myInternalJar.getPath()), null, null); @@ -500,7 +500,7 @@ public void setUpMockView() throws Exception { /* * @see TestCase#tearDown() */ - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); JavaProjectHelper.delete(fJProject2); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests2.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests2.java index e8ec8a86e04..ccbecfeb51a 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests2.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewContentProviderTests2.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.browsing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -105,7 +105,7 @@ public class PackagesViewContentProviderTests2 { public void testGetElementsPackageFragmentRoot() throws Exception { Object[] children= fProvider.getElements(fRoot1); Object[] expectedChildren= new Object[] { fPack21, fPack31, fPack41, fPack51, fPack61, fPack81, fPack91, fPackDefault1 }; - assertTrue("Wrong children found for PackageFragment", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for PackageFragment"); //$NON-NLS-1$ } @Test @@ -136,7 +136,7 @@ public void testGetElementsProject() throws Exception { Object[] children= fProvider.getElements(fJProject2); Object[] expectedChildren= new Object[] { defaultCp, cp3, cp4, cp5, cp6, cp10, fPack21, fPack12, fPack91, fPack81, fPack17 }; - assertTrue("Wrong children founf for PackageFragment", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children founf for PackageFragment"); //$NON-NLS-1$ } //---------------Delta Tests----------------------------- @@ -154,8 +154,8 @@ public void testRemovePackageNotLogicalPackage() throws Exception { //force events from display fMyPart.pushDisplay(); - assertTrue("Remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Correct package removed", fMyPart.getRemovedObject().contains(fPack12)); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRemovedObject().contains(fPack12), "Correct package removed"); //$NON-NLS-1$ } @Test @@ -178,12 +178,12 @@ public void testRemovePackageInTwoPackageLogicalPackage() throws Exception { fMyPart.pushDisplay(); //assert remove happened (delta worked) - assertTrue("Refresh happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Refresh happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Refresh happened"); //$NON-NLS-1$ Object addedObject= fMyPart.getAddedObject().get(0); Object removedObject= fMyPart.getRemovedObject().get(0); - assertTrue("Correct guy removed", canFindEqualCompoundElement(cp10, new Object[] { removedObject })); //$NON-NLS-1$ - assertEquals("Correct guy added", fInternalPack10, addedObject); //$NON-NLS-1$ + assertTrue(canFindEqualCompoundElement(cp10, new Object[] { removedObject }), "Correct guy removed"); //$NON-NLS-1$ + assertEquals(fInternalPack10, addedObject, "Correct guy added"); //$NON-NLS-1$ } @Test @@ -203,7 +203,7 @@ public void testRemovePackageFromLogicalPackage() throws Exception { fMyPart.pushDisplay(); //assert remove happened (delta worked) - assertFalse("Refresh did not happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRefreshHappened(), "Refresh did not happened"); //$NON-NLS-1$ } @Test @@ -228,9 +228,9 @@ public void testRemoveCUFromPackageNotLogicalPackage() throws Exception { } private void assertPack81RefreshedOnce() { - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("fPack81 not refreshed:\n" + fMyPart.getRefreshedObject(), fMyPart.getRefreshedObject().contains(fPack81)); - assertEquals("Too many refreshes (" + fMyPart.getRefreshedObject().size() + "):\n" + fMyPart.getRefreshedObject(), 1, fMyPart.getRefreshedObject().size()); + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(fPack81), "fPack81 not refreshed:\n" + fMyPart.getRefreshedObject()); + assertEquals(1, fMyPart.getRefreshedObject().size(), "Too many refreshes (" + fMyPart.getRefreshedObject().size() + "):\n" + fMyPart.getRefreshedObject()); } @Test @@ -251,9 +251,9 @@ public void testAddCUFromPackageNotLogicalPackage() throws Exception { fMyPart.pushDisplay(); assertPack81RefreshedOnce(); - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("fPack81 not refreshed:\n" + fMyPart.getRefreshedObject(), fMyPart.getRefreshedObject().contains(fPack81)); - assertEquals("Too many refreshes (" + fMyPart.getRefreshedObject().size() + "):\n" + fMyPart.getRefreshedObject(), 1, fMyPart.getRefreshedObject().size()); + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(fPack81), "fPack81 not refreshed:\n" + fMyPart.getRefreshedObject()); + assertEquals(1, fMyPart.getRefreshedObject().size(), "Too many refreshes (" + fMyPart.getRefreshedObject().size() + "):\n" + fMyPart.getRefreshedObject()); } @Test @@ -276,7 +276,7 @@ public void testAddFragmentToLogicalPackage() throws Exception { fMyPart.pushDisplay(); //make sure no refresh happened - assertFalse("Refresh did not happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRefreshHappened(), "Refresh did not happened"); //$NON-NLS-1$ } @Test @@ -295,8 +295,8 @@ public void testAddPackageNotLogicalPackage() throws Exception { //force events from display fMyPart.pushDisplay(); - assertTrue("Add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ - assertTrue("Correct package added", fMyPart.getAddedObject().contains(test)); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Add happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getAddedObject().contains(test), "Correct package added"); //$NON-NLS-1$ } @Test @@ -322,12 +322,12 @@ public void testAddPackageToCreateLogicalPackage() throws Exception { fMyPart.pushDisplay(); //assert remove and add happened (delta worked) - assertTrue("Remove and add happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Remove and add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove and add happened"); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Remove and add happened"); //$NON-NLS-1$ Object addedObject= fMyPart.getAddedObject().get(0); Object removedObject= fMyPart.getRemovedObject().get(0); - assertEquals("Correct guy removed", fPack12, removedObject); //$NON-NLS-1$ - assertEquals("Correct guy added", lp1, addedObject); //$NON-NLS-1$ + assertEquals(fPack12, removedObject, "Correct guy removed"); //$NON-NLS-1$ + assertEquals(lp1, addedObject, "Correct guy added"); //$NON-NLS-1$ } @@ -335,7 +335,7 @@ public void testAddPackageToCreateLogicalPackage() throws Exception { /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); assertNotNull(fWorkspace); @@ -348,22 +348,22 @@ public void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");//$NON-NLS-1$//$NON-NLS-2$ fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project1 null", fJProject1);//$NON-NLS-1$ - assertNotNull("project2 null", fJProject2);//$NON-NLS-1$ + assertNotNull(fJProject1, "project1 null");//$NON-NLS-1$ + assertNotNull(fJProject2, "project2 null");//$NON-NLS-1$ //------------set up project #1 : External Jar and zip file------- IPackageFragmentRoot jdk= JavaProjectHelper.addVariableRTJar(fJProject1, "JRE_LIB_TEST", null, null);//$NON-NLS-1$ - assertNotNull("jdk not found", jdk);//$NON-NLS-1$ + assertNotNull(jdk, "jdk not found");//$NON-NLS-1$ //---Create zip file------------------- java.io.File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); - assertNotNull("junit src not found", junitSrcArchive);//$NON-NLS-1$ - assertTrue("junit src not found", junitSrcArchive.exists());//$NON-NLS-1$ + assertNotNull(junitSrcArchive, "junit src not found");//$NON-NLS-1$ + assertTrue(junitSrcArchive.exists(), "junit src not found");//$NON-NLS-1$ fArchiveFragmentRoot= JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);//$NON-NLS-1$ @@ -371,9 +371,9 @@ public void setUp() throws Exception { fPackJunitSamples= fArchiveFragmentRoot.getPackageFragment("junit.samples");//$NON-NLS-1$ fPackJunitSamplesMoney= fArchiveFragmentRoot.getPackageFragment("junit.samples.money");//$NON-NLS-1$ - assertNotNull("creating fPackJunit", fPackJunit);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamples", fPackJunitSamples);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamplesMoney",fPackJunitSamplesMoney);//$NON-NLS-1$ + assertNotNull(fPackJunit, "creating fPackJunit");//$NON-NLS-1$ + assertNotNull(fPackJunitSamples, "creating fPackJunitSamples");//$NON-NLS-1$ + assertNotNull(fPackJunitSamplesMoney,"creating fPackJunitSamplesMoney");//$NON-NLS-1$ fPackJunitSamplesMoney.getCompilationUnit("IMoney.java");//$NON-NLS-1$ fPackJunitSamplesMoney.getCompilationUnit("Money.java");//$NON-NLS-1$ @@ -386,8 +386,8 @@ public void setUp() throws Exception { //----------------Set up internal jar---------------------------- File myInternalJar= JavaTestPlugin.getDefault().getFileInPlugin(new Path("testresources/compoundtest.jar"));//$NON-NLS-1$ - assertNotNull("lib not found", myInternalJar);//$NON-NLS-1$ - assertTrue("lib not found", myInternalJar.exists());//$NON-NLS-1$ + assertNotNull(myInternalJar, "lib not found");//$NON-NLS-1$ + assertTrue(myInternalJar.exists(), "lib not found");//$NON-NLS-1$ fInternalJarRoot= JavaProjectHelper.addLibraryWithImport(fJProject2, Path.fromOSString(myInternalJar.getPath()), null, null); @@ -464,7 +464,7 @@ public void setUpMockView() throws Exception{ /* * @see TestCase#tearDown() */ - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewDeltaTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewDeltaTests.java index 0215213bc61..fd1df3d549f 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewDeltaTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/browsing/PackagesViewDeltaTests.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.browsing; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -110,8 +110,8 @@ public void testRemoveTopLevelFragmentNotLogicalPackage() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertTrue("Remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Correct package removed", fMyPart.getRemovedObject().contains(fPack12)); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRemovedObject().contains(fPack12), "Correct package removed"); //$NON-NLS-1$ } @Test @@ -128,7 +128,7 @@ public void testRemoveBottomLevelFragmentNotLogicalPackage() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertFalse("No remove happened, in Logical Package", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRemoveHappened(), "No remove happened, in Logical Package"); //$NON-NLS-1$ } //This is a bogus test because this situation could never occur @@ -162,15 +162,15 @@ public void testRemoveFragmentInMultiFragmentLogicalPackage() throws Exception { fMyPart.pushDisplay(); // Assert remove happened - assertFalse("Remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertFalse("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRemoveHappened(), "Remove happened"); //$NON-NLS-1$ + assertFalse(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ // Test life cycle of Logical Package Object parent= fProvider.getParent(ChildCp1); - assertTrue("wrong parent found for logical package after remove", parent instanceof LogicalPackage); + assertTrue(parent instanceof LogicalPackage, "wrong parent found for logical package after remove"); LogicalPackage lp= (LogicalPackage) parent; - assertEquals("PackageFragment removed from logical package", expectedParent, lp); //$NON-NLS-1$ + assertEquals(expectedParent, lp, "PackageFragment removed from logical package"); //$NON-NLS-1$ } @Test @@ -208,16 +208,16 @@ public void testRemoveBottomLevelFragmentInMultiFragmentLogicalPackage() throws fMyPart.pushDisplay(); // Assert delta correct (no remove or refresh, only change to logicalpackage) - assertFalse("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertFalse("Refresh happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertFalse(fMyPart.hasRemoveHappened(), "Refresh happened"); //$NON-NLS-1$ // Test life cycle of LogicalPackage Object[] child= fProvider.getChildren(ParentCp5); - assertTrue("wrong parent found for logical package after remove", (child.length == 1) && (child[0] instanceof LogicalPackage)); //$NON-NLS-1$ + assertTrue((child.length == 1) && (child[0] instanceof LogicalPackage), "wrong parent found for logical package after remove"); //$NON-NLS-1$ LogicalPackage lp= (LogicalPackage) child[0]; - assertEquals("PackageFragment removed from logical package", expectedChild, lp); //$NON-NLS-1$ + assertEquals(expectedChild, lp, "PackageFragment removed from logical package"); //$NON-NLS-1$ } @Test @@ -253,16 +253,16 @@ public void testRemoveFragmentInTwoFragmentLogicalPackage() throws Exception { fMyPart.pushDisplay(); // Assert remove happened (delta worked) - assertTrue("Refresh happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Refresh happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Refresh happened"); //$NON-NLS-1$ Object addedObject= fMyPart.getAddedObject().get(0); Object removedObject= fMyPart.getRemovedObject().get(0); - assertEquals("Correct guy removed", cp10, removedObject); //$NON-NLS-1$ - assertEquals("Correct guy added", fInternalPack10, addedObject); //$NON-NLS-1$ + assertEquals(cp10, removedObject, "Correct guy removed"); //$NON-NLS-1$ + assertEquals(fInternalPack10, addedObject, "Correct guy added"); //$NON-NLS-1$ // Assert correct children gotten Object[] children= fProvider.getChildren(ParentCp4); - assertTrue("PackageFragment removed from logial package", compareArrays(children, new Object[] { fPack91, fInternalPack10 })); //$NON-NLS-1$ + assertTrue(compareArrays(children, new Object[] { fPack91, fInternalPack10 }), "PackageFragment removed from logial package"); //$NON-NLS-1$ } //-----------------------Add delta test cases---------------------------------- @@ -281,8 +281,8 @@ public void testAddTopLevelFragmentNotLogicalPackage() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertTrue("Add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ - assertTrue("Correct package added", fMyPart.getAddedObject().contains(test)); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Add happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getAddedObject().contains(test), "Correct package added"); //$NON-NLS-1$ } @Test @@ -305,7 +305,7 @@ public void testAddFragmentToLogicalPackage() throws Exception { fMyPart.pushDisplay(); // Make sure no refresh happened - assertFalse("Refresh did not happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRefreshHappened(), "Refresh did not happened"); //$NON-NLS-1$ } @Test @@ -332,9 +332,9 @@ public void testAddCUFromFragmentNotLogicalPackageVisible() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct package refreshed", fMyPart.getRefreshedObject().contains(fPack81)); //$NON-NLS-1$ - assertEquals("Correct number of refreshes", 1, fMyPart.getRefreshedObject().size());//$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(fPack81), "Correct package refreshed"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Correct number of refreshes");//$NON-NLS-1$ } @Test @@ -359,9 +359,9 @@ public void testAddCUFromFragmentNotLogicalPackageNotVisible() throws Exception // Force events from display fMyPart.pushDisplay(); - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct package refreshed", fMyPart.getRefreshedObject().contains(cp3)); //$NON-NLS-1$ - assertEquals("Correct number of refreshes", 1, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(cp3), "Correct package refreshed"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Correct number of refreshes"); //$NON-NLS-1$ } @Test @@ -390,9 +390,9 @@ public void testRemoveCUFromFragmentNotLogicalPackage() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct package refreshed", fMyPart.getRefreshedObject().contains(fPack81)); //$NON-NLS-1$ - assertEquals("Correct number of refreshes", 1, fMyPart.getRefreshedObject().size());//$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(fPack81), "Correct package refreshed"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Correct number of refreshes");//$NON-NLS-1$ } @Test @@ -417,9 +417,9 @@ public void testRemoveCUFromFragmentNotLogicalPackageWithParentNotVisible() thro // Force events from display fMyPart.pushDisplay(); - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct package refreshed", fMyPart.getRefreshedObject().contains(cp3)); //$NON-NLS-1$ - assertEquals("Correct number of refreshes", 1, fMyPart.getRefreshedObject().size());//$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRefreshedObject().contains(cp3), "Correct package refreshed"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Correct number of refreshes");//$NON-NLS-1$ } @Test @@ -443,14 +443,14 @@ public void testAddBottomLevelFragmentNotLogicalPackage() throws Exception { // Force events from display fMyPart.pushDisplay(); - assertTrue("Add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ - assertTrue("Corrent package added", fMyPart.getAddedObject().contains(test)); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Add happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getAddedObject().contains(test), "Corrent package added"); //$NON-NLS-1$ } /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); assertNotNull(fWorkspace); @@ -462,12 +462,12 @@ public void setUp() throws Exception { //------------set up project ------------------------------ fJProject= JavaProjectHelper.createJavaProject("TestProject2", "bin"); //$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project null", fJProject); //$NON-NLS-1$ + assertNotNull(fJProject, "project null"); //$NON-NLS-1$ //----------------Set up internal jar---------------------------- File myInternalJar= JavaTestPlugin.getDefault().getFileInPlugin(new Path("testresources/compoundtest.jar")); //$NON-NLS-1$ - assertNotNull("lib not found", myInternalJar); //$NON-NLS-1$ - assertTrue("lib not found", myInternalJar.exists()); //$NON-NLS-1$ + assertNotNull(myInternalJar, "lib not found"); //$NON-NLS-1$ + assertTrue(myInternalJar.exists(), "lib not found"); //$NON-NLS-1$ fInternalJarRoot= JavaProjectHelper.addLibraryWithImport(fJProject, Path.fromOSString(myInternalJar.getPath()), null, null); fInternalJarRoot.getPackageFragment(""); //$NON-NLS-1$ fInternalPack3= fInternalJarRoot.getPackageFragment("pack3"); //$NON-NLS-1$ @@ -542,7 +542,7 @@ public void setUpMockView() throws Exception { /* * @see TestCase#tearDown() */ - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject); fProvider.inputChanged(null, null, null); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionEnablementTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionEnablementTest.java index fe10a251d96..b6cb5a70385 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionEnablementTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionEnablementTest.java @@ -13,18 +13,18 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.buildpath; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -107,7 +107,7 @@ public class BuildpathModifierActionEnablementTest { * |- NormalFolder */ - @Before + @BeforeEach public void setUp() throws Exception { fActions= createActions(); fProject= createProject(); @@ -138,7 +138,7 @@ private BuildpathModifierAction[] createActions() { }; } - @After + @AfterEach public void tearDown() throws Exception { fProject.getProject().delete(true, true, null); } @@ -146,9 +146,9 @@ public void tearDown() throws Exception { private void assertOnlyEnabled(IAction[] enabledActions) { for (BuildpathModifierAction action : fActions) { if (action.isEnabled()) { - assertTrue(action.getText() + " is enabled but should not be.", contains(enabledActions, action)); + assertTrue(contains(enabledActions, action), action.getText() + " is enabled but should not be."); } else { - assertFalse(action.getText() + " is disabled but should not be.", contains(enabledActions, action)); + assertFalse(contains(enabledActions, action), action.getText() + " is disabled but should not be."); } } } @@ -164,7 +164,7 @@ private boolean contains(IAction[] actions, IAction action) { private void assertAllDisabled() { for (BuildpathModifierAction action : fActions) { - assertFalse(action.getText() + " is enabled but should not be.", action.isEnabled()); + assertFalse(action.isEnabled(), action.getText() + " is enabled but should not be."); } } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionTest.java index 2b7be9d3a51..275e238147b 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathModifierActionTest.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.buildpath; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.util.List; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -54,7 +54,7 @@ public class BuildpathModifierActionTest { private IJavaProject fJavaProject; - @After + @AfterEach public void tearDown() throws Exception { if (fJavaProject != null) { JavaProjectHelper.delete(fJavaProject); @@ -88,18 +88,18 @@ private static void assertDeltaResources(BuildpathDelta delta, IPath[] createdFo for (int i= 0; i < createdPaths.length; i++) { IPath path= createdPaths[i]; if (createdResources[i] instanceof IFile) { - assertTrue("File " + createdResources[i] + " is unexpected created", contains(createdFiles, path)); + assertTrue(contains(createdFiles, path), "File " + createdResources[i] + " is unexpected created"); } else if (createdResources[i] instanceof IFolder) { - assertTrue("Folder " + createdResources[i] + " is unexpected created", contains(createdFolders, path)); + assertTrue(contains(createdFolders, path), "Folder " + createdResources[i] + " is unexpected created"); } else { fail("Resource " + createdResources[i] + " is nor file nor folder."); } } for (IPath createdFolder : createdFolders) { - assertTrue("Folder at " + createdFolder + " was not created", contains(createdPaths, createdFolder)); + assertTrue(contains(createdPaths, createdFolder), "Folder at " + createdFolder + " was not created"); } for (IPath createdFile : createdFiles) { - assertTrue("File at " + createdFile + " was not created", contains(createdPaths, createdFile)); + assertTrue(contains(createdPaths, createdFile), "File at " + createdFile + " was not created"); } IResource[] deletedResources= delta.getDeletedResources(); @@ -111,24 +111,24 @@ private static void assertDeltaResources(BuildpathDelta delta, IPath[] createdFo for (int i= 0; i < deletedPaths.length; i++) { IPath path= deletedPaths[i]; if (deletedResources[i] instanceof IFile) { - assertTrue("File " + deletedResources[i] + " is unexpected removed", contains(removedFiles, path)); + assertTrue(contains(removedFiles, path), "File " + deletedResources[i] + " is unexpected removed"); } else if (deletedResources[i] instanceof IFolder) { - assertTrue("Folder " + deletedResources[i] + " is unexpected removed", contains(removedFolders, path)); + assertTrue(contains(removedFolders, path), "Folder " + deletedResources[i] + " is unexpected removed"); } else { fail("Resource " + deletedResources[i] + " is nor file nor folder."); } } for (IPath removedFolder : removedFolders) { - assertTrue("Folder at " + removedFolder + " was not removed", contains(deletedPaths, removedFolder)); + assertTrue(contains(deletedPaths, removedFolder), "Folder at " + removedFolder + " was not removed"); } for (IPath removedFile : removedFiles) { - assertTrue("File at " + removedFile + " was not removed", contains(deletedPaths, removedFile)); + assertTrue(contains(deletedPaths, removedFile), "File at " + removedFile + " was not removed"); } } private static void assertDeltaRemovedEntries(BuildpathDelta delta, IPath[] paths) { List removedEntries= delta.getRemovedEntries(); - assertEquals("Expected " + paths.length + " is " + removedEntries.size(), removedEntries.size(), paths.length); + assertEquals(removedEntries.size(), paths.length, "Expected " + paths.length + " is " + removedEntries.size()); IPath[] removed= new IPath[removedEntries.size()]; int i= 0; for (CPListElement element : removedEntries) { @@ -136,16 +136,16 @@ private static void assertDeltaRemovedEntries(BuildpathDelta delta, IPath[] path i++; } for (IPath path : paths) { - assertTrue("Entry " + path + " was not removed", contains(removed, path)); + assertTrue(contains(removed, path), "Entry " + path + " was not removed"); } for (IPath removed1 : removed) { - assertTrue("Entry " + removed1 + " was removed", contains(paths, removed1)); + assertTrue(contains(paths, removed1), "Entry " + removed1 + " was removed"); } } private static void assertDeltaAddedEntries(BuildpathDelta delta, IPath[] paths) { List addedEntries= delta.getAddedEntries(); - assertEquals("Expected " + paths.length + " is " + addedEntries.size(), addedEntries.size(), paths.length); + assertEquals(addedEntries.size(), paths.length, "Expected " + paths.length + " is " + addedEntries.size()); IPath[] added= new IPath[addedEntries.size()]; int i= 0; for (CPListElement element : addedEntries) { @@ -153,10 +153,10 @@ private static void assertDeltaAddedEntries(BuildpathDelta delta, IPath[] paths) i++; } for (IPath path : paths) { - assertTrue("Entry " + path + " was not added", contains(added, path)); + assertTrue(contains(added, path), "Entry " + path + " was not added"); } for (IPath add : added) { - assertTrue("Entry " + add + " was added", contains(paths, add)); + assertTrue(contains(paths, add), "Entry " + add + " was added"); } } @@ -171,11 +171,11 @@ private static boolean contains(IPath[] paths, IPath path) { private static void assertDeltaDefaultOutputFolder(BuildpathDelta delta, IPath expectedLocation) { IPath location= delta.getDefaultOutputLocation(); - assertTrue("Default output location is " + location + " expected was " + expectedLocation, location.equals(expectedLocation)); + assertTrue(location.equals(expectedLocation), "Default output location is " + location + " expected was " + expectedLocation); } private static void assertNumberOfEntries(IClasspathEntry[] entries, int expected) { - assertEquals("Expected count was " + expected + " is " + entries.length, expected, entries.length); + assertEquals(expected, entries.length, "Expected count was " + expected + " is " + entries.length); } @Test @@ -245,7 +245,7 @@ public void testAddExternalJar02AddMuiltiLibsTwice() throws Exception { cpProject= CPJavaProject.createFromExisting(fJavaProject); IStatus status= ClasspathModifier.checkAddExternalJarsPrecondition(jarPaths, cpProject); - assertEquals(status.getMessage(), IStatus.INFO, status.getSeverity()); + assertEquals(IStatus.INFO, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.addExternalJars(jarPaths, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[0], new IPath[0], new IPath[0]); @@ -299,7 +299,7 @@ public void testEditOutputFolder01SetOutputFolderForSourceFolder() throws Except CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertNotEquals(status.getMessage(), IStatus.ERROR, status.getSeverity()); + assertNotEquals(IStatus.ERROR, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -314,7 +314,7 @@ public void testEditOutputFolder01SetOutputFolderForSourceFolder() throws Except IClasspathEntry entry= classpathEntries[1]; assertSame(src.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); } @Test @@ -333,7 +333,7 @@ public void testEditOutputFolder02RemoveProjectAsSourceFolder() throws Exception CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertEquals(status.getMessage(), IStatus.INFO, status.getSeverity()); + assertEquals(IStatus.INFO, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -343,14 +343,14 @@ public void testEditOutputFolder02RemoveProjectAsSourceFolder() throws Exception ClasspathModifier.commitClassPath(cpProject, null); - assertTrue("Default output folder was not set to bin", fJavaProject.getOutputLocation().equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME))); + assertTrue(fJavaProject.getOutputLocation().equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)), "Default output folder was not set to bin"); IClasspathEntry[] classpathEntries= fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 2); IClasspathEntry entry= classpathEntries[1]; assertSame(src.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); } @Test @@ -364,7 +364,7 @@ public void testEditOutputFolder03ExcludeOutputFolderSelf() throws Exception { CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertNotEquals(status.getMessage(), IStatus.ERROR, status.getSeverity()); + assertNotEquals(IStatus.ERROR, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -379,7 +379,7 @@ public void testEditOutputFolder03ExcludeOutputFolderSelf() throws Exception { IClasspathEntry entry= classpathEntries[1]; assertSame(src1.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); IPath[] exclusionPatterns= entry.getExclusionPatterns(); assertEquals(1, exclusionPatterns.length); assertEquals("bin/", exclusionPatterns[0].toString()); @@ -397,7 +397,7 @@ public void testEditOutputFolder03ExcludeOutputFolderOther() throws Exception { CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertNotEquals(status.getMessage(), IStatus.ERROR, status.getSeverity()); + assertNotEquals(IStatus.ERROR, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -412,7 +412,7 @@ public void testEditOutputFolder03ExcludeOutputFolderOther() throws Exception { IClasspathEntry entry= classpathEntries[1]; assertSame(src1.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); entry= classpathEntries[2]; assertSame(src2.getRawClasspathEntry(), entry); @@ -438,7 +438,7 @@ public void testEditOutputFolder04RemoveProjectAndExcludeOutput() throws Excepti CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertEquals(status.getMessage(), IStatus.INFO, status.getSeverity()); + assertEquals(IStatus.INFO, status.getSeverity(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -448,14 +448,14 @@ public void testEditOutputFolder04RemoveProjectAndExcludeOutput() throws Excepti ClasspathModifier.commitClassPath(cpProject, null); - assertTrue("Default output folder was not set to bin", fJavaProject.getOutputLocation().equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME))); + assertTrue(fJavaProject.getOutputLocation().equals(fJavaProject.getPath().append(DEFAULT_OUTPUT_FOLDER_NAME)), "Default output folder was not set to bin"); IClasspathEntry[] classpathEntries= fJavaProject.getRawClasspath(); assertNumberOfEntries(classpathEntries, 3); IClasspathEntry entry= classpathEntries[1]; assertSame(src1.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); entry= classpathEntries[2]; assertSame(src2.getRawClasspathEntry(), entry); @@ -476,7 +476,7 @@ public void testEditOutputFolder05CannotOutputToSource() throws Exception { CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertEquals(status.getMessage(), IStatus.ERROR, status.getSeverity()); + assertEquals(IStatus.ERROR, status.getSeverity(), status.getMessage()); } @Test @@ -490,7 +490,7 @@ public void testEditOutputFolderBug153068() throws Exception { CPJavaProject cpProject= CPJavaProject.createFromExisting(fJavaProject); CPListElement element= cpProject.getCPElement(CPListElement.createFromExisting(src.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertEquals(status.getMessage(), IStatus.ERROR, status.getSeverity()); + assertEquals(IStatus.ERROR, status.getSeverity(), status.getMessage()); } @Test @@ -511,7 +511,7 @@ public void testEditOutputFolderBug154044() throws Exception { cpProject= CPJavaProject.createFromExisting(fJavaProject); element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertTrue(status.getMessage(), status.isOK()); + assertTrue(status.isOK(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[] {oldOutputPath}, new IPath[0], new IPath[0]); @@ -526,10 +526,10 @@ public void testEditOutputFolderBug154044() throws Exception { IClasspathEntry entry= classpathEntries[1]; assertSame(src1.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); IPath[] exclusionPatterns= entry.getExclusionPatterns(); assertEquals(1, exclusionPatterns.length); - assertEquals(exclusionPatterns[0].toString(), "sub/newBin/", exclusionPatterns[0].toString()); + assertEquals("sub/newBin/", exclusionPatterns[0].toString(), exclusionPatterns[0].toString()); } @Test @@ -549,7 +549,7 @@ public void testEditOutputFolderBug154044OldIsProject() throws Exception { cpProject= CPJavaProject.createFromExisting(fJavaProject); element= cpProject.getCPElement(CPListElement.createFromExisting(p01.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertTrue(status.getMessage(), status.isOK()); + assertTrue(status.isOK(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -564,10 +564,10 @@ public void testEditOutputFolderBug154044OldIsProject() throws Exception { IClasspathEntry entry= classpathEntries[1]; assertSame(p01.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); IPath[] exclusionPatterns= entry.getExclusionPatterns(); assertEquals(1, exclusionPatterns.length); - assertEquals(exclusionPatterns[0].toString(), "bin/", exclusionPatterns[0].toString()); + assertEquals("bin/", exclusionPatterns[0].toString(), exclusionPatterns[0].toString()); } @Test @@ -588,7 +588,7 @@ public void testEditOutputFolderBug154044DonotDeleteDefaultOutputFolder() throws cpProject= CPJavaProject.createFromExisting(fJavaProject); element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, outputPath, false, cpProject); - assertTrue(status.getMessage(), status.isOK()); + assertTrue(status.isOK(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, outputPath, false, cpProject); assertDeltaResources(delta, new IPath[] {outputPath}, new IPath[0], new IPath[0], new IPath[0]); @@ -603,7 +603,7 @@ public void testEditOutputFolderBug154044DonotDeleteDefaultOutputFolder() throws IClasspathEntry entry= classpathEntries[1]; assertSame(src1.getRawClasspathEntry(), entry); IPath location= entry.getOutputLocation(); - assertTrue("Output path is " + location + " expected was " + outputPath, outputPath.equals(location)); + assertTrue(outputPath.equals(location), "Output path is " + location + " expected was " + outputPath); IPath[] exclusionPatterns= entry.getExclusionPatterns(); assertEquals(0, exclusionPatterns.length); } @@ -624,7 +624,7 @@ public void testEditOutputFolderBug154196() throws Exception { cpProject= CPJavaProject.createFromExisting(fJavaProject); element= cpProject.getCPElement(CPListElement.createFromExisting(src1.getRawClasspathEntry(), fJavaProject)); IStatus status= ClasspathModifier.checkSetOutputLocationPrecondition(element, null, false, cpProject); - assertTrue(status.getMessage(), status.isOK()); + assertTrue(status.isOK(), status.getMessage()); BuildpathDelta delta= ClasspathModifier.setOutputLocation(element, null, false, cpProject); assertDeltaResources(delta, new IPath[0], new IPath[] {oldOutputPath}, new IPath[0], new IPath[0]); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathProblemQuickFixTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathProblemQuickFixTest.java index a06af9dd560..ade4b04e6f8 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathProblemQuickFixTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/BuildpathProblemQuickFixTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Till Brychcy and others. + * Copyright (c) 2020, 2024 Till Brychcy and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,15 +13,15 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.buildpath; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Arrays; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -52,7 +52,7 @@ public class BuildpathProblemQuickFixTest { private IJavaProject fJavaProject2; - @After + @AfterEach public void tearDown() throws Exception { if (fJavaProject1 != null) { JavaProjectHelper.delete(fJavaProject1); @@ -169,7 +169,7 @@ public void test2Cyclic() throws CoreException, IOException { @Test public void test3RequiredBinaryLevel() throws CoreException, IOException { - IPath container= new Path("org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"); + IPath container= new Path("org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8"); @SuppressWarnings("restriction") IVMInstall vm= org.eclipse.jdt.internal.launching.JREContainerInitializer.resolveVM(container); if (vm == null) { @@ -177,8 +177,8 @@ public void test3RequiredBinaryLevel() throws CoreException, IOException { } if (vm instanceof IVMInstall2) { String version= ((IVMInstall2) vm).getJavaVersion(); - if (version == null || !version.startsWith(JavaCore.VERSION_1_7)) { - // higher version instead of JavaSE 1.7 not found: + if (version == null || !version.startsWith(JavaCore.VERSION_1_8)) { + // higher version instead of JavaSE 1.8 not found: // skip test as error against vm's class files would be reported return; } @@ -194,7 +194,7 @@ public void test3RequiredBinaryLevel() throws CoreException, IOException { String classpath= """ - + @@ -202,9 +202,9 @@ public void test3RequiredBinaryLevel() throws CoreException, IOException { """; addFile(fJavaProject1.getPath(), ".classpath", classpath); addFile(src1.getFullPath(), "LowClass.java", "public class LowClass{HighClass x;}"); - fJavaProject1.setOption(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_7); - fJavaProject1.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_7); - fJavaProject1.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_7); + fJavaProject1.setOption(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); + fJavaProject1.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); + fJavaProject1.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); fJavaProject1.setOption(JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL, JavaCore.ERROR); @@ -222,15 +222,15 @@ public void test3RequiredBinaryLevel() throws CoreException, IOException { """; addFile(fJavaProject2.getPath(), ".classpath", classpath2); addFile(src2.getFullPath(), "HighClass.java", "public class HighClass{}"); - fJavaProject2.setOption(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_1_8); - fJavaProject2.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8); - fJavaProject2.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_1_8); + fJavaProject2.setOption(JavaCore.COMPILER_COMPLIANCE, JavaCore.VERSION_11); + fJavaProject2.setOption(JavaCore.COMPILER_SOURCE, JavaCore.VERSION_11); + fJavaProject2.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, JavaCore.VERSION_11); fJavaProject1.getProject().getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, null); IMarker[] markers= fJavaProject1.getResource().findMarkers("org.eclipse.jdt.core.buildpath_problem", true, IResource.DEPTH_INFINITE); assertEquals( - "Incompatible .class files version in required binaries. Project '3_JDKLevelLow' is targeting a 1.7 runtime, but is compiled against '3_JDKLevelHigh' which requires a 1.8 runtime", + "Incompatible .class files version in required binaries. Project '3_JDKLevelLow' is targeting a 1.8 runtime, but is compiled against '3_JDKLevelHigh' which requires a 11 runtime", markers[0].getAttribute(IMarker.MESSAGE)); assertEquals(1, markers.length); IMarkerResolution[] resolutions= sortResolutions(IDE.getMarkerHelpRegistry().getResolutions(markers[0])); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/CPUserLibraryTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/CPUserLibraryTest.java index 75675c4eb8e..6389e7d67a8 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/CPUserLibraryTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/CPUserLibraryTest.java @@ -13,13 +13,13 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.buildpath; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; @@ -79,7 +79,7 @@ public void testUserLibrarySorting() { String result = Arrays.stream(sortedChildren) .map(e -> ((CPUserLibraryElement)e).getName()) .collect(Collectors.joining(":")); - assertEquals("Unexpected element", "ALIB:BLIB:CLIB", result); + assertEquals("ALIB:BLIB:CLIB", result, "Unexpected element"); } finally { parent.dispose(); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/ClassPathElementsOrderTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/ClassPathElementsOrderTest.java index db53a47582d..ccd303fb46c 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/ClassPathElementsOrderTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/buildpath/ClassPathElementsOrderTest.java @@ -13,14 +13,14 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.buildpath; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.osgi.service.prefs.BackingStoreException; import org.eclipse.core.runtime.CoreException; @@ -52,7 +52,7 @@ public class ClassPathElementsOrderTest { private static final String NEW_JAR_PATH= "/data/test.jar"; - @Before + @BeforeEach public void setUp() throws CoreException, BackingStoreException { IWorkspaceRoot wsRoot= ResourcesPlugin.getWorkspace().getRoot(); IProject genProj= wsRoot.getProject("java proj"); @@ -94,14 +94,14 @@ public void testClassPathOrder() { LibrariesWorkbookPage page= new LibrariesWorkbookPage(classPathList, null); page.init(javaProject); CPListElement cpElement= new CPListElement(javaProject, IClasspathEntry.CPE_LIBRARY, new Path(NEW_JAR_PATH), null); - assertEquals("There should be 2 classpath elements before adding class path element", 2, classPathList.getElements().size()); - assertEquals("java container should be at the top", cont1, classPathList.getElements().get(0)); - assertEquals("src should be at position 1", src1, classPathList.getElements().get(1)); + assertEquals(2, classPathList.getElements().size(), "There should be 2 classpath elements before adding class path element"); + assertEquals(cont1, classPathList.getElements().get(0), "java container should be at the top"); + assertEquals(src1, classPathList.getElements().get(1), "src should be at position 1"); page.addElement(cpElement); - assertEquals("There should be 3 classpath elements after adding class path element", 3, classPathList.getElements().size()); - assertEquals("java container should be at the top", cont1, classPathList.getElements().get(0)); - assertEquals("src should be at position 1", src1, classPathList.getElements().get(1)); - assertEquals("newly added class path entry must be at the end of the list", NEW_JAR_PATH, classPathList.getElements().get(2).getPath().toString()); + assertEquals(3, classPathList.getElements().size(), "There should be 3 classpath elements after adding class path element"); + assertEquals(cont1, classPathList.getElements().get(0), "java container should be at the top"); + assertEquals(src1, classPathList.getElements().get(1), "src should be at position 1"); + assertEquals(NEW_JAR_PATH, classPathList.getElements().get(2).getPath().toString(), "newly added class path entry must be at the end of the list"); } /** @@ -131,14 +131,14 @@ public void testIntegrationClassPathOrderAddingLibrary() { classPathList.setElements(elements); TestableLibrariesWorkBookPage page= new TestableLibrariesWorkBookPage(classPathList, null); page.init(javaProject); - assertEquals("There should be 6 classpath elements before adding external jar", 6, classPathList.getElements().size()); - assertEquals("java container should be at the top", cont1, classPathList.getElements().get(0)); - assertEquals("src should be at position 2", src1, classPathList.getElements().get(2)); + assertEquals(6, classPathList.getElements().size(), "There should be 6 classpath elements before adding external jar"); + assertEquals(cont1, classPathList.getElements().get(0), "java container should be at the top"); + assertEquals(src1, classPathList.getElements().get(2), "src should be at position 2"); page.addExternalJar(); - assertEquals("There should be 7 classpath elements after adding external jar", 7, classPathList.getElements().size()); - assertEquals("java container should be at the top", cont1, classPathList.getElements().get(0)); - assertEquals("src should be at position 2", src1, classPathList.getElements().get(2)); - assertEquals("newly added jar must be at the end of the list", NEW_JAR_PATH, classPathList.getElements().get(6).getPath().toString()); + assertEquals(7, classPathList.getElements().size(), "There should be 7 classpath elements after adding external jar"); + assertEquals(cont1, classPathList.getElements().get(0), "java container should be at the top"); + assertEquals(src1, classPathList.getElements().get(2), "src should be at position 2"); + assertEquals(NEW_JAR_PATH, classPathList.getElements().get(6).getPath().toString(), "newly added jar must be at the end of the list"); } public class TestableLibrariesWorkBookPage extends LibrariesWorkbookPage { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyContentProviderTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyContentProviderTest.java index bc676a746be..fe47a77097b 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyContentProviderTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyContentProviderTest.java @@ -14,14 +14,14 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.callhierarchy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.util.DisplayHelper; @@ -53,7 +53,7 @@ public class CallHierarchyContentProviderTest { private int fOriginalMaxCallDepth; - @Before + @BeforeEach public void setUp() throws Exception { if (!welcomeClosed) { closeIntro(PlatformUI.getWorkbench()); @@ -68,7 +68,7 @@ public void setUp() throws Exception { DisplayHelper.driveEventQueue(Display.getDefault()); } - @After + @AfterEach public void tearDown() throws Exception { helper.tearDown(); helper= null; @@ -84,29 +84,29 @@ public void testGetChildrenOfCalleeRoot() throws Exception { TreeRoot root= wrapCalleeRoot(helper.getMethod4()); Object[] children= fProvider.getChildren(root); - assertEquals("Wrong number of children", 1, children.length); + assertEquals(1, children.length, "Wrong number of children"); helper.assertCalls(new IMember[] { helper.getMethod4()}, children); - assertEquals("Wrong method", helper.getMethod4(), ((MethodWrapper) children[0]).getMember()); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertEquals(helper.getMethod4(), ((MethodWrapper) children[0]).getMember(), "Wrong method"); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getMethod3()}, secondLevelChildren); assertCalleeMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); Object[] thirdLevelChildren= fProvider.getChildren(secondLevelChildren[0]); helper.assertCalls(new IMember[] { helper.getMethod1(), helper.getMethod2()}, thirdLevelChildren); assertCalleeMethodWrapperChildren(thirdLevelChildren); - assertTrue("third level hasChildren", fProvider.hasChildren(secondLevelChildren[0])); + assertTrue(fProvider.hasChildren(secondLevelChildren[0]), "third level hasChildren"); MethodWrapper fourthLevelMethodWrapper= helper.findMethodWrapper(helper.getMethod1(), thirdLevelChildren); - assertNotNull("method1 not found", fourthLevelMethodWrapper); + assertNotNull(fourthLevelMethodWrapper, "method1 not found"); assertEquals( - "Wrong number of fourth level children", 0, - fProvider.getChildren(fourthLevelMethodWrapper).length); + fProvider.getChildren(fourthLevelMethodWrapper).length, + "Wrong number of fourth level children"); // hasChildren should be true even if the node doesn't have children (for performance reasons) - assertTrue("fourth level hasChildren", fProvider.hasChildren(fourthLevelMethodWrapper)); + assertTrue(fProvider.hasChildren(fourthLevelMethodWrapper), "fourth level hasChildren"); } /* @@ -119,23 +119,23 @@ public void testGetChildrenOfCallerRoot() throws Exception { TreeRoot root= wrapCallerRoot(helper.getMethod1()); Object[] children= fProvider.getChildren(root); helper.assertCalls(new IMember[] { helper.getMethod1()}, children); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getMethod2(), helper.getMethod3()}, secondLevelChildren); assertCallerMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); MethodWrapper thirdLevelMethodWrapper= helper.findMethodWrapper(helper.getMethod3(), secondLevelChildren); - assertNotNull("method3() not found", thirdLevelMethodWrapper); + assertNotNull(thirdLevelMethodWrapper, "method3() not found"); Object[] thirdLevelChildren= fProvider.getChildren(thirdLevelMethodWrapper); helper.assertCalls(new IMember[] { helper.getMethod4()}, thirdLevelChildren); assertCallerMethodWrapperChildren(thirdLevelChildren); - assertTrue("third level hasChildren", fProvider.hasChildren(thirdLevelMethodWrapper)); + assertTrue(fProvider.hasChildren(thirdLevelMethodWrapper), "third level hasChildren"); - assertEquals("Wrong number of fourth level children", 0, fProvider.getChildren(thirdLevelChildren[0]).length); + assertEquals(0, fProvider.getChildren(thirdLevelChildren[0]).length, "Wrong number of fourth level children"); // hasChildren should be true even if the node doesn't have children (for performance reasons) - assertTrue("fourth level hasChildren", fProvider.hasChildren(thirdLevelChildren[0])); + assertTrue(fProvider.hasChildren(thirdLevelChildren[0]), "fourth level hasChildren"); } /* @@ -150,23 +150,23 @@ public void testGetChildrenOfCallerMaxDepth() throws Exception { TreeRoot root= wrapCallerRoot(helper.getMethod1()); Object[] children= fProvider.getChildren(root); helper.assertCalls(new IMember[] { helper.getMethod1()}, children); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getMethod2(), helper.getMethod3()}, secondLevelChildren); assertCallerMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); MethodWrapper thirdLevelMethodWrapper= helper.findMethodWrapper(helper.getMethod3(), secondLevelChildren); - assertNotNull("method3() not found", thirdLevelMethodWrapper); + assertNotNull(thirdLevelMethodWrapper, "method3() not found"); Object[] thirdLevelChildren= fProvider.getChildren(thirdLevelMethodWrapper); helper.assertCalls(new IMember[] { helper.getMethod4()}, thirdLevelChildren); assertCallerMethodWrapperChildren(thirdLevelChildren); - assertTrue("third level hasChildren", fProvider.hasChildren(thirdLevelMethodWrapper)); + assertTrue(fProvider.hasChildren(thirdLevelMethodWrapper), "third level hasChildren"); - assertEquals("Wrong number of fourth level children", 0, fProvider.getChildren(thirdLevelChildren[0]).length); + assertEquals(0, fProvider.getChildren(thirdLevelChildren[0]).length, "Wrong number of fourth level children"); // hasChildren should be false since the maximum depth has been reached - assertFalse("fourth level hasChildren", fProvider.hasChildren(thirdLevelChildren[0])); + assertFalse(fProvider.hasChildren(thirdLevelChildren[0]), "fourth level hasChildren"); } /* @@ -180,29 +180,29 @@ public void testGetChildrenOfCalleeMaxDepth() throws Exception { TreeRoot root= wrapCalleeRoot(helper.getMethod4()); Object[] children= fProvider.getChildren(root); - assertEquals("Wrong number of children", 1, children.length); + assertEquals(1, children.length, "Wrong number of children"); helper.assertCalls(new IMember[] { helper.getMethod4()}, children); - assertEquals("Wrong method", helper.getMethod4(), ((MethodWrapper) children[0]).getMember()); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertEquals(helper.getMethod4(), ((MethodWrapper) children[0]).getMember(), "Wrong method"); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getMethod3()}, secondLevelChildren); assertCalleeMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); Object[] thirdLevelChildren= fProvider.getChildren(secondLevelChildren[0]); helper.assertCalls(new IMember[] { helper.getMethod1(), helper.getMethod2()}, thirdLevelChildren); assertCalleeMethodWrapperChildren(thirdLevelChildren); - assertTrue("third level hasChildren", fProvider.hasChildren(secondLevelChildren[0])); + assertTrue(fProvider.hasChildren(secondLevelChildren[0]), "third level hasChildren"); MethodWrapper fourthLevelMethodWrapper= helper.findMethodWrapper(helper.getMethod1(), thirdLevelChildren); - assertNotNull("method1 not found", fourthLevelMethodWrapper); + assertNotNull(fourthLevelMethodWrapper, "method1 not found"); assertEquals( - "Wrong number of fourth level children", 0, - fProvider.getChildren(fourthLevelMethodWrapper).length); + fProvider.getChildren(fourthLevelMethodWrapper).length, + "Wrong number of fourth level children"); // hasChildren should be false since the maximum depth has been reached - assertFalse("fourth level hasChildren", fProvider.hasChildren(thirdLevelChildren[0])); + assertFalse(fProvider.hasChildren(thirdLevelChildren[0]), "fourth level hasChildren"); } /* @@ -215,12 +215,12 @@ public void testGetChildrenOfCalleeRecursive() throws Exception { TreeRoot root= wrapCalleeRoot(helper.getRecursiveMethod1()); Object[] children= fProvider.getChildren(root); helper.assertCalls(new IMember[] { helper.getRecursiveMethod1()}, children); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getRecursiveMethod2()}, secondLevelChildren); assertCalleeMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); MethodWrapper thirdLevelMethodWrapper= (MethodWrapper) secondLevelChildren[0]; Object[] thirdLevelChildren= fProvider.getChildren(thirdLevelMethodWrapper); @@ -228,7 +228,7 @@ public void testGetChildrenOfCalleeRecursive() throws Exception { assertCalleeMethodWrapperChildren(thirdLevelChildren); // A recursion should have occurred, resulting in hasChildren = false - assertFalse("third level hasChildren", fProvider.hasChildren(thirdLevelChildren[0])); + assertFalse(fProvider.hasChildren(thirdLevelChildren[0]), "third level hasChildren"); } /* @@ -241,12 +241,12 @@ public void testGetChildrenOfCallerRecursive() throws Exception { TreeRoot root= wrapCallerRoot(helper.getRecursiveMethod1()); Object[] children= fProvider.getChildren(root); helper.assertCalls(new IMember[] { helper.getRecursiveMethod1()}, children); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getRecursiveMethod2()}, secondLevelChildren); assertCallerMethodWrapperChildren(secondLevelChildren); - assertTrue("second level hasChildren", fProvider.hasChildren(children[0])); + assertTrue(fProvider.hasChildren(children[0]), "second level hasChildren"); MethodWrapper thirdLevelMethodWrapper= (MethodWrapper) secondLevelChildren[0]; Object[] thirdLevelChildren= fProvider.getChildren(thirdLevelMethodWrapper); @@ -254,7 +254,7 @@ public void testGetChildrenOfCallerRecursive() throws Exception { assertCallerMethodWrapperChildren(thirdLevelChildren); // A recursion should have occurred, resulting in hasChildren = false - assertFalse("third level hasChildren", fProvider.hasChildren(thirdLevelChildren[0])); + assertFalse(fProvider.hasChildren(thirdLevelChildren[0]), "third level hasChildren"); } @Test @@ -263,7 +263,7 @@ public void testLambdaCallers() throws Exception { TreeRoot root= wrapCallerRoot(helper.getMethod1()); Object[] children= fProvider.getChildren(root); helper.assertCalls(new IMember[] { helper.getMethod1() }, children); - assertTrue("root's hasChildren", fProvider.hasChildren(root)); + assertTrue(fProvider.hasChildren(root), "root's hasChildren"); Object[] secondLevelChildren= fProvider.getChildren(children[0]); helper.assertCalls(new IMember[] { helper.getMethod2() }, secondLevelChildren); @@ -271,18 +271,18 @@ public void testLambdaCallers() throws Exception { Object[] thirdLevelChildren= fProvider.getChildren(secondLevelChildren[0]); assertEquals( - "Wrong number of third level children", 6, thirdLevelChildren.length); + 6, thirdLevelChildren.length, "Wrong number of third level children"); } private void assertCalleeMethodWrapperChildren(Object[] children) { for (Object child : children) { - assertTrue("Wrong class returned", child.getClass().getName().endsWith(".CalleeMethodWrapper")); + assertTrue(child.getClass().getName().endsWith(".CalleeMethodWrapper"), "Wrong class returned"); } } private void assertCallerMethodWrapperChildren(Object[] children) { for (Object child : children) { - assertTrue("Wrong class returned", child.getClass().getName().endsWith(".CallerMethodWrapper")); + assertTrue(child.getClass().getName().endsWith(".CallerMethodWrapper"), "Wrong class returned"); } } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyTestHelper.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyTestHelper.java index 624bcc3d384..6cb088c7dee 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyTestHelper.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/callhierarchy/CallHierarchyTestHelper.java @@ -19,7 +19,7 @@ import java.util.Collection; import java.util.List; -import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -332,8 +332,8 @@ static String x() {\ cu.createImport("java.util.function.Function", fType1, null); fMethod1= fType1.getMethod("x", EMPTY); fMethod2= fType1.getMethod("transform", new String[] { "QString;" }); - Assert.assertNotNull(fMethod1); - Assert.assertNotNull(fMethod2); + Assertions.assertNotNull(fMethod1); + Assertions.assertNotNull(fMethod2); assertBuildWithoutErrors(fPack1); } @@ -593,7 +593,7 @@ public static List convertMarkers(IMarker [] markers) throws Exception { */ protected void assertBuildWithoutErrors(IJavaElement element) throws Exception { IResource resource= element.getResource(); - Assert.assertNotNull("Given element has no resource: " + element, resource); + Assertions.assertNotNull(resource, "Given element has no resource: " + element); resource.getProject().build(IncrementalProjectBuilder.FULL_BUILD, null); assertNoErrorMarkers(resource); } @@ -607,8 +607,8 @@ protected void assertBuildWithoutErrors(IJavaElement element) throws Exception { protected void assertNoErrorMarkers(IResource resource) throws Exception { List errorMarkers = getErrorMarkers(resource); List messages = convertMarkers(errorMarkers.toArray(new IMarker[errorMarkers.size()])); - Assert.assertEquals("No error marker expected, but found markers with messages: " + messages.toString(), 0, - errorMarkers.size()); + Assertions.assertEquals(0, errorMarkers.size(), + "No error marker expected, but found markers with messages: " + messages.toString()); } /** @@ -621,8 +621,8 @@ public void assertCalls(Collection expectedMembers, Collection newCP= new ArrayList<>(); - for (IClasspathEntry cpe : jp.getRawClasspath()) { - if (cpe.getEntryKind() != IClasspathEntry.CPE_LIBRARY) { - newCP.add(cpe); - } + ArrayList newCP= new ArrayList<>(); + for (IClasspathEntry cpe : jp.getRawClasspath()) { + if (cpe.getEntryKind() != IClasspathEntry.CPE_LIBRARY) { + newCP.add(cpe); } - jp.setRawClasspath(newCP.toArray(new IClasspathEntry[newCP.size()]), null); - } - if (is60orHigher) { - JavaProjectHelper.addRTJar18(jp); - } - if (!is50orHigher) { - JavaProjectHelper.addRTJar18(jp); } + jp.setRawClasspath(newCP.toArray(new IClasspathEntry[newCP.size()]), null); + JavaProjectHelper.addRTJar18(jp); } public void runOperation(IType type, IMember[] members, IJavaElement insertBefore) throws CoreException { @@ -464,253 +454,6 @@ public void concatArrayLimit() throws Exception { compareSourceAssertCompilation(expected, a, oldCUNode); } - /** - * string concatenation - custom Array, limit elements, java 1.4 compatibility - * - * @throws Exception if test failed - */ - @Test - public void concatArrayLimit1_4() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", - true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "aBool", "anA", "floatArray", "hashMap", "intArray", "integerCollection", "list", "object", "stringArray", - "wildCollection", "charArrayMethod", "floatArrayMethod" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " Object object;\r\n" - + " A anA;\r\n" - + " int[] intArray;\r\n" - + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" - + " return \"A [AArray=\" + (AArray != null ? arrayToString(AArray, AArray.length, maxLen) : null) + \", aBool=\" + aBool + \", anA=\" + anA + \", floatArray=\" + (floatArray != null ? arrayToString(floatArray, floatArray.length, maxLen) : null) + \", hashMap=\" + (hashMap != null ? toString(hashMap.entrySet(), maxLen) : null) + \", intArray=\" + (intArray != null ? arrayToString(intArray, intArray.length, maxLen) : null) + \", integerCollection=\" + (integerCollection != null ? toString(integerCollection, maxLen) : null) + \", list=\" + (list != null ? toString(list, maxLen) : null) + \", object=\" + object + \", stringArray=\" + (stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen) : null) + \", wildCollection=\" + (wildCollection != null ? toString(wildCollection, maxLen) : null) + \", charArrayMethod()=\" + (charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, maxLen) : null) + \", floatArrayMethod()=\"\r\n" - + " + (floatArrayMethod() != null ? arrayToString(floatArrayMethod(), floatArrayMethod().length, maxLen) : null) + \"]\";\r\n" + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " buffer.append(\"[\");\r\n" + " int i = 0;\r\n" - + " for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" + " }\r\n" - + " buffer.append(iterator.next());\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" + " return buffer.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array, int len, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " len = Math.min(len, maxLen);\r\n" - + " buffer.append(\"[\");\r\n" + " for (int i = 0; i < len; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" + " }\r\n" - + " if (array instanceof float[]) {\r\n" + " buffer.append(((float[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof int[]) {\r\n" - + " buffer.append(((int[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof char[]) {\r\n" + " buffer.append(((char[]) array)[i]);\r\n" + " }\r\n" - + " if (array instanceof Object[]) {\r\n" + " buffer.append(((Object[]) array)[i]);\r\n" + " }\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" - + " return buffer.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - - /** - * string concatenation - custom Array, limit elements, java 1.4 compatibility, unique variable - * names needed - * - * @throws Exception if test failed - */ - @Test - public void concatArrayLimit1_4Unique() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " int[] intArray;\r\n" + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " List list;\r\n" - + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " Object builder;\r\n" + " Object buffer;\r\n" + " Object maxLen;\r\n" - + " Object len;\r\n" + " Object collection;\r\n" + " Object array;\r\n" + "}\r\n" + "", true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "aBool", "intArray", "stringArray", "AArray", "list", "hashMap", "wildCollection", "integerCollection", "builder", "buffer", - "maxLen", "len", "collection", "array" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " int[] intArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " Object builder;\r\n" - + " Object buffer;\r\n" - + " Object maxLen;\r\n" - + " Object len;\r\n" - + " Object collection;\r\n" - + " Object array;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen2 = 10;\r\n" - + " return \"A [aBool=\" + aBool + \", intArray=\" + (intArray != null ? arrayToString(intArray, intArray.length, maxLen2) : null) + \", stringArray=\" + (stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen2) : null) + \", AArray=\" + (AArray != null ? arrayToString(AArray, AArray.length, maxLen2) : null) + \", list=\" + (list != null ? toString(list, maxLen2) : null) + \", hashMap=\" + (hashMap != null ? toString(hashMap.entrySet(), maxLen2) : null) + \", wildCollection=\" + (wildCollection != null ? toString(wildCollection, maxLen2) : null) + \", integerCollection=\" + (integerCollection != null ? toString(integerCollection, maxLen2) : null) + \", builder=\" + builder + \", buffer=\" + buffer + \", maxLen=\" + maxLen + \", len=\" + len + \", collection=\" + collection + \", array=\" + array + \"]\";\r\n" - + " }\r\n" + " private String toString(Collection collection2, int maxLen2) {\r\n" + " StringBuffer buffer2 = new StringBuffer();\r\n" + " buffer2.append(\"[\");\r\n" - + " int i = 0;\r\n" + " for (Iterator iterator = collection2.iterator(); iterator.hasNext() && i < maxLen2; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer2.append(\", \");\r\n" - + " }\r\n" + " buffer2.append(iterator.next());\r\n" + " }\r\n" + " buffer2.append(\"]\");\r\n" + " return buffer2.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array2, int len2, int maxLen2) {\r\n" + " StringBuffer buffer2 = new StringBuffer();\r\n" + " len2 = Math.min(len2, maxLen2);\r\n" - + " buffer2.append(\"[\");\r\n" + " for (int i = 0; i < len2; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer2.append(\", \");\r\n" + " }\r\n" - + " if (array2 instanceof int[]) {\r\n" + " buffer2.append(((int[]) array2)[i]);\r\n" + " }\r\n" + " if (array2 instanceof Object[]) {\r\n" - + " buffer2.append(((Object[]) array2)[i]);\r\n" + " }\r\n" + " }\r\n" + " buffer2.append(\"]\");\r\n" + " return buffer2.toString();\r\n" + " }\r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - - /** - * string concatenation - custom Array, limit elements, java 1.5 compatibility - * - * @throws Exception if test failed - */ - @Test - public void concatArrayLimit1_5() throws Exception { - setCompilerLevels(true, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", - true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "aBool", "anA", "floatArray", "hashMap", "intArray", "integerCollection", "list", "object", "stringArray", - "wildCollection", "charArrayMethod", "floatArrayMethod" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " Object object;\r\n" - + " A anA;\r\n" - + " int[] intArray;\r\n" - + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" - + " return \"A [AArray=\" + (AArray != null ? arrayToString(AArray, AArray.length, maxLen) : null) + \", aBool=\" + aBool + \", anA=\" + anA + \", floatArray=\" + (floatArray != null ? arrayToString(floatArray, floatArray.length, maxLen) : null) + \", hashMap=\" + (hashMap != null ? toString(hashMap.entrySet(), maxLen) : null) + \", intArray=\" + (intArray != null ? arrayToString(intArray, intArray.length, maxLen) : null) + \", integerCollection=\" + (integerCollection != null ? toString(integerCollection, maxLen) : null) + \", list=\" + (list != null ? toString(list, maxLen) : null) + \", object=\" + object + \", stringArray=\" + (stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen) : null) + \", wildCollection=\" + (wildCollection != null ? toString(wildCollection, maxLen) : null) + \", charArrayMethod()=\" + (charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, maxLen) : null) + \", floatArrayMethod()=\"\r\n" - + " + (floatArrayMethod() != null ? arrayToString(floatArrayMethod(), floatArrayMethod().length, maxLen) : null) + \"]\";\r\n" + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" - + " StringBuilder builder = new StringBuilder();\r\n" + " builder.append(\"[\");\r\n" + " int i = 0;\r\n" - + " for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {\r\n" + " if (i > 0) {\r\n" + " builder.append(\", \");\r\n" + " }\r\n" - + " builder.append(iterator.next());\r\n" + " }\r\n" + " builder.append(\"]\");\r\n" + " return builder.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array, int len, int maxLen) {\r\n" + " StringBuilder builder = new StringBuilder();\r\n" + " len = Math.min(len, maxLen);\r\n" - + " builder.append(\"[\");\r\n" + " for (int i = 0; i < len; i++) {\r\n" + " if (i > 0) {\r\n" + " builder.append(\", \");\r\n" + " }\r\n" - + " if (array instanceof float[]) {\r\n" + " builder.append(((float[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof int[]) {\r\n" - + " builder.append(((int[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof char[]) {\r\n" + " builder.append(((char[]) array)[i]);\r\n" + " }\r\n" - + " if (array instanceof Object[]) {\r\n" + " builder.append(((Object[]) array)[i]);\r\n" + " }\r\n" + " }\r\n" + " builder.append(\"]\");\r\n" - + " return builder.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - - /** - * string concatenation - custom Array, limit elements, java 1.5 compatibility, unique names - * needed - * - * @throws Exception if test failed - */ - @Test - public void concatArrayLimit1_5Unique() throws Exception { - setCompilerLevels(true, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " int[] intArray;\r\n" + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " List list;\r\n" - + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " Object builder;\r\n" + " Object buffer;\r\n" + " Object maxLen;\r\n" - + " Object len;\r\n" + " Object collection;\r\n" + " Object array;\r\n" + "}\r\n" + "", true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "aBool", "intArray", "stringArray", "AArray", "list", "hashMap", "wildCollection", "integerCollection", "builder", "buffer", - "maxLen", "len", "collection", "array" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " int[] intArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " Object builder;\r\n" - + " Object buffer;\r\n" - + " Object maxLen;\r\n" - + " Object len;\r\n" - + " Object collection;\r\n" - + " Object array;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen2 = 10;\r\n" - + " return \"A [aBool=\" + aBool + \", intArray=\" + (intArray != null ? arrayToString(intArray, intArray.length, maxLen2) : null) + \", stringArray=\" + (stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen2) : null) + \", AArray=\" + (AArray != null ? arrayToString(AArray, AArray.length, maxLen2) : null) + \", list=\" + (list != null ? toString(list, maxLen2) : null) + \", hashMap=\" + (hashMap != null ? toString(hashMap.entrySet(), maxLen2) : null) + \", wildCollection=\" + (wildCollection != null ? toString(wildCollection, maxLen2) : null) + \", integerCollection=\" + (integerCollection != null ? toString(integerCollection, maxLen2) : null) + \", builder=\" + builder + \", buffer=\" + buffer + \", maxLen=\" + maxLen + \", len=\" + len + \", collection=\" + collection + \", array=\" + array + \"]\";\r\n" - + " }\r\n" + " private String toString(Collection collection2, int maxLen2) {\r\n" + " StringBuilder builder2 = new StringBuilder();\r\n" + " builder2.append(\"[\");\r\n" - + " int i = 0;\r\n" + " for (Iterator iterator = collection2.iterator(); iterator.hasNext() && i < maxLen2; i++) {\r\n" + " if (i > 0) {\r\n" - + " builder2.append(\", \");\r\n" + " }\r\n" + " builder2.append(iterator.next());\r\n" + " }\r\n" + " builder2.append(\"]\");\r\n" + " return builder2.toString();\r\n" - + " }\r\n" + " private String arrayToString(Object array2, int len2, int maxLen2) {\r\n" + " StringBuilder builder2 = new StringBuilder();\r\n" - + " len2 = Math.min(len2, maxLen2);\r\n" + " builder2.append(\"[\");\r\n" + " for (int i = 0; i < len2; i++) {\r\n" + " if (i > 0) {\r\n" + " builder2.append(\", \");\r\n" - + " }\r\n" + " if (array2 instanceof int[]) {\r\n" + " builder2.append(((int[]) array2)[i]);\r\n" + " }\r\n" + " if (array2 instanceof Object[]) {\r\n" - + " builder2.append(((Object[]) array2)[i]);\r\n" + " }\r\n" + " }\r\n" + " builder2.append(\"]\");\r\n" + " return builder2.toString();\r\n" + " }\r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - /** * string concatenation - custom Array, limit elements to 0 * @@ -1073,14 +816,38 @@ public String toString() {\r */ @Test public void concatReplace() throws Exception { - setCompilerLevels(true, false); - - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " A anA;\r\n" + " float[] floatArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" - + " float[] floatArrayMethod() {\r\n" + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " @Override\r\n" - + " public String toString() {\r\n" + " return \"A []\";\r\n" + " }\r\n" + " private String arrayToString(Object array, int len, int maxLen) {\r\n" - + " return array[0].toString();\r\n" + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" + " return collection.toString();\r\n" + " }\r\n" + " \r\n" - + "}\r\n" + "", true, null); + ICompilationUnit a= fPackageP.createCompilationUnit("A.java", """ + package p;\r + \r + import java.util.Collection;\r + import java.util.HashMap;\r + import java.util.List;\r + \r + public class A {\r + \r + A anA;\r + float[] floatArray;\r + char[] charArrayMethod() {\r + return new char[0];\r + }\r + float[] floatArrayMethod() {\r + return null;\r + }\r + List list;\r + HashMap hashMap;\r + @Override\r + public String toString() {\r + return "A []";\r + }\r + private String arrayToString(Object array, int len, int maxLen) {\r + return array[0].toString();\r + }\r + private String toString(Collection collection, int maxLen) {\r + return collection.toString();\r + }\r + \r + }\r + """, true, null); CompilationUnit oldCUNode= getCUNode(a); IMember[] members= getMembers(a.getType("A"), new String[] { "anA", "floatArray", "hashMap", "list", "charArrayMethod", "floatArrayMethod" }); @@ -1088,34 +855,41 @@ public void concatReplace() throws Exception { fSettings2.limitElements= true; runOperation(a.getType("A"), members, null); - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " A anA;\r\n" - + " float[] floatArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" - + " return \"A [anA=\" + anA + \", floatArray=\" + (floatArray != null ? arrayToString(floatArray, floatArray.length, maxLen) : null) + \", hashMap=\" + (hashMap != null ? toString(hashMap.entrySet(), maxLen) : null) + \", list=\" + (list != null ? toString(list, maxLen) : null) + \", charArrayMethod()=\" + (charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, maxLen) : null) + \", floatArrayMethod()=\" + (floatArrayMethod() != null ? arrayToString(floatArrayMethod(), floatArrayMethod().length, maxLen) : null) + \"]\";\r\n" - + " }\r\n" + " private String arrayToString(Object array, int len, int maxLen) {\r\n" + " StringBuilder builder = new StringBuilder();\r\n" + " len = Math.min(len, maxLen);\r\n" - + " builder.append(\"[\");\r\n" + " for (int i = 0; i < len; i++) {\r\n" + " if (i > 0) {\r\n" + " builder.append(\", \");\r\n" + " }\r\n" - + " if (array instanceof float[]) {\r\n" + " builder.append(((float[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof char[]) {\r\n" - + " builder.append(((char[]) array)[i]);\r\n" + " }\r\n" + " }\r\n" + " builder.append(\"]\");\r\n" + " return builder.toString();\r\n" + " }\r\n" - + " private String toString(Collection collection, int maxLen) {\r\n" + " return collection.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; + String expected= """ + package p;\r + \r + import java.util.Arrays;\r + import java.util.Collection;\r + import java.util.HashMap;\r + import java.util.Iterator;\r + import java.util.List;\r + \r + public class A {\r + \r + A anA;\r + float[] floatArray;\r + char[] charArrayMethod() {\r + return new char[0];\r + }\r + float[] floatArrayMethod() {\r + return null;\r + }\r + List list;\r + HashMap hashMap;\r + @Override\r + public String toString() {\r + final int maxLen = 10;\r + return "A [anA=" + anA + ", floatArray=" + (floatArray != null ? Arrays.toString(Arrays.copyOf(floatArray, Math.min(floatArray.length, maxLen))) : null) + ", hashMap=" + (hashMap != null ? toString(hashMap.entrySet(), maxLen) : null) + ", list=" + (list != null ? toString(list, maxLen) : null) + ", charArrayMethod()=" + (charArrayMethod() != null ? Arrays.toString(Arrays.copyOf(charArrayMethod(), Math.min(charArrayMethod().length, maxLen))) : null) + ", floatArrayMethod()=" + (floatArrayMethod() != null ? Arrays.toString(Arrays.copyOf(floatArrayMethod(), Math.min(floatArrayMethod().length, maxLen))) : null) + "]";\r + }\r + private String arrayToString(Object array, int len, int maxLen) {\r + return array[0].toString();\r + }\r + private String toString(Collection collection, int maxLen) {\r + return collection.toString();\r + }\r + \r + }\r + """; compareSourceAssertCompilation(expected, a, oldCUNode); } @@ -1328,110 +1102,6 @@ public void builderArrayLimit() throws Exception { compareSourceAssertCompilation(expected, a, oldCUNode); } - /** - * string builder - custom array, limit of elements, without java 5.0 compatibility - * - * @throws Exception if test failed - */ - @Test - public void builderArrayLimit1_4() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", - true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "aBool", "anA", "floatArray", "hashMap", "intArray", "integerCollection", "list", "object", "stringArray", - "wildCollection", "charArrayMethod", "floatArrayMethod" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - fSettings2.toStringStyle= 1; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.Iterator;\r\n" + "import java.util.List;\r\n" + "\r\n" - + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" + " return null;\r\n" + " }\r\n" - + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " buffer.append(\"A [AArray=\");\r\n" - + " buffer.append(AArray != null ? arrayToString(AArray, AArray.length, maxLen) : null);\r\n" + " buffer.append(\", aBool=\");\r\n" + " buffer.append(aBool);\r\n" - + " buffer.append(\", anA=\");\r\n" + " buffer.append(anA);\r\n" + " buffer.append(\", floatArray=\");\r\n" - + " buffer.append(floatArray != null ? arrayToString(floatArray, floatArray.length, maxLen) : null);\r\n" + " buffer.append(\", hashMap=\");\r\n" - + " buffer.append(hashMap != null ? toString(hashMap.entrySet(), maxLen) : null);\r\n" + " buffer.append(\", intArray=\");\r\n" - + " buffer.append(intArray != null ? arrayToString(intArray, intArray.length, maxLen) : null);\r\n" + " buffer.append(\", integerCollection=\");\r\n" - + " buffer.append(integerCollection != null ? toString(integerCollection, maxLen) : null);\r\n" + " buffer.append(\", list=\");\r\n" - + " buffer.append(list != null ? toString(list, maxLen) : null);\r\n" + " buffer.append(\", object=\");\r\n" + " buffer.append(object);\r\n" - + " buffer.append(\", stringArray=\");\r\n" + " buffer.append(stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen) : null);\r\n" - + " buffer.append(\", wildCollection=\");\r\n" + " buffer.append(wildCollection != null ? toString(wildCollection, maxLen) : null);\r\n" - + " buffer.append(\", charArrayMethod()=\");\r\n" + " buffer.append(charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, maxLen) : null);\r\n" - + " buffer.append(\", floatArrayMethod()=\");\r\n" + " buffer.append(floatArrayMethod() != null ? arrayToString(floatArrayMethod(), floatArrayMethod().length, maxLen) : null);\r\n" - + " buffer.append(\"]\");\r\n" + " return buffer.toString();\r\n" + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" - + " StringBuffer buffer = new StringBuffer();\r\n" + " buffer.append(\"[\");\r\n" + " int i = 0;\r\n" - + " for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" + " }\r\n" - + " buffer.append(iterator.next());\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" + " return buffer.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array, int len, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " len = Math.min(len, maxLen);\r\n" - + " buffer.append(\"[\");\r\n" + " for (int i = 0; i < len; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" + " }\r\n" - + " if (array instanceof float[]) {\r\n" + " buffer.append(((float[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof int[]) {\r\n" - + " buffer.append(((int[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof char[]) {\r\n" + " buffer.append(((char[]) array)[i]);\r\n" + " }\r\n" - + " if (array instanceof Object[]) {\r\n" + " buffer.append(((Object[]) array)[i]);\r\n" + " }\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" - + " return buffer.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - - /** - * string builder - custom array, limit of elements, without java 5.0 compatibility, unique - * names needed - * - * @throws Exception if test failed - */ - @Test - public void builderArrayLimit1_4Unique() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " int[] intArray;\r\n" + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " List list;\r\n" - + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " Object builder;\r\n" + " Object buffer;\r\n" + " Object maxLen;\r\n" - + " Object len;\r\n" + " Object collection;\r\n" + " Object array;\r\n" + "}\r\n" + "", true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "aBool", "intArray", "stringArray", "AArray", "list", "hashMap", "wildCollection", "integerCollection", "builder", "buffer", - "maxLen", "len", "collection", "array" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - fSettings2.toStringStyle= 1; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.Iterator;\r\n" + "import java.util.List;\r\n" + "\r\n" - + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " int[] intArray;\r\n" + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " Object builder;\r\n" + " Object buffer;\r\n" + " Object maxLen;\r\n" + " Object len;\r\n" - + " Object collection;\r\n" + " Object array;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" + " final int maxLen2 = 10;\r\n" + " StringBuffer buffer2 = new StringBuffer();\r\n" - + " buffer2.append(\"A [aBool=\");\r\n" + " buffer2.append(aBool);\r\n" + " buffer2.append(\", intArray=\");\r\n" - + " buffer2.append(intArray != null ? arrayToString(intArray, intArray.length, maxLen2) : null);\r\n" + " buffer2.append(\", stringArray=\");\r\n" - + " buffer2.append(stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen2) : null);\r\n" + " buffer2.append(\", AArray=\");\r\n" - + " buffer2.append(AArray != null ? arrayToString(AArray, AArray.length, maxLen2) : null);\r\n" + " buffer2.append(\", list=\");\r\n" - + " buffer2.append(list != null ? toString(list, maxLen2) : null);\r\n" + " buffer2.append(\", hashMap=\");\r\n" - + " buffer2.append(hashMap != null ? toString(hashMap.entrySet(), maxLen2) : null);\r\n" + " buffer2.append(\", wildCollection=\");\r\n" - + " buffer2.append(wildCollection != null ? toString(wildCollection, maxLen2) : null);\r\n" + " buffer2.append(\", integerCollection=\");\r\n" - + " buffer2.append(integerCollection != null ? toString(integerCollection, maxLen2) : null);\r\n" + " buffer2.append(\", builder=\");\r\n" + " buffer2.append(builder);\r\n" - + " buffer2.append(\", buffer=\");\r\n" + " buffer2.append(buffer);\r\n" + " buffer2.append(\", maxLen=\");\r\n" + " buffer2.append(maxLen);\r\n" - + " buffer2.append(\", len=\");\r\n" + " buffer2.append(len);\r\n" + " buffer2.append(\", collection=\");\r\n" + " buffer2.append(collection);\r\n" - + " buffer2.append(\", array=\");\r\n" + " buffer2.append(array);\r\n" + " buffer2.append(\"]\");\r\n" + " return buffer2.toString();\r\n" + " }\r\n" - + " private String toString(Collection collection2, int maxLen2) {\r\n" + " StringBuffer buffer2 = new StringBuffer();\r\n" + " buffer2.append(\"[\");\r\n" + " int i = 0;\r\n" - + " for (Iterator iterator = collection2.iterator(); iterator.hasNext() && i < maxLen2; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer2.append(\", \");\r\n" + " }\r\n" - + " buffer2.append(iterator.next());\r\n" + " }\r\n" + " buffer2.append(\"]\");\r\n" + " return buffer2.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array2, int len2, int maxLen2) {\r\n" + " StringBuffer buffer2 = new StringBuffer();\r\n" + " len2 = Math.min(len2, maxLen2);\r\n" - + " buffer2.append(\"[\");\r\n" + " for (int i = 0; i < len2; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer2.append(\", \");\r\n" + " }\r\n" - + " if (array2 instanceof int[]) {\r\n" + " buffer2.append(((int[]) array2)[i]);\r\n" + " }\r\n" + " if (array2 instanceof Object[]) {\r\n" - + " buffer2.append(((Object[]) array2)[i]);\r\n" + " }\r\n" + " }\r\n" + " buffer2.append(\"]\");\r\n" + " return buffer2.toString();\r\n" + " }\r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - /** * string builder - custom array, limit of elements, skip nulls, use keyword this, no one-line * blocks @@ -1840,75 +1510,6 @@ public void chainedBuilderArrayUnique() throws Exception { compareSourceAssertCompilation(expected, a, oldCUNode); } - /** - * string builder, chained calls - custom array, limit of elements, without java 5.0 - * compatibility - * - * @throws Exception if test failed - */ - @Test - public void chainedBuilderArrayLimit1_4() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", - true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "aBool", "anA", "floatArray", "hashMap", "intArray", "integerCollection", "list", "object", "stringArray", - "wildCollection", "charArrayMethod", "floatArrayMethod" }); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - fSettings2.toStringStyle= 2; - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " Object object;\r\n" - + " A anA;\r\n" - + " int[] intArray;\r\n" - + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" - + " StringBuffer buffer = new StringBuffer();\r\n" - + " buffer.append(\"A [AArray=\").append(AArray != null ? arrayToString(AArray, AArray.length, maxLen) : null).append(\", aBool=\").append(aBool).append(\", anA=\").append(anA).append(\", floatArray=\").append(floatArray != null ? arrayToString(floatArray, floatArray.length, maxLen) : null).append(\", hashMap=\").append(hashMap != null ? toString(hashMap.entrySet(), maxLen) : null).append(\", intArray=\").append(intArray != null ? arrayToString(intArray, intArray.length, maxLen) : null).append(\", integerCollection=\").append(integerCollection != null ? toString(integerCollection, maxLen) : null).append(\", list=\").append(list != null ? toString(list, maxLen) : null).append(\", object=\").append(object).append(\", stringArray=\").append(stringArray != null ? arrayToString(stringArray, stringArray.length, maxLen) : null).append(\", wildCollection=\").append(wildCollection != null ? toString(wildCollection, maxLen) : null).append(\", charArrayMethod()=\")\r\n" - + " .append(charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, maxLen) : null).append(\", floatArrayMethod()=\").append(floatArrayMethod() != null ? arrayToString(floatArrayMethod(), floatArrayMethod().length, maxLen) : null).append(\"]\");\r\n" - + " return buffer.toString();\r\n" + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" - + " buffer.append(\"[\");\r\n" + " int i = 0;\r\n" + " for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {\r\n" + " if (i > 0) {\r\n" - + " buffer.append(\", \");\r\n" + " }\r\n" + " buffer.append(iterator.next());\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" + " return buffer.toString();\r\n" + " }\r\n" - + " private String arrayToString(Object array, int len, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " len = Math.min(len, maxLen);\r\n" - + " buffer.append(\"[\");\r\n" + " for (int i = 0; i < len; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" + " }\r\n" - + " if (array instanceof float[]) {\r\n" + " buffer.append(((float[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof int[]) {\r\n" - + " buffer.append(((int[]) array)[i]);\r\n" + " }\r\n" + " if (array instanceof char[]) {\r\n" + " buffer.append(((char[]) array)[i]);\r\n" + " }\r\n" - + " if (array instanceof Object[]) {\r\n" + " buffer.append(((Object[]) array)[i]);\r\n" + " }\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" - + " return buffer.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - - /** * string builder, chained calls - custom array, JDK 1.5 compatybility * @@ -1916,7 +1517,7 @@ public void chainedBuilderArrayLimit1_4() throws Exception { */ @Test public void chainedBuilderArray1_5() throws Exception { - setCompilerLevels(true, false); + setCompilerLevels(); ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" @@ -2410,66 +2011,6 @@ public void formatLimitThis() throws Exception { compareSourceAssertCompilation(expected, a, oldCUNode); } - /** - * String.format() - custom array, limit of elements, jdk 1.4 - * - * @throws Exception if test failed - */ - @Test - public void formatLimit1_4() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " boolean aBool;\r\n" + " Object object;\r\n" + " A anA;\r\n" + " int[] intArray;\r\n" + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" + " }\r\n" + " List list;\r\n" + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "aBool", "anA", "floatArray", "hashMap", "intArray", "integerCollection", "list", "object", "stringArray", - "wildCollection", "charArrayMethod", "floatArrayMethod" }); - fSettings2.limitElements= true; - fSettings2.toStringStyle= 3; - - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.text.MessageFormat;\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " boolean aBool;\r\n" - + " Object object;\r\n" - + " A anA;\r\n" - + " int[] intArray;\r\n" - + " float[] floatArray;\r\n" - + " String[] stringArray;\r\n" - + " A[] AArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " float[] floatArrayMethod() {\r\n" - + " return null;\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int maxLen = 10;\r\n" - + " return MessageFormat.format(\"A [AArray={0}, aBool={1}, anA={2}, floatArray={3}, hashMap={4}, intArray={5}, integerCollection={6}, list={7}, object={8}, stringArray={9}, wildCollection={10}, charArrayMethod()={11}, floatArrayMethod()={12}]\", new Object[]{AArray, new Boolean(aBool), anA, floatArray, hashMap != null ? toString(hashMap.entrySet(), maxLen) : null, intArray, integerCollection != null ? toString(integerCollection, maxLen) : null, list != null ? toString(list, maxLen) : null, object, stringArray, wildCollection != null ? toString(wildCollection, maxLen) : null, charArrayMethod(), floatArrayMethod()});\r\n" - + " }\r\n" + " private String toString(Collection collection, int maxLen) {\r\n" + " StringBuffer buffer = new StringBuffer();\r\n" + " buffer.append(\"[\");\r\n" - + " int i = 0;\r\n" + " for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {\r\n" + " if (i > 0) {\r\n" + " buffer.append(\", \");\r\n" - + " }\r\n" + " buffer.append(iterator.next());\r\n" + " }\r\n" + " buffer.append(\"]\");\r\n" + " return buffer.toString();\r\n" + " }\r\n" + " \r\n" + "}\r\n" + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - /** * Custom ToString() builder - basic case * @@ -3381,113 +2922,6 @@ public String toString() {\r compareSourceAssertCompilation(expected, a, oldCUNode); } - /** - * string builder - custom array, limit elements, JDK1.4, use prefixes and suffixes for local variables and parameters - * - * @throws Exception if test failed - */ - @Test - public void builderArrayLimit1_4Prefixes() throws Exception { - setCompilerLevels(false, false); - ICompilationUnit a= fPackageP.createCompilationUnit("A.java", "package p;\r\n" + "\r\n" + "import java.util.Collection;\r\n" + "import java.util.HashMap;\r\n" + "import java.util.List;\r\n" - + "\r\n" + "public class A {\r\n" + "\r\n" + " int[] intArray;\r\n" - + " A[] AArray;\r\n" + " char[] charArrayMethod() {\r\n" + " return new char[0];\r\n" + " }\r\n" + " List list;\r\n" - + " HashMap hashMap;\r\n" + " Collection wildCollection;\r\n" + " Collection integerCollection;\r\n" + " \r\n" + "}\r\n" + "", true, null); - CompilationUnit oldCUNode= getCUNode(a); - - IMember[] members= getMembers(a.getType("A"), new String[] { "AArray", "hashMap", "intArray", "integerCollection", "list", "wildCollection", "charArrayMethod"}); - fSettings2.customArrayToString= true; - fSettings2.limitElements= true; - fSettings2.toStringStyle= 1; - - IJavaProject project= fRoot.getJavaProject(); - project.setOption(AssistOptions.OPTION_LocalPrefixes, "l_"); - project.setOption(AssistOptions.OPTION_LocalSuffixes, "_l"); - project.setOption(AssistOptions.OPTION_ArgumentPrefixes, "a_"); - project.setOption(AssistOptions.OPTION_ArgumentSuffixes, "_a"); - - runOperation(a.getType("A"), members, null); - - String expected= "package p;\r\n" - + "\r\n" - + "import java.util.Collection;\r\n" - + "import java.util.HashMap;\r\n" - + "import java.util.Iterator;\r\n" - + "import java.util.List;\r\n" - + "\r\n" - + "public class A {\r\n" - + "\r\n" - + " int[] intArray;\r\n" - + " A[] AArray;\r\n" - + " char[] charArrayMethod() {\r\n" - + " return new char[0];\r\n" - + " }\r\n" - + " List list;\r\n" - + " HashMap hashMap;\r\n" - + " Collection wildCollection;\r\n" - + " Collection integerCollection;\r\n" - + " @Override\r\n" - + " public String toString() {\r\n" - + " final int l_maxLen_l = 10;\r\n" - + " StringBuffer l_buffer_l = new StringBuffer();\r\n" - + " l_buffer_l.append(\"A [AArray=\");\r\n" - + " l_buffer_l.append(AArray != null ? arrayToString(AArray, AArray.length, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", hashMap=\");\r\n" - + " l_buffer_l.append(hashMap != null ? toString(hashMap.entrySet(), l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", intArray=\");\r\n" - + " l_buffer_l.append(intArray != null ? arrayToString(intArray, intArray.length, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", integerCollection=\");\r\n" - + " l_buffer_l.append(integerCollection != null ? toString(integerCollection, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", list=\");\r\n" - + " l_buffer_l.append(list != null ? toString(list, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", wildCollection=\");\r\n" - + " l_buffer_l.append(wildCollection != null ? toString(wildCollection, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\", charArrayMethod()=\");\r\n" - + " l_buffer_l.append(charArrayMethod() != null ? arrayToString(charArrayMethod(), charArrayMethod().length, l_maxLen_l) : null);\r\n" - + " l_buffer_l.append(\"]\");\r\n" - + " return l_buffer_l.toString();\r\n" - + " }\r\n" - + " private String toString(Collection a_collection_a, int a_maxLen_a) {\r\n" - + " StringBuffer l_buffer_l = new StringBuffer();\r\n" - + " l_buffer_l.append(\"[\");\r\n" - + " int l_i_l = 0;\r\n" - + " for (Iterator l_iterator_l = a_collection_a.iterator(); l_iterator_l.hasNext() && l_i_l < a_maxLen_a; l_i_l++) {\r\n" - + " if (l_i_l > 0) {\r\n" - + " l_buffer_l.append(\", \");\r\n" - + " }\r\n" - + " l_buffer_l.append(l_iterator_l.next());\r\n" - + " }\r\n" - + " l_buffer_l.append(\"]\");\r\n" - + " return l_buffer_l.toString();\r\n" - + " }\r\n" - + " private String arrayToString(Object a_array_a, int a_len_a, int a_maxLen_a) {\r\n" - + " StringBuffer l_buffer_l = new StringBuffer();\r\n" - + " a_len_a = Math.min(a_len_a, a_maxLen_a);\r\n" - + " l_buffer_l.append(\"[\");\r\n" - + " for (int l_i_l = 0; l_i_l < a_len_a; l_i_l++) {\r\n" - + " if (l_i_l > 0) {\r\n" - + " l_buffer_l.append(\", \");\r\n" - + " }\r\n" - + " if (a_array_a instanceof int[]) {\r\n" - + " l_buffer_l.append(((int[]) a_array_a)[l_i_l]);\r\n" - + " }\r\n" - + " if (a_array_a instanceof char[]) {\r\n" - + " l_buffer_l.append(((char[]) a_array_a)[l_i_l]);\r\n" - + " }\r\n" - + " if (a_array_a instanceof Object[]) {\r\n" - + " l_buffer_l.append(((Object[]) a_array_a)[l_i_l]);\r\n" - + " }\r\n" - + " }\r\n" - + " l_buffer_l.append(\"]\");\r\n" - + " return l_buffer_l.toString();\r\n" - + " }\r\n" - + " \r\n" - + "}\r\n" - + ""; - - compareSourceAssertCompilation(expected, a, oldCUNode); - } - /** * Custom toString() builder - alternative class, chained calls, skip nulls * diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests1.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests1.java index 71436e6fcab..333893ec06c 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests1.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests1.java @@ -13,15 +13,15 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -105,48 +105,48 @@ public class ContentProviderTests1 { public void testGetChildrenProjectWithSourceFolders() throws Exception { Object[] expectedChildren= new Object[]{fRoot1, fDotClasspathFile, dotSettings, fDotProjectFile}; Object[] actualChildren= fProvider.getChildren(fJProject2); - assertTrue("Wrong children found for project", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for project");//$NON-NLS-1$ } @Test public void testGetChildrentMidLevelFragment() throws Exception { Object[] expectedChildren= new Object[]{fPack4, fPack5}; Object[] actualChildren= fProvider.getChildren(fPack3); - assertTrue("Wrong children found for PackageFragment", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragment");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment() throws Exception { Object[] expectedChildren= new Object[]{fCU1}; Object[] actualChildren= fProvider.getChildren(fPack2); - assertTrue("Wrong children found for PackageFragment", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragment");//$NON-NLS-1$ } @Test public void testGetChildrenMidLevelFragmentInArchive() throws Exception { Object[] expectedChildren= new Object[]{fPackJunitSamplesMoney, fCUAllTests, fCUSimpleTest, fCUVectorTest }; Object[] actualChildren= fProvider.getChildren(fPackJunitSamples); - assertTrue("wrong chidren found for mid level PackageFragment in Archive", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "wrong chidren found for mid level PackageFragment in Archive");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentInArchive() throws Exception { Object[] expectedChildren= new Object[]{fCUIMoney, fCUMoney, fCUMoneyBag, fCUMoneyTest}; Object[] actualChildren= fProvider.getChildren(fPackJunitSamplesMoney); - assertTrue("wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive", compareArrays(actualChildren, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive"); //$NON-NLS-1$ } @Test public void testGetChildrenSourceFolder() throws Exception { Object[] expectedChildren = new Object[] { fPack1, fPack2, fPack3, fRoot1.getPackageFragment("")};//$NON-NLS-1$ Object[] actualChildren = fProvider.getChildren(fRoot1); - assertTrue("Wrong children found for PackageFragmentRoot", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong children found for PackageFragmentRoot");//$NON-NLS-1$ } @Test public void testGetChildrenArchive(){ Object[] expectedChildren= new Object[]{fPackJunit, fArchiveFragmentRoot.getPackageFragment("")};//$NON-NLS-1$ Object[] actualChildren= fProvider.getChildren(fArchiveFragmentRoot); - assertTrue("Wrong child found for PackageFragmentRoot Archive", compareArrays(actualChildren, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actualChildren, expectedChildren), "Wrong child found for PackageFragmentRoot Archive");//$NON-NLS-1$ } //---------------Get Parent Tests----------------------------- @@ -154,35 +154,35 @@ public void testGetChildrenSourceFolder() throws Exception { @Test public void testGetParentArchive() throws Exception { Object parent= fProvider.getParent(fArchiveFragmentRoot); - assertSame("Wrong parent found for PackageFragmentRoot Archive", parent, fJProject1);//$NON-NLS-1$ + assertSame(parent, fJProject1, "Wrong parent found for PackageFragmentRoot Archive");//$NON-NLS-1$ } @Test public void testGetParentMidLevelFragmentInArchive() throws Exception { Object expectedParent= fPackJunitSamples; Object actualParent= fProvider.getParent(fPackJunitSamplesMoney); - assertEquals("Wrong parent found for a NON top level PackageFragment in an Archive", expectedParent, actualParent);//$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a NON top level PackageFragment in an Archive");//$NON-NLS-1$ } @Test public void testGetParentTopLevelFragmentInArchive() throws Exception { Object expectedParent= fPackJunit; Object actualParent= fProvider.getParent(fPackJunitSamples); - assertEquals("Wrong parent found for a top level PackageFragment in an Archive", expectedParent, actualParent); //$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a top level PackageFragment in an Archive"); //$NON-NLS-1$ } @Test public void testGetParentTopLevelFragment() throws Exception { Object expectedParent= fRoot1; Object actualParent= fProvider.getParent(fPack3); - assertEquals("Wrong parent found for a top level PackageFragment", expectedParent, actualParent);//$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a top level PackageFragment");//$NON-NLS-1$ } @Test public void testGetParentMidLevelFragment() throws Exception { Object expectedParent= fPack3; Object actualParent= fProvider.getParent(fPack4); - assertEquals("Wrong parent found for a NON top level PackageFragment", expectedParent, actualParent);//$NON-NLS-1$ + assertEquals(expectedParent, actualParent, "Wrong parent found for a NON top level PackageFragment");//$NON-NLS-1$ } @Test @@ -195,9 +195,9 @@ public void testDeleteBottomLevelFragment() throws Exception { // Force events from dispaly while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} - assertTrue("Remove happened", fMyPart.hasRemoveHappened());//$NON-NLS-1$ - assertTrue("Correct Remove", fMyPart.getRemovedObjects().contains(fPack2));//$NON-NLS-1$ - assertEquals("No refreshes", 0, fMyPart.getRefreshedObject().size());//$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove happened");//$NON-NLS-1$ + assertTrue(fMyPart.getRemovedObjects().contains(fPack2), "Correct Remove");//$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refreshes");//$NON-NLS-1$ } @Test @@ -212,9 +212,9 @@ public void testAddBottomLevelFragment() throws Exception { // Force events from dispaly while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} - assertTrue("Add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ - assertEquals("Correct Add", test, fMyPart.getAddedObject()); //$NON-NLS-1$ - assertEquals("No refreshes", 0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasAddHappened(), "Add happened"); //$NON-NLS-1$ + assertEquals(test, fMyPart.getAddedObject(), "Correct Add"); //$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refreshes"); //$NON-NLS-1$ } @Test @@ -227,7 +227,7 @@ public void testChangedTopLevelPackageFragment() throws Exception { // Force events from display while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} - assertEquals("No refresh happened", 0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refresh happened"); //$NON-NLS-1$ } @Test @@ -241,7 +241,7 @@ public void testChangeBottomLevelPackageFragment() throws Exception { // Force events from display while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} - assertEquals("No refresh happened", 0, fMyPart.getRefreshedObject().size());//$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refresh happened");//$NON-NLS-1$ } @Test @@ -255,7 +255,7 @@ public void testRemoveCUsFromPackageFragment() throws Exception { while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} // removing more than one CU now results in a refresh. - assertEquals("One refresh", 1, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "One refresh"); //$NON-NLS-1$ } @Test @@ -268,9 +268,9 @@ public void testRemoveCUFromPackageFragment() throws Exception { // Force events from display while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) {} - assertTrue("Remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Correct refresh", fMyPart.getRemovedObjects().contains(fCU2)); //$NON-NLS-1$ - assertEquals("No refreshes", 0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRemovedObjects().contains(fCU2), "Correct refresh"); //$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refreshes"); //$NON-NLS-1$ } @Test @@ -282,11 +282,11 @@ public void testBug65240() throws Exception { fJProject2.setRawClasspath(new IClasspathEntry[] {element.getClasspathEntry()}, null); Object[] expectedChildren= new Object[]{fPack4.getResource(), fPack5}; Object[] children= fProvider.getChildren(fPack3.getResource()); - assertTrue("Wrong children found for folder", compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for folder");//$NON-NLS-1$ expectedChildren= new Object[]{fPack1.getResource(), fPack2.getResource(), fPack3.getResource()}; children= fProvider.getChildren(fRoot1); - assertTrue("Wrong children found for source folder", compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for source folder");//$NON-NLS-1$ } // public void testAddWorkingCopyCU() throws Exception { @@ -323,7 +323,7 @@ public void testBug65240() throws Exception { // } - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); assertNotNull(fWorkspace); @@ -337,8 +337,8 @@ public void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");//$NON-NLS-1$//$NON-NLS-2$ fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project1 null", fJProject1);//$NON-NLS-1$ - assertNotNull("project2 null", fJProject2);//$NON-NLS-1$ + assertNotNull(fJProject1, "project1 null");//$NON-NLS-1$ + assertNotNull(fJProject2, "project2 null");//$NON-NLS-1$ fJProject1.setRawClasspath(new IClasspathEntry[0], null); @@ -362,22 +362,22 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ // Set up project #1 : External Jar and zip file IPackageFragmentRoot jdk= JavaProjectHelper.addVariableRTJar(fJProject1, "JRE_LIB_TEST", null, null);//$NON-NLS-1$ - assertNotNull("jdk not found", jdk);//$NON-NLS-1$ + assertNotNull(jdk, "jdk not found");//$NON-NLS-1$ java.io.File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); - assertNotNull("junit src not found", junitSrcArchive);//$NON-NLS-1$ - assertTrue("junit src not found", junitSrcArchive.exists());//$NON-NLS-1$ + assertNotNull(junitSrcArchive, "junit src not found");//$NON-NLS-1$ + assertTrue(junitSrcArchive.exists(), "junit src not found");//$NON-NLS-1$ fArchiveFragmentRoot= JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);//$NON-NLS-1$ - assertTrue("Unable to create zipfile archive",fArchiveFragmentRoot.exists());//$NON-NLS-1$ + assertTrue(fArchiveFragmentRoot.exists(),"Unable to create zipfile archive");//$NON-NLS-1$ fPackJunit= fArchiveFragmentRoot.getPackageFragment("junit");//$NON-NLS-1$ fPackJunitSamples= fArchiveFragmentRoot.getPackageFragment("junit.samples");//$NON-NLS-1$ fPackJunitSamplesMoney= fArchiveFragmentRoot.getPackageFragment("junit.samples.money");//$NON-NLS-1$ - assertNotNull("creating fPackJunit", fPackJunit);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamples", fPackJunitSamples);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamplesMoney",fPackJunitSamplesMoney);//$NON-NLS-1$ + assertNotNull(fPackJunit, "creating fPackJunit");//$NON-NLS-1$ + assertNotNull(fPackJunitSamples, "creating fPackJunitSamples");//$NON-NLS-1$ + assertNotNull(fPackJunitSamplesMoney,"creating fPackJunitSamplesMoney");//$NON-NLS-1$ fCUIMoney= fPackJunitSamplesMoney.getCompilationUnit("IMoney.java");//$NON-NLS-1$ fCUMoney= fPackJunitSamplesMoney.getCompilationUnit("Money.java");//$NON-NLS-1$ @@ -431,7 +431,7 @@ public void setUpMockView() throws Exception { assertNotNull(fProvider); } - @After + @AfterEach public void tearDown() throws Exception { fArchiveFragmentRoot.close(); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests2.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests2.java index 99914fff34c..ac2ef654858 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests2.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests2.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -97,62 +97,62 @@ public class ContentProviderTests2{ public void testGetChildrenProject() throws Exception{ Object[] expectedChildren= new Object[]{fPack1, fPack2, fPack3, fRoot1.getPackageFragment(""), fFile1, fFile2, dotSettings, fInternalRoot1,jdk}; //$NON-NLS-1$ Object[] children= fProvider.getChildren(fJProject3); - assertTrue("Wrong children found for project", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for project"); //$NON-NLS-1$ } @Test public void testGetChildrentMidLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{fPack4, fPack5}; Object[] children= fProvider.getChildren(fPack3); - assertTrue("Wrong children found for PackageFragment",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{}; Object[] children= fProvider.getChildren(fPack1); - assertTrue("Wrong children found for PackageFragment",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentWithCU() throws Exception{ Object[] expectedChildren= new Object[]{fCU1}; Object[] children= fProvider.getChildren(fPack2); - assertTrue("Wrong children found for PackageFragment with CU",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with CU"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentFile() throws Exception{ Object[] expectedChildren= new Object[]{}; Object[] children= fProvider.getChildren(fPack1); - assertTrue("Wrong children found for PackageFragment with File",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with File"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment2() throws Exception{ Object[] expectedChildren= new Object[]{fCU2}; Object[] children= fProvider.getChildren(fPack6); - assertTrue("Wrong children found for PackageFragment",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment"); //$NON-NLS-1$ } @Test public void testGetChildrenMidLevelFragmentInInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fC}; Object[] children= fProvider.getChildren(fB); - assertTrue("wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Internal Archive", compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Internal Archive");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentInInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fYClassFile}; Object[] children= fProvider.getChildren(fY); - assertTrue("wrong children found for a bottom PackageFragment in PackageFragmentRoot Internal Archive", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "wrong children found for a bottom PackageFragment in PackageFragmentRoot Internal Archive"); //$NON-NLS-1$ } public void getChildrenInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fX,fA, fInternalRoot1.getPackageFragment("")}; //$NON-NLS-1$ Object[] children= fProvider.getChildren(fInternalRoot1); - assertTrue("Wrong child found for PackageFragmentRoot Internal Archive", compareArrays(children,expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong child found for PackageFragmentRoot Internal Archive");//$NON-NLS-1$ } //---------------Get Parent Tests----------------------------- @@ -160,40 +160,40 @@ public void getChildrenInternalArchive() throws Exception{ @Test public void testGetParentArchive() throws Exception{ Object parent= fProvider.getParent(fInternalRoot1); - assertSame("Wrong parent found for PackageFragmentRoot Archive", parent, fJProject3); //$NON-NLS-1$ + assertSame(parent, fJProject3, "Wrong parent found for PackageFragmentRoot Archive"); //$NON-NLS-1$ } @Test public void testGetParentMidLevelFragmentInArchive() throws Exception{ Object expectedParent= fB; Object parent= fProvider.getParent(fC); - assertEquals("Wrong parent found for a NON top level PackageFragment in an Archive", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment in an Archive"); //$NON-NLS-1$ } @Test public void testGetParentTopLevelFragmentInArchive() throws Exception{ Object expectedParent= fInternalRoot1; Object parent= fProvider.getParent(fA); - assertEquals("Wrong parent found for a top level PackageFragment in an Archive", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment in an Archive"); //$NON-NLS-1$ } @Test public void testGetParentTopLevelFragment() throws Exception{ Object expectedParent= fJProject3; Object parent= fProvider.getParent(fPack3); - assertEquals("Wrong parent found for a top level PackageFragment", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment"); //$NON-NLS-1$ } @Test public void testGetParentMidLevelFragment() throws Exception{ Object expectedParent= fPack3; Object parent= fProvider.getParent(fPack5); - assertEquals("Wrong parent found for a NON top level PackageFragment", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment"); //$NON-NLS-1$ } //-------------------Set up methods-------------------------------- - @Before + @BeforeEach public void setUp() throws Exception { @@ -206,7 +206,7 @@ public void setUp() throws Exception { //create project fJProject3= JavaProjectHelper.createJavaProject("TestProject3", "bin"); //$NON-NLS-1$ //$NON-NLS-2$ - assertNotNull("project3 null", fJProject3); //$NON-NLS-1$ + assertNotNull(fJProject3, "project3 null"); //$NON-NLS-1$ for (Object object : fJProject3.getNonJavaResources()) { if(object instanceof IFile){ @@ -228,17 +228,17 @@ else if (".project".equals(file.getName())) //$NON-NLS-1$ //add rt.jar jdk= JavaProjectHelper.addVariableRTJar(fJProject3, "JRE_LIB_TEST", null, null); //$NON-NLS-1$ - assertNotNull("jdk not found", jdk); //$NON-NLS-1$ + assertNotNull(jdk, "jdk not found"); //$NON-NLS-1$ //create the PackageFragmentRoot that represents the project as source folder fRoot1= JavaProjectHelper.addSourceContainer(fJProject3, ""); //$NON-NLS-1$ - assertNotNull("getting default package", fRoot1); //$NON-NLS-1$ + assertNotNull(fRoot1, "getting default package"); //$NON-NLS-1$ //set up project #3: file system structure with project as source folder //add an internal jar File myInternalLibJar= JavaTestPlugin.getDefault().getFileInPlugin(new Path("testresources/myinternallib.jar")); //$NON-NLS-1$ - assertNotNull("lib not found", myInternalLibJar); //$NON-NLS-1$ - assertTrue("lib not found", myInternalLibJar.exists()); //$NON-NLS-1$ + assertNotNull(myInternalLibJar, "lib not found"); //$NON-NLS-1$ + assertTrue(myInternalLibJar.exists(), "lib not found"); //$NON-NLS-1$ fInternalRoot1= JavaProjectHelper.addLibraryWithImport(fJProject3, Path.fromOSString(myInternalLibJar.getPath()), null, null); //create internal PackageFragments @@ -294,7 +294,7 @@ public void setUpMockView() throws Exception { assertNotNull(fProvider); } - @After + @AfterEach public void tearDown() throws Exception { fInternalRoot1.close(); JavaProjectHelper.delete(fJProject3); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests3.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests3.java index abfbc3e8ff2..c6dcf4b94c1 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests3.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests3.java @@ -13,18 +13,18 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -111,7 +111,7 @@ public class ContentProviderTests3{ public void testGetChildrenProjectWithSourceFolders() throws Exception{ Object[] expectedChildren= new Object[]{fRoot1, fFile1, fFile2, dotSettings, jdk}; Object[] children= fProvider.getChildren(fJProject2); - assertTrue("Wrong children found for project with folding", compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for project with folding");//$NON-NLS-1$ } @@ -119,14 +119,14 @@ public void testGetChildrenProjectWithSourceFolders() throws Exception{ public void testGetChildrentMidLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{fPack4, fPack6}; Object[] children= fProvider.getChildren(fPack3); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding");//$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{}; Object[] children= fProvider.getChildren(fPack1); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding");//$NON-NLS-1$ } @@ -134,28 +134,28 @@ public void testGetChildrenBottomLevelFragment() throws Exception{ public void testGetChildrenBottomLevelFragmentWithCU() throws Exception{ Object[] expectedChildren= new Object[]{fCU1}; Object[] children= fProvider.getChildren(fPack2); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentInArchive() throws Exception{ Object[] expectedChildren= new Object[]{fCUIMoney, fCUMoney, fCUMoneyBag, fCUMoneyTest}; Object[] children= fProvider.getChildren(fPackJunitSamplesMoney); - assertTrue("wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "wrong children found for a bottom PackageFragment in PackageFragmentRoot Archive with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenSource() throws Exception{ Object[] expectedChildren= new Object[]{fPack1,fPack2,fPack3, fRoot1.getPackageFragment("")};//$NON-NLS-1$ Object[] children= fProvider.getChildren(fRoot1); - assertTrue("Wrong children found for PackageFragmentRoot with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for PackageFragmentRoot with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenArchive(){ Object[] expectedChildren= new Object[]{fPackJunit, fArchiveFragmentRoot.getPackageFragment("")};//$NON-NLS-1$ Object[] children= fProvider.getChildren(fArchiveFragmentRoot); - assertTrue("Wrong child found for PackageFragmentRoot Archive with folding", compareArrays(children,expectedChildren));//$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong child found for PackageFragmentRoot Archive with folding");//$NON-NLS-1$ } @@ -164,28 +164,28 @@ public void testGetChildrenArchive(){ @Test public void testGetParentArchive() throws Exception{ Object parent= fProvider.getParent(fArchiveFragmentRoot); - assertSame("Wrong parent found for PackageFragmentRoot Archive with folding", parent, fJProject1);//$NON-NLS-1$ + assertSame(parent, fJProject1, "Wrong parent found for PackageFragmentRoot Archive with folding");//$NON-NLS-1$ } @Test public void testGetParentTopLevelFragmentInArchive() throws Exception{ Object expectedParent= fPackJunit; Object parent= fProvider.getParent(fPackJunitSamples); - assertEquals("Wrong parent found for a top level PackageFragment in an Archive with folding", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment in an Archive with folding"); //$NON-NLS-1$ } @Test public void testGetParentTopLevelFragment() throws Exception{ Object expectedParent= fRoot1; Object parent= fProvider.getParent(fPack3); - assertEquals("Wrong parent found for a top level PackageFragment with folding", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetParentFoldedBottomFragment() throws Exception{ Object expectedParent= fRoot1; Object parent= fProvider.getParent(fPack3); - assertEquals("Wrong parent found for a top level PackageFragment with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment with folding");//$NON-NLS-1$ } @@ -193,7 +193,7 @@ public void testGetParentFoldedBottomFragment() throws Exception{ public void testGetParentMidLevelFragment() throws Exception{ Object expectedParent= fPack3; Object parent= fProvider.getParent(fPack4); - assertEquals("Wrong parent found for a NON top level PackageFragment with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment with folding");//$NON-NLS-1$ } @Test @@ -207,9 +207,9 @@ public void testDeleteBottomLevelFragmentFolding() throws Exception { //force events from dispaly while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct Refresh", fMyPart.wasObjectRefreshed(fRoot1)); //$NON-NLS-1$ - assertEquals("Single refresh", 1, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.wasObjectRefreshed(fRoot1), "Correct Refresh"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Single refresh"); //$NON-NLS-1$ } @Test @@ -225,10 +225,10 @@ public void testAddBottomLevelFragmentFolding() throws Exception { while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertFalse("No add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("Correct Refresh", fMyPart.wasObjectRefreshed(fRoot1)); //$NON-NLS-1$ - assertEquals("Single refresh", 1, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertFalse(fMyPart.hasAddHappened(), "No add happened"); //$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.wasObjectRefreshed(fRoot1), "Correct Refresh"); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "Single refresh"); //$NON-NLS-1$ } @Test @@ -242,7 +242,7 @@ public void testChangedTopLevelPackageFragmentFolding() throws Exception { while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertEquals("No refreshs", 0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refreshs"); //$NON-NLS-1$ } @Test @@ -256,7 +256,7 @@ public void testChangeBottomLevelPackageFragmentFolding() throws Exception { while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertEquals("No refreshs",0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertEquals(0,fMyPart.getRefreshedObject().size(), "No refreshs"); //$NON-NLS-1$ } @Test @@ -272,7 +272,7 @@ public void testRemoveCUsFromPackageFragment() throws Exception{ } // removing more than one CU now results in a refresh. - assertEquals("One refresh", 1, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertEquals(1, fMyPart.getRefreshedObject().size(), "One refresh"); //$NON-NLS-1$ } @Test @@ -287,16 +287,16 @@ public void testRemoveCUFromPackageFragment() throws Exception { while(fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertTrue("Remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ - assertTrue("Correct refresh", fMyPart.getRemovedObjects().contains(fCU2)); //$NON-NLS-1$ - assertEquals("No refreshes", 0, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRemoveHappened(), "Remove happened"); //$NON-NLS-1$ + assertTrue(fMyPart.getRemovedObjects().contains(fCU2), "Correct refresh"); //$NON-NLS-1$ + assertEquals(0, fMyPart.getRefreshedObject().size(), "No refreshes"); //$NON-NLS-1$ } /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); @@ -309,8 +309,8 @@ public void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");//$NON-NLS-1$//$NON-NLS-2$ fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project1 null", fJProject1);//$NON-NLS-1$ - assertNotNull("project2 null", fJProject2);//$NON-NLS-1$ + assertNotNull(fJProject1, "project1 null");//$NON-NLS-1$ + assertNotNull(fJProject2, "project2 null");//$NON-NLS-1$ for (Object object : fJProject2.getNonJavaResources()) { if(object instanceof IFile){ @@ -332,12 +332,12 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ //set up project #1 : External Jar and zip file jdk= JavaProjectHelper.addVariableRTJar(fJProject1, "JRE_LIB_TEST", null, null);//$NON-NLS-1$ - assertNotNull("jdk not found", jdk);//$NON-NLS-1$ + assertNotNull(jdk, "jdk not found");//$NON-NLS-1$ File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC_381); - assertNotNull("junit src not found", junitSrcArchive);//$NON-NLS-1$ - assertTrue("junit src not found", junitSrcArchive.exists());//$NON-NLS-1$ + assertNotNull(junitSrcArchive, "junit src not found");//$NON-NLS-1$ + assertTrue(junitSrcArchive.exists(), "junit src not found");//$NON-NLS-1$ fArchiveFragmentRoot= JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", junitSrcArchive, JavaProjectHelper.JUNIT_SRC_ENCODING);//$NON-NLS-1$ @@ -351,15 +351,15 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ fPackJunitTextUi= fArchiveFragmentRoot.getPackageFragment("junit.textui");//$NON-NLS-1$ fPackJunitUi= fArchiveFragmentRoot.getPackageFragment("junit.ui");//$NON-NLS-1$ - assertNotNull("creating fPackJunit", fPackJunit);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamples", fPackJunitSamples);//$NON-NLS-1$ - assertNotNull("creating fPackJunitSamplesMoney",fPackJunitSamplesMoney);//$NON-NLS-1$ - assertNotNull("", fPackJunitExtentions);//$NON-NLS-1$ - assertNotNull("",fPackJunitFramework);//$NON-NLS-1$ - assertNotNull("",fPackJunitRunner);//$NON-NLS-1$ - assertNotNull("",fPackJunitTests);//$NON-NLS-1$ - assertNotNull("",fPackJunitTextUi);//$NON-NLS-1$ - assertNotNull("",fPackJunitUi);//$NON-NLS-1$ + assertNotNull(fPackJunit, "creating fPackJunit");//$NON-NLS-1$ + assertNotNull(fPackJunitSamples, "creating fPackJunitSamples");//$NON-NLS-1$ + assertNotNull(fPackJunitSamplesMoney,"creating fPackJunitSamplesMoney");//$NON-NLS-1$ + assertNotNull(fPackJunitExtentions, "");//$NON-NLS-1$ + assertNotNull(fPackJunitFramework,"");//$NON-NLS-1$ + assertNotNull(fPackJunitRunner,"");//$NON-NLS-1$ + assertNotNull(fPackJunitTests,"");//$NON-NLS-1$ + assertNotNull(fPackJunitTextUi,"");//$NON-NLS-1$ + assertNotNull(fPackJunitUi,"");//$NON-NLS-1$ fCUIMoney= fPackJunitSamplesMoney.getCompilationUnit("IMoney.java");//$NON-NLS-1$ fCUMoney= fPackJunitSamplesMoney.getCompilationUnit("Money.java");//$NON-NLS-1$ @@ -367,8 +367,8 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ fCUMoneyTest= fPackJunitSamplesMoney.getCompilationUnit("MoneyTest.java");//$NON-NLS-1$ File mylibJar= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.MYLIB); - assertNotNull("lib not found", mylibJar);//$NON-NLS-1$ - assertTrue("lib not found", mylibJar.exists());//$NON-NLS-1$ + assertNotNull(mylibJar, "lib not found");//$NON-NLS-1$ + assertTrue(mylibJar.exists(), "lib not found");//$NON-NLS-1$ JavaProjectHelper.addLibraryWithImport(fJProject1, Path.fromOSString(mylibJar.getPath()), null, null); //set up project #2: file system structure with in a source folder @@ -422,7 +422,7 @@ public void setUpMockView() throws Exception{ assertNotNull(fProvider); } - @After + @AfterEach public void tearDown() throws Exception { fArchiveFragmentRoot.close(); JavaProjectHelper.delete(fJProject1); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests4.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests4.java index 740619d49ef..8eec99f796e 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests4.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests4.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.File; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -101,62 +101,62 @@ public class ContentProviderTests4{ public void testGetChildrenProject() throws Exception{ Object[] expectedChildren= new Object[]{fPack1, fPack2, fPack3, fDefaultPackage, fFile1, fFile2, dotSettings, fInternalRoot1,jdk}; Object[] children= fProvider.getChildren(fJProject3); - assertTrue("Wrong children found for project with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for project with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenDefaultProject(){ Object[] expectedChildren= new Object[]{fCUinDefault}; Object[] children= fProvider.getChildren(fDefaultPackage); - assertTrue("Wrong children found for default package with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong children found for default package with folding"); //$NON-NLS-1$ } @Test public void testGetChildrentMidLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{fPack4, fPack6}; Object[] children= fProvider.getChildren(fPack3); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragment() throws Exception{ Object[] expectedChildren= new Object[]{}; Object[] children= fProvider.getChildren(fPack1); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentWithCU() throws Exception{ Object[] expectedChildren= new Object[]{fCU1}; Object[] children= fProvider.getChildren(fPack2); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmenWithCU2() throws Exception{ Object[] expectedChildren= new Object[]{fCU2}; Object[] children= fProvider.getChildren(fPack6); - assertTrue("Wrong children found for PackageFragment with folding",compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren),"Wrong children found for PackageFragment with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenMidLevelFragmentInInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fC, fD, fAClassFile}; Object[] children= fProvider.getChildren(fA); - assertTrue("wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Internal Archive with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "wrong children found for a NON bottom PackageFragment in PackageFragmentRoot Internal Archive with folding"); //$NON-NLS-1$ } @Test public void testGetChildrenBottomLevelFragmentInInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fYClassFile}; Object[] children= fProvider.getChildren(fY); - assertTrue("wrong children found for a bottom PackageFragment in PackageFragmentRoot Internal Archive with folding", compareArrays(children, expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "wrong children found for a bottom PackageFragment in PackageFragmentRoot Internal Archive with folding"); //$NON-NLS-1$ } public void getChildrenInternalArchive() throws Exception{ Object[] expectedChildren= new Object[]{fX,fA, fInternalRoot1.getPackageFragment("")}; //$NON-NLS-1$ Object[] children= fProvider.getChildren(fInternalRoot1); - assertTrue("Wrong child found for PackageFragmentRoot Internal Archive with folding", compareArrays(children,expectedChildren)); //$NON-NLS-1$ + assertTrue(compareArrays(children, expectedChildren), "Wrong child found for PackageFragmentRoot Internal Archive with folding"); //$NON-NLS-1$ } //---------------Get Parent Tests----------------------------- @@ -164,47 +164,47 @@ public void getChildrenInternalArchive() throws Exception{ @Test public void testGetParentArchive() throws Exception{ Object parent= fProvider.getParent(fInternalRoot1); - assertSame("Wrong parent found for PackageFragmentRoot Archive with folding", parent, fJProject3);//$NON-NLS-1$ + assertSame(parent, fJProject3, "Wrong parent found for PackageFragmentRoot Archive with folding");//$NON-NLS-1$ } @Test public void testGetParentMidLevelFragmentInArchive() throws Exception{ Object expectedParent= fA; Object parent= fProvider.getParent(fC); - assertEquals("Wrong parent found for a NON top level PackageFragment in an Archive with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment in an Archive with folding");//$NON-NLS-1$ } @Test public void testGetParentTopLevelFragmentInArchive() throws Exception{ Object expectedParent= fInternalRoot1; Object parent= fProvider.getParent(fA); - assertEquals("Wrong parent found for a top level PackageFragment in an Archive with folding", expectedParent, parent); //$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment in an Archive with folding"); //$NON-NLS-1$ } @Test public void testGetParentTopLevelFragment() throws Exception{ Object expectedParent= fJProject3; Object parent= fProvider.getParent(fPack3); - assertEquals("Wrong parent found for a top level PackageFragment with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a top level PackageFragment with folding");//$NON-NLS-1$ } @Test public void testGetParentMidLevelFragment() throws Exception{ Object expectedParent= fPack3; Object parent= fProvider.getParent(fPack6); - assertEquals("Wrong parent found for a NON top level PackageFragment with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment with folding");//$NON-NLS-1$ } @Test public void testGetParentMidLevelFragment2() throws Exception{ Object expectedParent= fPack3; Object parent= fProvider.getParent(fPack5); - assertEquals("Wrong parent found for a NON top level PackageFragment with folding", expectedParent, parent);//$NON-NLS-1$ + assertEquals(expectedParent, parent, "Wrong parent found for a NON top level PackageFragment with folding");//$NON-NLS-1$ } //-------------------Set up methods-------------------------------- - @Before + @BeforeEach public void setUp() throws Exception { fWorkspace= ResourcesPlugin.getWorkspace(); assertNotNull(fWorkspace); @@ -215,7 +215,7 @@ public void setUp() throws Exception { //create project fJProject3 = JavaProjectHelper.createJavaProject("TestProject3", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project3 null", fJProject3);//$NON-NLS-1$ + assertNotNull(fJProject3, "project3 null");//$NON-NLS-1$ for (Object object : fJProject3.getNonJavaResources()) { if (object instanceof IFile) { @@ -237,11 +237,11 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ //add rt.jar jdk= JavaProjectHelper.addVariableRTJar(fJProject3, "JRE_LIB_TEST", null, null);//$NON-NLS-1$ - assertNotNull("jdk not found", jdk);//$NON-NLS-1$ + assertNotNull(jdk, "jdk not found");//$NON-NLS-1$ //create the PackageFragmentRoot that represents the project as source folder fRoot1= JavaProjectHelper.addSourceContainer(fJProject3, "");//$NON-NLS-1$ - assertNotNull("getting default package", fRoot1);//$NON-NLS-1$ + assertNotNull(fRoot1, "getting default package");//$NON-NLS-1$ fDefaultPackage= fRoot1.createPackageFragment("",true,null);//$NON-NLS-1$ fCUinDefault= fDefaultPackage.createCompilationUnit("Object.java","",true, null);//$NON-NLS-1$//$NON-NLS-2$ @@ -249,8 +249,8 @@ else if (".project".equals(file.getName()))//$NON-NLS-1$ //set up project #3: file system structure with project as source folder //add an internal jar myInternalLibJar = JavaTestPlugin.getDefault().getFileInPlugin(new Path("testresources/myinternallib.jar"));//$NON-NLS-1$ - assertNotNull("lib not found", myInternalLibJar); //$NON-NLS-1$ - assertTrue("lib not found", myInternalLibJar.exists()); //$NON-NLS-1$ + assertNotNull(myInternalLibJar, "lib not found"); //$NON-NLS-1$ + assertTrue(myInternalLibJar.exists(), "lib not found"); //$NON-NLS-1$ fInternalRoot1= JavaProjectHelper.addLibraryWithImport(fJProject3, Path.fromOSString(myInternalLibJar.getPath()), null, null); //create internal PackageFragments @@ -307,7 +307,7 @@ public void setUpMockView() throws Exception { assertNotNull(fProvider); } - @After + @AfterEach public void tearDown() throws Exception { fInternalRoot1.close(); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests5.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests5.java index 68adfeac7f2..6423acf5025 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests5.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests5.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -78,7 +78,7 @@ public class ContentProviderTests5{ private IFile fDotProject; private IPackageFragmentRoot jdk; - @Before + @BeforeEach public void setUp() throws Exception { IWorkspace workspace= ResourcesPlugin.getWorkspace(); @@ -112,7 +112,7 @@ else if (".project".equals(file.getName())) //add rt.jar jdk= JavaProjectHelper.addVariableRTJar(fJProject, "JRE_LIB_TEST", null, null); - assertNotNull("jdk not found", jdk); + assertNotNull(jdk, "jdk not found"); setUpView(); } @@ -140,7 +140,7 @@ private void setFolding(boolean fold) { JavaPlugin.getDefault().getPreferenceStore().setValue(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, fold); } - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject); @@ -266,7 +266,7 @@ public void testInclExcl1() throws Exception { //bug 35851, 66694 } private void assertEqualElements(Object[] expected, Object[] actual) { - assertEquals("array length", expected.length, actual.length); + assertEquals(expected.length, actual.length, "array length"); exp: for (int i= 0; i < expected.length; i++) { Object e= expected[i]; for (Object a : actual) { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests6.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests6.java index c5912eeac6f..16f6c2d93db 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests6.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests6.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.ByteArrayInputStream; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -90,7 +90,7 @@ public void testAddFileToClassFolder() throws Exception { while (fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertFalse("No add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasAddHappened(), "No add happened"); //$NON-NLS-1$ assertions(); } @@ -111,7 +111,7 @@ public void testAddFolderToClassFolder() throws Exception { while (fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertFalse("No add happened", fMyPart.hasAddHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasAddHappened(), "No add happened"); //$NON-NLS-1$ assertions(); } @@ -133,7 +133,7 @@ public void testRemoveFileFromClassFolder() throws Exception { while (fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertFalse("No remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRemoveHappened(), "No remove happened"); //$NON-NLS-1$ assertions(); } @@ -155,7 +155,7 @@ public void testRemoveFolderFromClassFolder() throws Exception { while (fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertFalse("No remove happened", fMyPart.hasRemoveHappened()); //$NON-NLS-1$ + assertFalse(fMyPart.hasRemoveHappened(), "No remove happened"); //$NON-NLS-1$ assertions(); } @@ -175,21 +175,21 @@ public void testChangeClassInProject() throws Exception { while (fMyPart.getTreeViewer().getControl().getDisplay().readAndDispatch()) { } - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertFalse("Project not refreshed", fMyPart.wasObjectRefreshed(fJProject)); //$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertFalse(fMyPart.wasObjectRefreshed(fJProject), "Project not refreshed"); //$NON-NLS-1$ } private void assertions() { - assertTrue("Refresh happened", fMyPart.hasRefreshHappened()); //$NON-NLS-1$ - assertTrue("LibraryContainer Refreshed", fMyPart.wasObjectRefreshed(new LibraryContainer(fJProject))); //$NON-NLS-1$ - assertTrue("Resource Refreshed", fMyPart.wasObjectRefreshed(classFolder.getResource())); //$NON-NLS-1$ - assertEquals("Number of refreshed objects", 2, fMyPart.getRefreshedObject().size()); //$NON-NLS-1$ + assertTrue(fMyPart.hasRefreshHappened(), "Refresh happened"); //$NON-NLS-1$ + assertTrue(fMyPart.wasObjectRefreshed(new LibraryContainer(fJProject)), "LibraryContainer Refreshed"); //$NON-NLS-1$ + assertTrue(fMyPart.wasObjectRefreshed(classFolder.getResource()), "Resource Refreshed"); //$NON-NLS-1$ + assertEquals(2, fMyPart.getRefreshedObject().size(), "Number of refreshed objects"); //$NON-NLS-1$ } /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { IWorkspaceDescription workspaceDesc= ResourcesPlugin.getWorkspace().getDescription(); fEnableAutoBuildAfterTesting= workspaceDesc.isAutoBuilding(); @@ -197,11 +197,11 @@ public void setUp() throws Exception { CoreUtility.setAutoBuilding(false); fJProject= JavaProjectHelper.createJavaProject("TestProject", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project null", fJProject);//$NON-NLS-1$ + assertNotNull(fJProject, "project null");//$NON-NLS-1$ //set up project : Add classFolder classFolder= JavaProjectHelper.addClassFolder(fJProject, "classFolder", null, null); //$NON-NLS-1$ - assertNotNull("class folder null", classFolder); //$NON-NLS-1$ + assertNotNull(classFolder, "class folder null"); //$NON-NLS-1$ //set up the mock view setUpMockView(); @@ -223,7 +223,7 @@ public void setUpMockView() throws Exception{ assertNotNull(fProvider); } - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject); if (fEnableAutoBuildAfterTesting) diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests7.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests7.java index 75471950237..988a3333948 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests7.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/ContentProviderTests7.java @@ -13,12 +13,12 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -94,8 +94,8 @@ private Object[] getChildren(IJavaElement src, boolean isFlatLayout) { } private void assertResults(Object[][] actual, Object[] expectedSrcFolderChildren, Object[] expectedDefaultPkgChildren) { - assertTrue("Wrong children found for source folder", compareArrays(actual[0], expectedSrcFolderChildren)); - assertTrue("Wrong children found for default package", compareArrays(actual[1], expectedDefaultPkgChildren));//$NON-NLS-1$ + assertTrue(compareArrays(actual[0], expectedSrcFolderChildren), "Wrong children found for source folder"); + assertTrue(compareArrays(actual[1], expectedDefaultPkgChildren), "Wrong children found for default package");//$NON-NLS-1$ } @Test @@ -190,10 +190,10 @@ public void testModule2Flat() throws Exception { /* * @see TestCase#setUp() */ - @Before + @BeforeEach public void setUp() throws Exception { fJProject= JavaProjectHelper.createJavaProject("TestProject", "bin");//$NON-NLS-1$//$NON-NLS-2$ - assertNotNull("project null", fJProject);//$NON-NLS-1$ + assertNotNull(fJProject, "project null");//$NON-NLS-1$ IPath[] rtJarPath= JavaProjectHelper.findRtJar(JavaProjectHelper.RT_STUBS_9); JavaProjectHelper.set9CompilerOptions(fJProject); IClasspathAttribute[] attributes= { new ClasspathAttribute(IClasspathAttribute.MODULE, "true") }; @@ -203,7 +203,7 @@ public void setUp() throws Exception { //set up project : Add classFolder fSrcFolder= JavaProjectHelper.addSourceContainer(fJProject, "src", null, null); //$NON-NLS-1$ - assertNotNull("source folder null", fSrcFolder); //$NON-NLS-1$ + assertNotNull(fSrcFolder, "source folder null"); //$NON-NLS-1$ } private boolean compareArrays(Object[] children, Object[] expectedChildren) { @@ -244,7 +244,7 @@ private boolean contains(IJavaElement fragment, Object[] expectedChildren) { return false; } - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fJProject); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/HierarchicalContentProviderTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/HierarchicalContentProviderTests.java index e36a975a7d5..cb1ea7525a3 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/HierarchicalContentProviderTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/HierarchicalContentProviderTests.java @@ -20,10 +20,12 @@ import java.util.Collections; import java.util.List; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExternalResource; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; @@ -46,7 +48,7 @@ public class HierarchicalContentProviderTests { - private static class MyTestSetup extends ExternalResource { + private static class MyTestSetup implements BeforeEachCallback, AfterEachCallback { public static IJavaProject fJProject; public static IPackageFragmentRoot fJAR; @@ -55,7 +57,7 @@ private static class MyTestSetup extends ExternalResource { public static List fExpectedInJAR, fExpectedInCF; @Override - protected void before() throws Exception { + public void beforeEach(ExtensionContext context) throws Exception { fJProject= JavaProjectHelper.createJavaProject("Testing", "bin"); JavaProjectHelper.addRTJar(fJProject); @@ -80,7 +82,7 @@ private static List getExpected(IPackageFragmentRoot root) throws JavaMo } @Override - protected void after() { + public void afterEach(ExtensionContext context) { try { JavaProjectHelper.delete(fJProject); } catch (CoreException e) { @@ -93,7 +95,7 @@ protected void after() { } - @Rule + @RegisterExtension public MyTestSetup mytestsetup=new MyTestSetup(); private static void testAndAdd(Object curr, List res) { @@ -131,7 +133,7 @@ public void testClassFolderFoldedHierarchical() { private void assertEquals(List expected, List current) { - Assert.assertEquals(getString(expected), getString(current)); + Assertions.assertEquals(getString(expected), getString(current)); } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageCacheTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageCacheTest.java index 5bb05824c0a..24ac3903c74 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageCacheTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageCacheTest.java @@ -13,7 +13,7 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import java.util.Arrays; @@ -22,9 +22,9 @@ import java.util.List; import java.util.Map; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -59,7 +59,7 @@ public class PackageCacheTest { private PackageCache packageCache; - @Before + @BeforeEach public void setUp() throws Exception { IProgressMonitor monitor= new NullProgressMonitor(); @@ -81,7 +81,7 @@ public void setUp() throws Exception { packageCache= new PackageCache(src); } - @After + @AfterEach public void tearDown() throws Exception { testProject.getProject().delete(true, false, new NullProgressMonitor()); } @@ -107,8 +107,8 @@ public void testGetDirectChildren() throws Exception { expectedChildren.put(package_f, Arrays.asList(package_f_g)); expectedChildren.put(package_f_g, Collections.emptyList()); - assertEquals("method returned wrong results", - expectedChildren, actualChildren); + assertEquals(expectedChildren, + actualChildren, "method returned wrong results"); } @Test @@ -116,8 +116,8 @@ public void testGetSingleChild() throws Exception { Map actualSingleChildren= actualSingleChildren(); Map expectedSingleChildren= expectedSingleChildren(); - assertEquals("method returned wrong results", - expectedSingleChildren, actualSingleChildren); + assertEquals(expectedSingleChildren, + actualSingleChildren, "method returned wrong results"); } @Test @@ -133,8 +133,8 @@ public void testSingleChildAgainstOldImplementation() throws Exception { } } - assertEquals("method returned wrong results", - expectedSingleChildren, actualSingleChildren); + assertEquals(expectedSingleChildren, + actualSingleChildren, "method returned wrong results"); } @Test @@ -142,8 +142,8 @@ public void testHasSingleChild() throws Exception { List actualPackagesWithSingleChild= actualPackagesWithSingleChild(); List expectedPackagesWithSingleChild= expectedPackagesWithSingleChild(); - assertEquals("method returned wrong results", - expectedPackagesWithSingleChild, actualPackagesWithSingleChild); + assertEquals(expectedPackagesWithSingleChild, + actualPackagesWithSingleChild, "method returned wrong results"); } @Test @@ -159,8 +159,8 @@ public void testHasSingleChildAgainstOldImplementation() throws Exception { } } - assertEquals("method returned wrong results", - expectedPackagesWithSingleChild, actualPackagesWithSingleChild); + assertEquals(expectedPackagesWithSingleChild, + actualPackagesWithSingleChild, "method returned wrong results"); } private Map actualSingleChildren() throws Exception { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageExplorerShowInTests.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageExplorerShowInTests.java index c35c6dc8255..c6083380758 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageExplorerShowInTests.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/PackageExplorerShowInTests.java @@ -18,9 +18,9 @@ import java.io.ByteArrayInputStream; +import org.junit.Rule; import org.junit.After; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/WorkingSetDropAdapterTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/WorkingSetDropAdapterTest.java index 5148a80be68..dc89651d719 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/WorkingSetDropAdapterTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/packageview/WorkingSetDropAdapterTest.java @@ -13,21 +13,23 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.packageview; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.ArrayList; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.swt.dnd.DND; import org.eclipse.core.runtime.IAdaptable; +import org.eclipse.core.runtime.ILogListener; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.resources.IFolder; @@ -60,10 +62,11 @@ public class WorkingSetDropAdapterTest { private PackageExplorerPart fPackageExplorer; private Accessor fPackageExplorerPartAccessor; private WorkingSetDropAdapter fAdapter; + private ILogListener expectNoLogging= (status, plugin) -> {throw new AssertionError(status.getMessage(), status.getException());}; - - @Before + @BeforeEach public void setUp() throws Exception { + Platform.addLogListener(expectNoLogging); fProject= JavaProjectHelper.createJavaProject("Test", "bin"); IWorkbenchPage activePage= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); fPackageExplorer= (PackageExplorerPart)activePage.showView(JavaUI.ID_PACKAGES); @@ -71,12 +74,13 @@ public void setUp() throws Exception { fAdapter= new WorkingSetDropAdapter(fPackageExplorer); } - @After + @AfterEach public void tearDown() throws Exception { JavaProjectHelper.delete(fProject); IWorkbenchPage activePage= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); activePage.hideView(fPackageExplorer); assertTrue(fPackageExplorer.getTreeViewer().getTree().isDisposed()); + Platform.removeLogListener(expectNoLogging); } @Test diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest15.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest15.java index def0097f865..3c132d97e56 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest15.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest15.java @@ -76,20 +76,21 @@ public void testConcatToTextBlock1() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"\" + //$NON-NLS-1$\n"); - buf.append(" \"public void foo() {\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" System.out.println(\\\"abc\\\");\\n\" + //$NON-NLS-1$\n"); - buf.append(" \"}\\n\"; //$NON-NLS-1$ // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "" + //$NON-NLS-1$ + "public void foo() {\\n" + //$NON-NLS-1$ + " System.out.println(\\"abc\\");\\n" + //$NON-NLS-1$ + "}\\n"; //$NON-NLS-1$ // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 1); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -127,20 +128,21 @@ public void testConcatToTextBlock2() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"\" +\n"); - buf.append(" \"public void foo() { \\n\" +\n"); - buf.append(" \" System.out.println(\\\"abc\\\");\\n\" +\n"); - buf.append(" \"}\\n\"; // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("System"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "" + + "public void foo() { \\n" + + " System.out.println(\\"abc\\");\\n" + + "}\\n"; // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("System"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -178,20 +180,21 @@ public void testConcatToTextBlock3() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"\" +\n"); - buf.append(" \"public void foo() { \\n\" +\n"); - buf.append(" \" System.out.println(\\\"\\\"\\\"abc\\\"\\\"\\\");\\n\" +\n"); - buf.append(" \"}\\n\"; // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("System"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "" + + "public void foo() { \\n" + + " System.out.println(\\"\\"\\"abc\\"\\"\\");\\n" + + "}\\n"; // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("System"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -229,20 +232,21 @@ public void testConcatToTextBlock4() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"\" +\n"); - buf.append(" \"abcdef\" +\n"); - buf.append(" \"ghijkl\\\"\\\"\\\"123\\\"\\\"\\\"\" +\n"); - buf.append(" \"mnop\";\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("abcdef"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "" + + "abcdef" + + "ghijkl\\"\\"\\"123\\"\\"\\"" + + "mnop"; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("abcdef"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -279,26 +283,27 @@ public void testConcatToTextBlock5() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" StringBuffer buf= new StringBuffer(\"intro string\\n\");\n"); - buf.append(" buf.append(\"public void foo() {\\n\");\n"); - buf.append(" buf.append(\" return null;\\n\");\n"); - buf.append(" buf.append(\"}\\n\");\n"); - buf.append(" buf.append(\"\\n\");\n"); - buf.append(" System.out.println(buf.toString());\n"); - buf.append(" System.out.println(buf.toString() + \"abc\");\n"); - buf.append(" // comment 2\n"); - buf.append(" buf = new StringBuffer(\"intro string 2\\n\");\n"); - buf.append(" buf.append(\"some string\\n\");\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + StringBuffer buf= new StringBuffer("intro string\\n"); + buf.append("public void foo() {\\n"); + buf.append(" return null;\\n"); + buf.append("}\\n"); + buf.append("\\n"); + System.out.println(buf.toString()); + System.out.println(buf.toString() + "abc"); + // comment 2 + buf = new StringBuffer("intro string 2\\n"); + buf.append("some string\\n"); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -343,23 +348,24 @@ public void testConcatToTextBlock6() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\");\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" // comment 1\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf"); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + // comment 1 + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -399,23 +405,24 @@ public void testConcatToTextBlock7() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\" return null;\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"}\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"\\n\"); //$NON-NLS-1$\n"); - buf.append(" // comment 1\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); //$NON-NLS-1$ + buf3.append(" return null;\\n"); //$NON-NLS-1$ + buf3.append("}\\n"); //$NON-NLS-1$ + buf3.append("\\n"); //$NON-NLS-1$ + // comment 1 + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 4); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -456,23 +463,24 @@ public void testConcatToTextBlock8() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\" return null;\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"}\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"\\n\"); //$NON-NLS-1$\n"); - buf.append(" // comment 1\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("StringBuilder"); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); //$NON-NLS-1$ + buf3.append(" return null;\\n"); //$NON-NLS-1$ + buf3.append("}\\n"); //$NON-NLS-1$ + buf3.append("\\n"); //$NON-NLS-1$ + // comment 1 + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("StringBuilder"); IInvocationContext ctx= getCorrectionContext(cu, index, 4); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -513,17 +521,18 @@ public void testConcatToTextBlock9() throws Exception { //https://github.com/ecl def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"foo \\n\" + \"bar \" + \"baz\" + \"biz\";\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "foo \\n" + "bar " + "baz" + "biz"; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -564,17 +573,18 @@ public void testConcatToTextBlock10() throws Exception { //https://github.com/ec def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"foo \\n\" + \"bar \" + \"baz\" + \"biz\";\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x = "foo \\n" + "bar " + "baz" + "biz"; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -615,21 +625,22 @@ public void testConcatToTextBlock11() throws Exception { //https://github.com/ec def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x =\"\\tif (true) {\\n\" +\n"); - buf.append(" \"\\t\\tstuff();\\n\" +\n"); - buf.append(" \"\\t} else\\n\" +\n"); - buf.append(" \"\\t\\tnoStuff\";\n"); - buf.append(" System.out.println(x);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x ="\\tif (true) {\\n" + + "\\t\\tstuff();\\n" + + "\\t} else\\n" + + "\\t\\tnoStuff"; + System.out.println(x); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -669,26 +680,27 @@ public void testConcatToTextBlock12() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\" return null;\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"}\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"\\n\"); //$NON-NLS-1$\n"); - buf.append(" // comment 1\n"); - buf.append(" write(buf3);\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append(" private void write(CharSequence c) {\n"); - buf.append(" System.out.println(c);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); //$NON-NLS-1$ + buf3.append(" return null;\\n"); //$NON-NLS-1$ + buf3.append("}\\n"); //$NON-NLS-1$ + buf3.append("\\n"); //$NON-NLS-1$ + // comment 1 + write(buf3); + \s + } + private void write(CharSequence c) { + System.out.println(c); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 4); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -732,24 +744,25 @@ public void testConcatToTextBlock13() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\");\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" // comment 1\n"); - buf.append(" int index = buf3.indexOf(\"null\");\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("StringBuilder"); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + // comment 1 + int index = buf3.indexOf("null"); + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("StringBuilder"); IInvocationContext ctx= getCorrectionContext(cu, index, 4); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -776,6 +789,70 @@ public void foo() { assertExpectedExistInProposals(proposals, new String[] { expected }); } + @Test + public void testConcatToTextBlock14() throws Exception { + fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); + fJProject1.setRawClasspath(projectSetup.getDefaultClasspath(), null); + JavaProjectHelper.set15CompilerOptions(fJProject1, false); + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + + String str= """ + module test { + } + """; + IPackageFragment def= fSourceFolder.createPackageFragment("", false, null); + def.createCompilationUnit("module-info.java", str, false, null); + + IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); + String str1= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + // comment 1 + int index = buf3.indexOf("null"); + bufFunc(buf3); + \s + } + public void bufFunc(StringBuilder x) { + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("StringBuilder"); + IInvocationContext ctx= getCorrectionContext(cu, index, 4); + assertNoErrors(ctx); + ArrayList proposals= collectAssists(ctx, false); + + String expected= """ + package test; + public class Cls { + public void foo() { + StringBuilder buf3= new StringBuilder(\""" + public void foo() { + return null; + } + \t + \"""); + // comment 1 + int index = buf3.indexOf("null"); + bufFunc(buf3); + \s + } + public void bufFunc(StringBuilder x) { + } + } + """; + + assertProposalExists(proposals, FixMessages.StringConcatToTextBlockFix_convert_msg); + assertExpectedExistInProposals(proposals, new String[] { expected }); + } + @Test public void testNoConcatToTextBlock1() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); @@ -791,19 +868,20 @@ public void testNoConcatToTextBlock1() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \n"); - buf.append(" \"abcdef\" +\n"); - buf.append(" \"ghijkl\";\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("abcdef"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x =\s + "abcdef" + + "ghijkl"; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("abcdef"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -826,20 +904,21 @@ public void testNoConcatToTextBlock2() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \n"); - buf.append(" \"abcdef\" +\n"); - buf.append(" \"ghijkl\" +\n"); - buf.append(" String.valueOf(true);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("abcdef"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x =\s + "abcdef" + + "ghijkl" + + String.valueOf(true); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("abcdef"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -862,20 +941,21 @@ public void testNoConcatToTextBlock3() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \n"); - buf.append(" \"abcdef\" +\n"); - buf.append(" \"ghijkl\" +\n"); - buf.append(" 3;\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("abcdef"); + String str1= """ + package test; + public class Cls { + public void foo() { + // comment 1 + String x =\s + "abcdef" + + "ghijkl" + + 3; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("abcdef"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -898,20 +978,21 @@ public void testNoConcatToTextBlock4() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo(String a) {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \n"); - buf.append(" \"abcdef\" +\n"); - buf.append(" \"ghijkl\" +\n"); - buf.append(" a;\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("abcdef"); + String str1= """ + package test; + public class Cls { + public void foo(String a) { + // comment 1 + String x =\s + "abcdef" + + "ghijkl" + + a; + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("abcdef"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -934,21 +1015,22 @@ public void testNoConcatToTextBlock5() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void noToString() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\");\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void noToString() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -971,23 +1053,24 @@ public void testNoConcatToTextBlock6() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void extraAppend() {\n"); - buf.append(" StringBuilder buf3= new StringBuilder();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\");\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" buf3.append(\"extra stuff\\n\");\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void extraAppend() { + StringBuilder buf3= new StringBuilder(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + String k = buf3.toString(); + buf3.append("extra stuff\\n"); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1010,22 +1093,23 @@ public void testNoConcatToTextBlock7() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void combinedAppendWithNLS() {\n"); - buf.append(" StringBuffer buf3= new StringBuffer();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\" return null;\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"}\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\"\\n\").append(\"extra append\\n\"); //$NON-NLS-1$ //$NON-NLS-2$\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void combinedAppendWithNLS() { + StringBuffer buf3= new StringBuffer(); + buf3.append("public void foo() {\\n"); //$NON-NLS-1$ + buf3.append(" return null;\\n"); //$NON-NLS-1$ + buf3.append("}\\n"); //$NON-NLS-1$ + buf3.append("\\n").append("extra append\\n"); //$NON-NLS-1$ //$NON-NLS-2$ + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1048,32 +1132,33 @@ public void testNoConcatToTextBlock8() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void inconsistentNLSMarkers() {\n"); - buf.append(" StringBuffer buf3= new StringBuffer();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\"); //$NON-NLS-1$\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append(" public void indexOfInside() {\n"); - buf.append(" StringBuffer buf3= new StringBuffer();\n"); - buf.append(" buf3.append(\"public void foo() {\\n\");\n"); - buf.append(" buf3.append(\" return null;\\n\");\n"); - buf.append(" buf3.append(\"}\\n\");\n"); - buf.append(" int index = buf3.indexOf(\"foo\");\n"); - buf.append(" buf3.append(\"\\n\");\n"); - buf.append(" String k = buf3.toString();\n"); - buf.append(" \n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("buf3"); + String str1= """ + package test; + public class Cls { + public void inconsistentNLSMarkers() { + StringBuffer buf3= new StringBuffer(); + buf3.append("public void foo() {\\n"); //$NON-NLS-1$ + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + buf3.append("\\n"); + String k = buf3.toString(); + \s + } + public void indexOfInside() { + StringBuffer buf3= new StringBuffer(); + buf3.append("public void foo() {\\n"); + buf3.append(" return null;\\n"); + buf3.append("}\\n"); + int index = buf3.indexOf("foo"); + buf3.append("\\n"); + String k = buf3.toString(); + \s + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("buf3"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1096,20 +1181,21 @@ public void testNoConcatToTextBlock9() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void inconsistentNLS() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String x = \"\" + //$NON-NLS-1$\n"); - buf.append(" \"public void foo() {\\n\" +\n"); - buf.append(" \" System.out.println(\\\"abc\\\");\\n\" + //$NON-NLS-1$\n"); - buf.append(" \"}\\n\"; //$NON-NLS-1$ // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void inconsistentNLS() { + // comment 1 + String x = "" + //$NON-NLS-1$ + "public void foo() {\\n" + + " System.out.println(\\"abc\\");\\n" + //$NON-NLS-1$ + "}\\n"; //$NON-NLS-1$ // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 1); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1132,22 +1218,23 @@ public void testNoConcatToTextBlock10() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void inconsistentNLS() {\n"); - buf.append(" // comment 1\n"); - buf.append(" String y = \"something\";\n"); - buf.append(" String x = \"\" +\n"); - buf.append(" \"public void foo() {\\n\" +\n"); - buf.append(" \" System.out.println(\\\"abc\\\");\\n\" +\n"); - buf.append(" y + \n"); - buf.append(" \"}\\n\"; //$NON-NLS-1$ // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - - int index= buf.indexOf("x"); + String str1= """ + package test; + public class Cls { + public void inconsistentNLS() { + // comment 1 + String y = "something"; + String x = "" + + "public void foo() {\\n" + + " System.out.println(\\"abc\\");\\n" + + y +\s + "}\\n"; //$NON-NLS-1$ // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + + int index= str1.indexOf("x"); IInvocationContext ctx= getCorrectionContext(cu, index, 1); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1170,23 +1257,24 @@ public void testConcatToMessageFormatTextBlock1() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/***********\\n\" +\n"); - buf.append(" \" * simple {} \\n\" +\n"); - buf.append(" \" * copyright\\n\" +\n"); - buf.append(" statement +\n"); - buf.append(" \" * notice {0}\\n\" +\n"); - buf.append(" \"***********/\\n\"; // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/***********\\n" + + " * simple {} \\n" + + " * copyright\\n" + + statement + + " * notice {0}\\n" + + "***********/\\n"; // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1232,23 +1320,24 @@ public void testConcatToMessageFormatTextBlock2() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/******************************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" statement +\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" ******************************/\\n\"; //$NON-NLS-1$\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/******************************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + statement + + " * copyright\\n" + //$NON-NLS-1$ + " ******************************/\\n"; //$NON-NLS-1$ + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1294,22 +1383,23 @@ public void testConcatToMessageFormatTextBlock3() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/***************************************************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" statement;\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/***************************************************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + " * copyright\\n" + //$NON-NLS-1$ + statement; + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1353,22 +1443,23 @@ public void testConcatToMessageFormatTextBlock4() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/*********************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" statement + \" * notice\\n\" + \"*********************/\\n\"; //comment 2 //$NON-NLS-1$ //$NON-NLS-2$\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/*********************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + " * copyright\\n" + //$NON-NLS-1$ + statement + " * notice\\n" + "*********************/\\n"; //comment 2 //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1415,16 +1506,17 @@ public void testConcatToMessageFormatTextBlock5() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo(String name, String id) {\n"); - buf.append(" String title = \"Name: \" + name + \" ID: \" + id;\n"); - buf.append(" System.out.println(title);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("title"); + String str1= """ + package test; + public class Cls { + public void foo(String name, String id) { + String title = "Name: " + name + " ID: " + id; + System.out.println(title); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("title"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1461,19 +1553,20 @@ public void testConcatToMessageFormatTextBlock6() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo(String name, String id) {\n"); - buf.append(" String title = \"Name: \" +\n"); - buf.append(" name + \n"); - buf.append(" \" ID: \" + \n"); - buf.append(" id;\n"); - buf.append(" System.out.println(title);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("title"); + String str1= """ + package test; + public class Cls { + public void foo(String name, String id) { + String title = "Name: " + + name +\s + " ID: " +\s + id; + System.out.println(title); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("title"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1510,23 +1603,24 @@ public void testConcatToStringFormatTextBlock1() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/*******************************\\n\" +\n"); - buf.append(" \" * simple \\n\" +\n"); - buf.append(" \" * copyright %\\n\" +\n"); - buf.append(" statement +\n"); - buf.append(" \" * notice\\n\" +\n"); - buf.append(" \" *******************************/\\n\"; // comment 2\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/*******************************\\n" + + " * simple \\n" + + " * copyright %\\n" + + statement + + " * notice\\n" + + " *******************************/\\n"; // comment 2 + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1569,23 +1663,24 @@ public void testConcatToStringFormatTextBlock2() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/******************************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" statement +\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" ******************************/\\n\"; //$NON-NLS-1$\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/******************************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + statement + + " * copyright\\n" + //$NON-NLS-1$ + " ******************************/\\n"; //$NON-NLS-1$ + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1628,22 +1723,23 @@ public void testConcatToStringFormatTextBlock3() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/***************************************************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" statement;\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/***************************************************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + " * copyright\\n" + //$NON-NLS-1$ + statement; + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1684,22 +1780,23 @@ public void testConcatToStringFormatTextBlock4() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo() {\n"); - buf.append(" String statement= \" * statement\\n\";\n"); - buf.append(" // comment 1\n"); - buf.append(" String copyright=\n"); - buf.append(" \"/*********************\\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * simple \\n\" + //$NON-NLS-1$\n"); - buf.append(" \" * copyright\\n\" + //$NON-NLS-1$\n"); - buf.append(" statement + \" * notice\\n\" + \"*********************/\\n\"; //comment 2 //$NON-NLS-1$ //$NON-NLS-2$\n"); - buf.append(" System.out.println(copyright);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("simple"); + String str1= """ + package test; + public class Cls { + public void foo() { + String statement= " * statement\\n"; + // comment 1 + String copyright= + "/*********************\\n" + //$NON-NLS-1$ + " * simple \\n" + //$NON-NLS-1$ + " * copyright\\n" + //$NON-NLS-1$ + statement + " * notice\\n" + "*********************/\\n"; //comment 2 //$NON-NLS-1$ //$NON-NLS-2$ + System.out.println(copyright); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("simple"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1743,16 +1840,17 @@ public void testConcatToStringFormatTextBlock5() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo(String name, String id) {\n"); - buf.append(" String title = \"Name: \" + name + \" ID: \" + id;\n"); - buf.append(" System.out.println(title);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("title"); + String str1= """ + package test; + public class Cls { + public void foo(String name, String id) { + String title = "Name: " + name + " ID: " + id; + System.out.println(title); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("title"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); @@ -1786,19 +1884,20 @@ public void testConcatToStringFormatTextBlock6() throws Exception { def.createCompilationUnit("module-info.java", str, false, null); IPackageFragment pack= fSourceFolder.createPackageFragment("test", false, null); - StringBuilder buf= new StringBuilder(); - buf.append("package test;\n"); - buf.append("public class Cls {\n"); - buf.append(" public void foo(String name, String id) {\n"); - buf.append(" String title = \"Name: \" +\n"); - buf.append(" name + \n"); - buf.append(" \" ID: \" + \n"); - buf.append(" id;\n"); - buf.append(" System.out.println(title);\n"); - buf.append(" }\n"); - buf.append("}\n"); - ICompilationUnit cu= pack.createCompilationUnit("Cls.java", buf.toString(), false, null); - int index= buf.indexOf("title"); + String str1= """ + package test; + public class Cls { + public void foo(String name, String id) { + String title = "Name: " + + name +\s + " ID: " +\s + id; + System.out.println(title); + } + } + """; + ICompilationUnit cu= pack.createCompilationUnit("Cls.java", str1, false, null); + int index= str1.indexOf("title"); IInvocationContext ctx= getCorrectionContext(cu, index, 6); assertNoErrors(ctx); ArrayList proposals= collectAssists(ctx, false); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest.java index 1ae0fcfa127..f0ae0e671cc 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest.java @@ -26156,10 +26156,24 @@ public int collapseIfStatements(boolean isActive, boolean isValid) { return 0; } + public int collapseIfStatementsWithLineComment(boolean isActive, boolean isValid) { + // Keep this comment + if (isActive) { // line comment + // Keep this comment too + if (isValid) { + // Keep this comment also + return 1; + } + } + + return 0; + } + public int collapseInnerLoneIf(boolean isActive, boolean isValid) { // Keep this comment - if (isActive) { + if (isActive) { // line comment if (isValid) + // Keep this comment also return 1; } @@ -26235,10 +26249,23 @@ public int collapseIfStatements(boolean isActive, boolean isValid) { return 0; } + public int collapseIfStatementsWithLineComment(boolean isActive, boolean isValid) { + // Keep this comment + // Keep this comment too + if (isActive && isValid) { // line comment + // Keep this comment also + return 1; + } + + return 0; + } + public int collapseInnerLoneIf(boolean isActive, boolean isValid) { // Keep this comment - if (isActive && isValid) + if (isActive && isValid) { // line comment + // Keep this comment also return 1; + } return 0; } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest15.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest15.java index 49e7cf98faa..e2c79bd81d9 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest15.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/CleanUpTest15.java @@ -409,10 +409,17 @@ public void foo() { buf11.append("mnop\\n"); int index = buf11.indexOf("fg"); System.out.println(buf11.toString()); + StringBuffer buf12 = new StringBuffer("abcd\\n"); + buf12.append("efgh\\n"); + buf12.append("ijkl\\n"); + buf12.append("mnopq\\n"); + bufFunc(buf12); } private void write(CharSequence c) { System.out.println(c); } + private void bufFunc(StringBuffer buf) { + } }"""; ICompilationUnit cu1= pack1.createCompilationUnit("E.java", sample, false, null); @@ -538,10 +545,19 @@ public class C { \"""; int index = str9.indexOf("fg"); System.out.println(str9); + StringBuffer buf12 = new StringBuffer(\""" + abcd + efgh + ijkl + mnopq + \"""); + bufFunc(buf12); } private void write(CharSequence c) { System.out.println(c); } + private void bufFunc(StringBuffer buf) { + } }"""; assertRefactoringResultAsExpected(new ICompilationUnit[] { cu1 }, new String[] { expected1 }, null); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest22.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest22.java index c9f54966ee4..e98aff6d33a 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest22.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest22.java @@ -330,4 +330,244 @@ public static void main(String[] args) { assertEqualString(preview1, expected1); } + @Test + public void testAddPermittedTypesToSwitchStatement() throws Exception { + fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); + fJProject1.setRawClasspath(projectsetup.getDefaultClasspath(), null); + JavaProjectHelper.set22CompilerOptions(fJProject1); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + String test= """ + package test; + + public class TestSwitch { + + sealed interface Foo { + record FooImpl_a(String x) implements Foo { + } + + record FooImpl_b(String y, String z) implements Foo { + } + + final class FooImpl_c implements Foo {} + } + + public static void main(String[] args) { + Foo foo = getFoo(); + switch (foo) { + } + } + + private static Foo getFoo() { + return new Foo.FooImpl_b("a", "b"); + } + } + """; + + ICompilationUnit cu= pack1.createCompilationUnit("TestSwitch.java", test, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal1= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal1); + + String expected1= """ + package test; + + public class TestSwitch { + + sealed interface Foo { + record FooImpl_a(String x) implements Foo { + } + + record FooImpl_b(String y, String z) implements Foo { + } + + final class FooImpl_c implements Foo {} + } + + public static void main(String[] args) { + Foo foo = getFoo(); + switch (foo) { + case Foo.FooImpl_a(String x) -> {} + case Foo.FooImpl_b(String y, String z) -> {} + case Foo.FooImpl_c f -> {} + case null -> {} + default -> {} + } + } + + private static Foo getFoo() { + return new Foo.FooImpl_b("a", "b"); + } + } + """; + + assertEqualString(preview1, expected1); + } + + @Test + public void testAddPermittedTypesToSwitchStatement2() throws Exception { + fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); + fJProject1.setRawClasspath(projectsetup.getDefaultClasspath(), null); + JavaProjectHelper.set22CompilerOptions(fJProject1); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + String shape= """ + package test; + public sealed class Shape permits Circle, Square { + } + """; + pack1.createCompilationUnit("Shape.java", shape, false, null); + + String circle= """ + package test; + public final class Circle extends Shape { + } + """; + pack1.createCompilationUnit("Circle.java", circle, false, null); + + String square= """ + package test; + public final class Square extends Shape { + } + """; + pack1.createCompilationUnit("Square.java", square, false, null); + + String test= """ + package test; + + public class TestSwitch { + + public static void main(String[] args) { + Shape shape = getShape(); + switch (shape) { + } + } + + private static Shape getShape() { + return new Circle(); + } + } + """; + + ICompilationUnit cu= pack1.createCompilationUnit("TestSwitch.java", test, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal1= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal1); + + String expected1= """ + package test; + + public class TestSwitch { + + public static void main(String[] args) { + Shape shape = getShape(); + switch (shape) { + case Circle c -> {} + case Square s -> {} + case null -> {} + default -> {} + } + } + + private static Shape getShape() { + return new Circle(); + } + } + """; + + assertEqualString(preview1, expected1); + } + + @Test + public void testAddPermittedTypesToSwitchExpression() throws Exception { + fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); + fJProject1.setRawClasspath(projectsetup.getDefaultClasspath(), null); + JavaProjectHelper.set22CompilerOptions(fJProject1); + + fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); + IPackageFragment pack1= fSourceFolder.createPackageFragment("test", false, null); + + String test= """ + package test; + + public class TestSwitch { + + sealed interface Foo { + record FooImpl_a(String x) implements Foo { + } + + record FooImpl_b(String y, String z) implements Foo { + } + + final class FooImpl_c implements Foo {} + } + + public static void main(String[] args) { + Foo foo = getFoo(); + int i = switch (foo) { + }; + } + + private static Foo getFoo() { + return new Foo.FooImpl_b("a", "b"); + } + } + """; + + ICompilationUnit cu= pack1.createCompilationUnit("TestSwitch.java", test, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot, 2, 1); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal1= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal1); + + String expected1= """ + package test; + + public class TestSwitch { + + sealed interface Foo { + record FooImpl_a(String x) implements Foo { + } + + record FooImpl_b(String y, String z) implements Foo { + } + + final class FooImpl_c implements Foo {} + } + + public static void main(String[] args) { + Foo foo = getFoo(); + int i = switch (foo) { + case Foo.FooImpl_a(String x) -> 0; + case Foo.FooImpl_b(String y, String z) -> 0; + case Foo.FooImpl_c f -> 0; + case null -> 0; + default -> 0; + }; + } + + private static Foo getFoo() { + return new Foo.FooImpl_b("a", "b"); + } + } + """; + + assertEqualString(preview1, expected1); + } + } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java index 106f5d004f5..ff9a698cb3b 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -2265,6 +2265,324 @@ void foo(Colors c) { assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } + @Test + public void testVarInEnumMethodReturn1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + String str= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + return BLUE; + } + } + """; + ICompilationUnit cu= pack1.createCompilationUnit("Colors.java", str, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal); + + String expected1= """ + package test1; + public enum Colors { + RED, BLUE; + public Colors foo() { + return BLUE; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(1); + String preview2= getPreviewContent(proposal); + + String expected2= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + return RED; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(2); + String preview3= getPreviewContent(proposal); + + String expected3= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + Colors BLUE; + return BLUE; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(3); + String preview4= getPreviewContent(proposal); + + String expected4= """ + package test1; + public enum Colors { + RED; + public Colors foo(Colors BLUE) { + return BLUE; + } + } + """; + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3, preview4 }, new String[] { expected1, expected2, expected3, expected4 }); + } + + @Test + public void testVarInEnumMethodReturn2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + String str= """ + package test1; + public enum Colors { + RED; + public int foo() { + return BLUE; + } + } + """; + ICompilationUnit cu= pack1.createCompilationUnit("Colors.java", str, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal); + + String expected1= """ + package test1; + public enum Colors { + RED; + private int BLUE; + + public int foo() { + return BLUE; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(1); + String preview2= getPreviewContent(proposal); + + String expected2= """ + package test1; + public enum Colors { + RED; + private static final int BLUE = 0; + + public int foo() { + return BLUE; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(2); + String preview3= getPreviewContent(proposal); + + String expected3= """ + package test1; + public enum Colors { + RED; + public int foo() { + int BLUE; + return BLUE; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(3); + String preview4= getPreviewContent(proposal); + + String expected4= """ + package test1; + public enum Colors { + RED; + public int foo(int BLUE) { + return BLUE; + } + } + """; + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3, preview4 }, new String[] { expected1, expected2, expected3, expected4 }); + } + + @Test + public void testVarInEnumMethod1() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + String str= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + Colors k = BLUE; + return k; + } + } + """; + ICompilationUnit cu= pack1.createCompilationUnit("Colors.java", str, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal); + + String expected1= """ + package test1; + public enum Colors { + RED, BLUE; + public Colors foo() { + Colors k = BLUE; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(1); + String preview2= getPreviewContent(proposal); + + String expected2= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + Colors BLUE; + Colors k = BLUE; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(2); + String preview3= getPreviewContent(proposal); + + String expected3= """ + package test1; + public enum Colors { + RED; + public Colors foo() { + Colors k = RED; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(3); + String preview4= getPreviewContent(proposal); + + String expected4= """ + package test1; + public enum Colors { + RED; + public Colors foo(Colors BLUE) { + Colors k = BLUE; + return k; + } + } + """; + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3, preview4 }, new String[] { expected1, expected2, expected3, expected4 }); + } + + @Test + public void testVarInEnumMethod2() throws Exception { + IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); + String str= """ + package test1; + public enum Colors { + RED; + public int foo() { + int k = BLUE; + return k; + } + } + """; + ICompilationUnit cu= pack1.createCompilationUnit("Colors.java", str, false, null); + + CompilationUnit astRoot= getASTRoot(cu); + ArrayList proposals= collectCorrections(cu, astRoot); + assertNumberOfProposals(proposals, 4); + assertCorrectLabels(proposals); + + CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); + String preview1= getPreviewContent(proposal); + + String expected1= """ + package test1; + public enum Colors { + RED; + private int BLUE; + + public int foo() { + int k = BLUE; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(1); + String preview2= getPreviewContent(proposal); + + String expected2= """ + package test1; + public enum Colors { + RED; + private static final int BLUE = 0; + + public int foo() { + int k = BLUE; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(2); + String preview3= getPreviewContent(proposal); + + String expected3= """ + package test1; + public enum Colors { + RED; + public int foo() { + int BLUE; + int k = BLUE; + return k; + } + } + """; + + proposal= (CUCorrectionProposal) proposals.get(3); + String preview4= getPreviewContent(proposal); + + String expected4= """ + package test1; + public enum Colors { + RED; + public int foo(int BLUE) { + int k = BLUE; + return k; + } + } + """; + + assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3, preview4 }, new String[] { expected1, expected2, expected3, expected4 }); + } + @Test public void testVarInMethodInvocation() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UtilitiesTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UtilitiesTest.java index 54a475dda54..e02a985a2e3 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UtilitiesTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UtilitiesTest.java @@ -209,7 +209,7 @@ public void testGetPossibleTypeKinds() throws Exception { FieldDeclaration[] fields= ((TypeDeclaration) astRoot.types().get(0)).getFields(); for (int i= 0; i < fields.length; i++) { ASTNode node= NodeFinder.perform(astRoot, buf.indexOf("X", fields[i].getStartPosition()), 1); - int kinds= ASTResolving.getPossibleTypeKinds(node, true); + int kinds= ASTResolving.getPossibleTypeKinds(node); if (kinds != expected[i]) { assertEquals("Guessing failed for " + fields[i].toString(), expected[i], kinds); } @@ -237,7 +237,7 @@ public void testGetPossibleTypeKindsForTypes() throws Exception { for (int i = 0; i < astRoot.types().size(); i++) { TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(i); ASTNode node= NodeFinder.perform(astRoot, buf.indexOf("X", typeDecl.getStartPosition()), 1); - int kinds= ASTResolving.getPossibleTypeKinds(node, true); + int kinds= ASTResolving.getPossibleTypeKinds(node); assertEquals("Guessing failed for " + node.toString(), expected[i], kinds); } } diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/IsCompletelySelectedTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/IsCompletelySelectedTest.java index 72407e5e55a..f0ff1fd499d 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/IsCompletelySelectedTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/IsCompletelySelectedTest.java @@ -13,17 +13,17 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import org.junit.After; -import org.junit.Before; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -72,7 +72,7 @@ public class IsCompletelySelectedTest { @Rule public ProjectTestSetup projectSetup = new ProjectTestSetup(); - @Before + @BeforeEach public void setUp() throws Exception { IProgressMonitor monitor= new NullProgressMonitor(); @@ -90,7 +90,7 @@ public void setUp() throws Exception { package_a_b_e= src.createPackageFragment("a.b.e", force, monitor); } - @After + @AfterEach public void tearDown() throws Exception { testProject.getProject().delete(true, false, new NullProgressMonitor()); } @@ -159,8 +159,8 @@ private void assertMatchesOnly(IsCompletelySelected predicate, IPackageFragment. } } - assertEquals("wrong set of completely selected packages", - new LinkedHashSet<>(Arrays.asList(expectedCompletelySelectedPackages)), actualCompletelySelectedPackages); + assertEquals(new LinkedHashSet<>(Arrays.asList(expectedCompletelySelectedPackages)), + actualCompletelySelectedPackages, "wrong set of completely selected packages"); } private IPackageFragment[] allPackages() { diff --git a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/ParentCheckerTest.java b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/ParentCheckerTest.java index f5e35a9f250..d7b7733dbdc 100644 --- a/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/ParentCheckerTest.java +++ b/org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/refactoring/ParentCheckerTest.java @@ -13,14 +13,14 @@ *******************************************************************************/ package org.eclipse.jdt.ui.tests.refactoring; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Arrays; import java.util.LinkedHashSet; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.eclipse.jdt.testplugin.JavaProjectHelper; @@ -53,7 +53,7 @@ public class ParentCheckerTest { private IResource classD2; - @Before + @BeforeEach public void setUp() throws Exception { /* @@ -92,7 +92,7 @@ public void setUp() throws Exception { classD2= createClass(package_a_b_d, "D2"); } - @After + @AfterEach public void tearDown() throws Exception { testProject.getProject().delete(true, true, null); } @@ -207,10 +207,10 @@ private static void assertCorrectRemovalOfElements(IJavaElement[] folders, IReso IJavaElement[] actualRemainingPackages= checker.getJavaElements(); IResource[] actualRemainingResources= checker.getResources(); - assertEquals("wrong folders remained after removing packages with ancestors", - asLinkedHashSet(expectedRemainingFolders), asLinkedHashSet(actualRemainingPackages)); - assertEquals("wrong resources remain after removing resources with ancestors", - asLinkedHashSet(expectedRemainingResources), asLinkedHashSet(actualRemainingResources)); + assertEquals(asLinkedHashSet(expectedRemainingFolders), + asLinkedHashSet(actualRemainingPackages), "wrong folders remained after removing packages with ancestors"); + assertEquals(asLinkedHashSet(expectedRemainingResources), + asLinkedHashSet(actualRemainingResources), "wrong resources remain after removing resources with ancestors"); } private static LinkedHashSet asLinkedHashSet(T[] elements) { diff --git a/org.eclipse.jdt.ui.unittest.junit.feature/feature.xml b/org.eclipse.jdt.ui.unittest.junit.feature/feature.xml index 1a6a1340db1..4a4243c800b 100644 --- a/org.eclipse.jdt.ui.unittest.junit.feature/feature.xml +++ b/org.eclipse.jdt.ui.unittest.junit.feature/feature.xml @@ -2,7 +2,7 @@ diff --git a/org.eclipse.jdt.ui.unittest.junit.feature/pom.xml b/org.eclipse.jdt.ui.unittest.junit.feature/pom.xml index 0c3e3c88625..1a12ee4c9bc 100644 --- a/org.eclipse.jdt.ui.unittest.junit.feature/pom.xml +++ b/org.eclipse.jdt.ui.unittest.junit.feature/pom.xml @@ -20,7 +20,7 @@ org.eclipse.jdt.feature org.eclipse.jdt.ui.unittest.junit.feature - 1.1.500-SNAPSHOT + 1.1.600-SNAPSHOT eclipse-feature diff --git a/org.eclipse.jdt.ui.unittest.junit/META-INF/MANIFEST.MF b/org.eclipse.jdt.ui.unittest.junit/META-INF/MANIFEST.MF index becd8104bb4..b81e2f2cd8c 100644 --- a/org.eclipse.jdt.ui.unittest.junit/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ui.unittest.junit/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.ui.unittest.junit Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.ui.unittest.junit;singleton:=true -Bundle-Version: 1.1.500.qualifier +Bundle-Version: 1.1.600.qualifier Bundle-Activator: org.eclipse.jdt.ui.unittest.junit.JUnitTestPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %providerName diff --git a/org.eclipse.jdt.ui.unittest.junit/pom.xml b/org.eclipse.jdt.ui.unittest.junit/pom.xml index 05ed1f45a55..2ec0580f391 100644 --- a/org.eclipse.jdt.ui.unittest.junit/pom.xml +++ b/org.eclipse.jdt.ui.unittest.junit/pom.xml @@ -18,6 +18,6 @@ org.eclipse.jdt org.eclipse.jdt.ui.unittest.junit - 1.1.500-SNAPSHOT + 1.1.600-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/launcher/JUnitRemoteTestRunnerClient.java b/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/launcher/JUnitRemoteTestRunnerClient.java index 11d69d7c5c8..0a36a100a42 100644 --- a/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/launcher/JUnitRemoteTestRunnerClient.java +++ b/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/launcher/JUnitRemoteTestRunnerClient.java @@ -424,7 +424,7 @@ private void notifyTestTreeEntry(final String treeEntry) { } int index6 = scanTestName(fixedTreeEntry, index5 + 1, displayNameBuffer); - displayName = displayNameBuffer.toString().trim(); + displayName = displayNameBuffer.toString().replace('\0', ' ').trim(); if (displayName.equals(testName)) { displayName = null; } diff --git a/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/ui/JUnitTestViewSupport.java b/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/ui/JUnitTestViewSupport.java index d1b19eeab64..1da731fdb95 100644 --- a/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/ui/JUnitTestViewSupport.java +++ b/org.eclipse.jdt.ui.unittest.junit/src/org/eclipse/jdt/ui/unittest/junit/ui/JUnitTestViewSupport.java @@ -89,7 +89,7 @@ public IAction getOpenTestAction(Shell shell, ITestSuiteElement testSuite) { int index = testName.indexOf('('); // test factory method if (index > 0) { - return new OpenTestAction(shell, testSuite.getTestName(), testName.substring(0, index), + return new OpenTestAction(shell, getClassName(testSuite), testName.substring(0, index), getParameterTypes(testSuite), true, testSuite.getTestRunSession()); } @@ -259,20 +259,34 @@ public ITestRunnerClient newTestRunnerClient(ITestRunSession session) { * @return a parameter type array */ private String[] getParameterTypes(ITestElement test) { - String testName = test.getDisplayName(); + final String testName = test.getDisplayName(); if (testName != null) { - int index = testName.lastIndexOf("method:"); //$NON-NLS-1$ + final int index = testName.lastIndexOf("method:"); //$NON-NLS-1$ if (index != -1) { - index = testName.indexOf('(', index); - if (index > 0) { - int closeIndex = testName.indexOf(')', index); - if (closeIndex > 0) { - String params = testName.substring(index + 1, closeIndex); - return params.split(","); //$NON-NLS-1$ - } + String[] result = extractParameters(testName, index); + if (result != null) { + return result; } } } + final String testUniqData = test.getData(); + if (testUniqData != null) { + final int testTemplateIdx = testUniqData.indexOf("test-template:"); //$NON-NLS-1$ + if (testTemplateIdx >= 0) { + return extractParameters(testUniqData, testTemplateIdx); + } + } + return null; + } + + private String[] extractParameters(String testDescription, int startIndex) { + final int index = testDescription.indexOf('(', startIndex); + if (index > 0) { + final int closeIndex = testDescription.indexOf(')', index); + if (closeIndex > 0) { + return testDescription.substring(index + 1, closeIndex).split(","); //$NON-NLS-1$ + } + } return null; } diff --git a/org.eclipse.jdt.ui/META-INF/MANIFEST.MF b/org.eclipse.jdt.ui/META-INF/MANIFEST.MF index 0a5b80724a4..0e4f86e1437 100644 --- a/org.eclipse.jdt.ui/META-INF/MANIFEST.MF +++ b/org.eclipse.jdt.ui/META-INF/MANIFEST.MF @@ -3,7 +3,7 @@ Automatic-Module-Name: org.eclipse.jdt.ui Bundle-ManifestVersion: 2 Bundle-Name: %pluginName Bundle-SymbolicName: org.eclipse.jdt.ui; singleton:=true -Bundle-Version: 3.33.200.qualifier +Bundle-Version: 3.34.0.qualifier Bundle-Activator: org.eclipse.jdt.internal.ui.JavaPlugin Bundle-ActivationPolicy: lazy Bundle-Vendor: %providerName @@ -113,7 +113,7 @@ Require-Bundle: org.eclipse.ui.ide;bundle-version="[3.15.0,4.0.0)", org.eclipse.ui.views;bundle-version="[3.3.100,4.0.0)", org.eclipse.ui.editors;bundle-version="[3.5.0,4.0.0)", - org.eclipse.core.runtime;bundle-version="[3.29.0,4.0.0)", + org.eclipse.core.runtime;bundle-version="[3.30.0,4.0.0)", org.eclipse.ltk.core.refactoring;bundle-version="[3.7.0,4.0.0)", org.eclipse.ltk.ui.refactoring;bundle-version="[3.12.0,4.0.0)", org.eclipse.ui.forms;bundle-version="[3.4.0,4.0.0)", 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 d06b50c32e2..8e40eb7c395 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 @@ -272,7 +272,7 @@ private TextEdit evaluateEdits(CompilationUnit root, ImportRewrite importRewrite return null; } return new ReplaceEdit(qualifierStart, simpleNameStart - qualifierStart, ""); //$NON-NLS-1$ - } else if (JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()) && (binding instanceof IVariableBinding || binding instanceof IMethodBinding)) { + } else if (binding instanceof IVariableBinding || binding instanceof IMethodBinding) { boolean isField= binding instanceof IVariableBinding; ITypeBinding declaringClass= isField ? ((IVariableBinding) binding).getDeclaringClass() : ((IMethodBinding) binding).getDeclaringClass(); if (declaringClass == null) { @@ -447,11 +447,9 @@ private int getSearchForConstant(int typeKinds) { * Finds a type by the simple name. */ private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor) throws JavaModelException { - boolean is50OrHigher= JavaModelUtil.is50OrHigher(fCompilationUnit.getJavaProject()); - int typeKinds= TypeKinds.ALL_TYPES; if (nameNode != null) { - typeKinds= ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher); + typeKinds= ASTResolving.getPossibleTypeKinds(nameNode); } ArrayList typeInfos= new ArrayList<>(); @@ -463,7 +461,7 @@ private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope sea for (int i= 0, len= typeInfos.size(); i < len; i++) { TypeNameMatch curr= typeInfos.get(i); if (curr.getPackageName().length() > 0) { // do not suggest imports from the default package - if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr)) { + if (isOfKind(curr, typeKinds) && isVisible(curr)) { typeRefsFound.add(curr); } } @@ -471,13 +469,13 @@ private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope sea return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]); } - private boolean isOfKind(TypeNameMatch curr, int typeKinds, boolean is50OrHigher) { + private boolean isOfKind(TypeNameMatch curr, int typeKinds) { int flags= curr.getModifiers(); if (Flags.isAnnotation(flags)) { - return is50OrHigher && (typeKinds & TypeKinds.ANNOTATIONS) != 0; + return (typeKinds & TypeKinds.ANNOTATIONS) != 0; } if (Flags.isEnum(flags)) { - return is50OrHigher && (typeKinds & TypeKinds.ENUMS) != 0; + return (typeKinds & TypeKinds.ENUMS) != 0; } if (Flags.isInterface(flags)) { return (typeKinds & TypeKinds.INTERFACES) != 0; diff --git a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsFix.java b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsFix.java index 0d8be70f602..94bc3b79280 100644 --- a/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsFix.java +++ b/org.eclipse.jdt.ui/core extension/org/eclipse/jdt/internal/corext/fix/NullAnnotationsFix.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2018 GK Software AG and others. + * Copyright (c) 2011, 2024 GK Software AG and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -40,7 +40,6 @@ import org.eclipse.jdt.internal.corext.fix.NullAnnotationsRewriteOperations.RemoveRedundantAnnotationRewriteOperation; import org.eclipse.jdt.internal.corext.fix.NullAnnotationsRewriteOperations.SignatureAnnotationRewriteOperation; import org.eclipse.jdt.internal.corext.fix.TypeAnnotationRewriteOperations.MoveTypeAnnotationRewriteOperation; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -166,10 +165,6 @@ public static NullAnnotationsFix createAddMissingDefaultNullnessAnnotationsFix(C // Entry for NullAnnotationsCleanup: public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit, IProblemLocation[] locations, int problemID) { - ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement(); - if (!JavaModelUtil.is50OrHigher(cu.getJavaProject())) - return null; - List operations= new ArrayList<>(); if (locations == null) { org.eclipse.jdt.core.compiler.IProblem[] problems= compilationUnit.getProblems(); 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 da901a50437..2e78973e4de 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 @@ -515,12 +515,6 @@ public void swapAnnotations() { fAnnotationToRemove= tmp; } - public boolean is50OrHigher() { - CompilationUnit compilationUnit= fUnit; - ICompilationUnit cu= (ICompilationUnit) compilationUnit.getJavaElement(); - return JavaModelUtil.is50OrHigher(cu.getJavaProject()); - } - public ASTNode getCoveringNode() { return fProblem.getCoveringNode(fUnit); } @@ -543,9 +537,6 @@ public SignatureAnnotationRewriteOperation createAddAnnotationOperation(Set 0 && JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null).isOK()) { + if (text.length() > 0 && JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null).isOK()) { fInitialFilter= text; fSelectionMode= FULL_SELECTION; } diff --git a/org.eclipse.jdt.ui/plugin.properties b/org.eclipse.jdt.ui/plugin.properties index 9ea43e11949..45211236b70 100644 --- a/org.eclipse.jdt.ui/plugin.properties +++ b/org.eclipse.jdt.ui/plugin.properties @@ -26,6 +26,7 @@ JavaSelectRulerAction.label= Java Editor Ruler Single-Click importExportWizards.category=Java elementFiltersName=Java Element Filters +semanticTokens=Java Editor Semantic Tokens for Syntax Highlighting classpathContainerPageExtensionPoint=Classpath Container Configuration classpathAttributeConfiguration=Classpath Attribute Configuration @@ -38,6 +39,8 @@ javadocExportWizardPageExtensionPoint=Javadoc Export Wizard Page cleanUpExtensionPoint=Clean Ups +semanticTokensExtensionPoint=Semantic Tokens + queryParticipantsExtensionPoint=Java Query Participants defaultClasspathContainerPage=Default Classpath Container diff --git a/org.eclipse.jdt.ui/plugin.xml b/org.eclipse.jdt.ui/plugin.xml index ceb88b44b7b..5c21a366586 100644 --- a/org.eclipse.jdt.ui/plugin.xml +++ b/org.eclipse.jdt.ui/plugin.xml @@ -34,6 +34,7 @@ + diff --git a/org.eclipse.jdt.ui/pom.xml b/org.eclipse.jdt.ui/pom.xml index fffaedcc7ea..bd14d5f10c9 100644 --- a/org.eclipse.jdt.ui/pom.xml +++ b/org.eclipse.jdt.ui/pom.xml @@ -18,7 +18,7 @@ org.eclipse.jdt org.eclipse.jdt.ui - 3.33.200-SNAPSHOT + 3.34.0-SNAPSHOT eclipse-plugin diff --git a/org.eclipse.jdt.ui/schema/semanticTokens.exsd b/org.eclipse.jdt.ui/schema/semanticTokens.exsd new file mode 100644 index 00000000000..7c45ce0890e --- /dev/null +++ b/org.eclipse.jdt.ui/schema/semanticTokens.exsd @@ -0,0 +1,132 @@ + + + + + + + + + Allows contributions of semantic tokens into Java source editor. Contributions are not sorted. This extension point is experimental. + + + + + + + + + + Allows contributions of semantic tokens into Java source editor. Contributions are not sorted. This extension point is experimental. + + + + + + + + + + a fully qualified identifier of the target extension point + + + + + + + an optional identifier of the extension instance + + + + + + + an optional name of the extension instance + + + + + + + + + + + + + Contributed provider of semantic tokens + + + + + + + Instance of the class able to compute Semantic Tokens for a given Java source AST + + + + + + + + + + + + + + + 3.34 + + + + + + + + + The following is an example of a Semantic Tokens Provider contribution: + +<p> +<pre> + <extension point="org.eclipse.jdt.ui.semanticTokens"> + <provider + class="org.eclipse.example.jdt.ExampleJavaSemanticTokensProvider"> + </provider> + </extension> +</pre> +</p> + + + + + + + + + The contributed class must implement <code>org.eclipse.jdt.ui.text.java.ISemanticTokensProvider</code> + + + + + + + + + Allows contributing <code>org.eclipse.jdt.ui.text.java.ISemanticTokensProvide</code> which will colour the code with colours allowed in the Java Editor. This is useful for languages embedded into Java via annotation parameters for example such as SQL queries, Spring Expression Language snippets etc. The contributions are not sorted. It is recommneded therefore not to override semantic tokens between providers. This extension is experimental and only used by LSP4E project at the moment. + + + + + + + + + Copyright (c) 2024 Broadcom Inc. and others.<br> + +This program and the accompanying materials are made available under the terms of the Eclipse Public License 2.0 which accompanies this distribution, and is available at <a href="https://www.eclipse.org/legal/epl-2.0">https://www.eclipse.org/legal/epl-v20.html</a>/ + +SPDX-License-Identifier: EPL-2.0 + + + + diff --git a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/ParameterEditDialog.java b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/ParameterEditDialog.java index 8f3434a306e..b8895dbd412 100644 --- a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/ParameterEditDialog.java +++ b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/ParameterEditDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -32,6 +32,7 @@ import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.corext.refactoring.Checks; import org.eclipse.jdt.internal.corext.refactoring.ParameterInfo; import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages; @@ -45,7 +46,6 @@ import org.eclipse.jdt.internal.ui.dialogs.TextFieldNavigationHandler; import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper; import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor; -import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; public class ParameterEditDialog extends StatusDialog { @@ -193,7 +193,7 @@ private IStatus validateName() { return createErrorStatus(RefactoringMessages.ParameterEditDialog_name_error); IStatus status= fContext != null ? JavaConventionsUtil.validateFieldName(text, fContext.getCuHandle().getJavaProject()) - : JavaConventions.validateFieldName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + : JavaConventions.validateFieldName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); if (status.matches(IStatus.ERROR)) return status; if (! Checks.startsWithLowerCase(text)) diff --git a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringMessages.java b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringMessages.java index 6c662459ea2..8b0ca0b85cf 100644 --- a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringMessages.java +++ b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringMessages.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2021 IBM Corporation and others. + * Copyright (c) 2000, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -998,8 +998,6 @@ public final class RefactoringMessages extends NLS { public static String SurroundWithTryMultiCatchAction_label; - public static String SurroundWithTryMultiCatchAction_not17; - public static String SurroundWithTryResourcesAction_label; public static String SurroundWithTryResourcesAction_exception; diff --git a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties index 88903dad63e..8b9ed6eb246 100644 --- a/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties +++ b/org.eclipse.jdt.ui/ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties @@ -1,5 +1,5 @@ ############################################################################### -# Copyright (c) 2000, 2021 IBM Corporation and others. +# Copyright (c) 2000, 2025 IBM Corporation and others. # # This program and the accompanying materials # are made available under the terms of the Eclipse Public License 2.0 @@ -37,7 +37,6 @@ SurroundWithTryCatchAction_label=Surround with tr&y/catch Block SurroundWithTryMultiCatchAction_label=Surround with t&ry/multi-catch Block SurroundWithTryCatchAction_dialog_title=Surround with try/catch SurroundWithTryMultiCatchAction_dialog_title=Surround with try/multi-catch -SurroundWithTryMultiCatchAction_not17=Project ''{0}'' cannot be processed since its compiler source level is below 1.7. SurroundWithTryCatchAction_exception=An unexpected exception occurred. See the error log for more details. SurroundWithTryResourcesAction_label=Surround with try-with-resources Block SurroundWithTryResourcesAction_dialog_title=Surround with try-with-resources diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/ExpandWithConstructorsConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/ExpandWithConstructorsConfigurationBlock.java index 25036120932..b5ede060dd4 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/ExpandWithConstructorsConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/ExpandWithConstructorsConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2009, 2016 IBM Corporation and others. + * Copyright (c) 2009, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -246,7 +246,7 @@ private void doValidation() { if (newText.length() == 0) { status.setError(""); //$NON-NLS-1$ } else { - IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null); + IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null); if (val.matches(IStatus.ERROR)) { if (fIsEditingMember) status.setError(CallHierarchyMessages.CallHierarchyTypesOrMembersDialog_error_invalidMemberName); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java index 582868d6b45..0d8b6d53fa3 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/FilteredTypesSelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -431,7 +431,7 @@ public int open() { String text= ((ITextSelection) selection).getText(); if (text != null) { text= text.trim(); - if (text.length() > 0 && JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null).isOK()) { + if (text.length() > 0 && JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null).isOK()) { setInitialPattern(text, FULL_SELECTION); } } @@ -810,7 +810,7 @@ public TypeInfoUtil(ITypeInfoImageProvider extension) { private void processVMInstallType(IVMInstallType installType, List locations, List labels) { if (installType != null) { - boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); + boolean isMac= Platform.OS.isMac(); for (IVMInstall install : installType.getVMInstalls()) { String label= getFormattedLabel(install.getName()); LibraryLocation[] libLocations = install.getLibraryLocations(); @@ -1116,7 +1116,7 @@ public TypeItemsComparator() { private void processVMInstallType(IVMInstallType installType, List locations, List labels) { if (installType != null) { - boolean isMac= Platform.OS_MACOSX.equals(Platform.getOS()); + boolean isMac= Platform.OS.isMac(); final String HOME_SUFFIX= "/Home"; //$NON-NLS-1$ for (IVMInstall install : installType.getVMInstalls()) { String label = getFormattedLabel(install.getName()); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateHashCodeEqualsDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateHashCodeEqualsDialog.java index 2b8a59fe37f..04cbebafb0c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateHashCodeEqualsDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/GenerateHashCodeEqualsDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2021 IBM Corporation and others. + * Copyright (c) 2005, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -32,12 +32,10 @@ import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ISelectionStatusValidator; -import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.IVariableBinding; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; @@ -130,13 +128,11 @@ public IStatus validate(Object[] selection) { private boolean fUseInstanceOf; private boolean fUseBlocks; private boolean fUseJ7HashEquals; - private IJavaProject fProject; private boolean fNoFields; public GenerateHashCodeEqualsDialog(Shell shell, CompilationUnitEditor editor, IType type, IVariableBinding[] allFields, IVariableBinding[] selectedFields) throws JavaModelException { super(shell, new BindingLabelProvider(), new GenerateHashCodeEqualsContentProvider(allFields), editor, type, false); - this.fProject = type.getJavaProject(); setEmptyListMessage(JavaUIMessages.GenerateHashCodeEqualsDialog_no_entries); setInitialSelections((Object[]) selectedFields); @@ -150,7 +146,7 @@ public GenerateHashCodeEqualsDialog(Shell shell, CompilationUnitEditor editor, I fUseInstanceOf= asBoolean(getDialogSettings().get(SETTINGS_INSTANCEOF), false); fUseBlocks= asBoolean(getDialogSettings().get(SETTINGS_BLOCKS), false); - fUseJ7HashEquals= asBoolean(getDialogSettings().get(SETTINGS_J7_HASH_EQUALS), JavaModelUtil.is1d7OrHigher(this.fProject)); + fUseJ7HashEquals= asBoolean(getDialogSettings().get(SETTINGS_J7_HASH_EQUALS), true); } @@ -158,8 +154,7 @@ public GenerateHashCodeEqualsDialog(Shell shell, CompilationUnitEditor editor, I public boolean close() { getDialogSettings().put(SETTINGS_INSTANCEOF, fUseInstanceOf); getDialogSettings().put(SETTINGS_BLOCKS, fUseBlocks); - if (JavaModelUtil.is1d7OrHigher(this.fProject)) - getDialogSettings().put(SETTINGS_J7_HASH_EQUALS, fUseJ7HashEquals); + getDialogSettings().put(SETTINGS_J7_HASH_EQUALS, fUseJ7HashEquals); return super.close(); } @@ -202,20 +197,14 @@ public void widgetSelected(SelectionEvent event) { button= new Button(composite, SWT.CHECK); button.setText(JavaUIMessages.GenerateHashCodeEqualsDialog_j7hashequals_button); - if (JavaModelUtil.is1d7OrHigher(this.fProject)) { - button.addSelectionListener(new SelectionAdapter() { + button.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent event) { - setUseJ7HashEquals((((Button) event.widget).getSelection())); - } - }); - button.setSelection(isUseJ7HashEquals()); - } else { - button.setEnabled(false); - button.setSelection(false); - setUseJ7HashEquals(false); - } + @Override + public void widgetSelected(SelectionEvent event) { + setUseJ7HashEquals((((Button) event.widget).getSelection())); + } + }); + button.setSelection(isUseJ7HashEquals()); data= new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalSpan= 2; button.setLayoutData(data); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filtertable/TypeFilterInputDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filtertable/TypeFilterInputDialog.java index 9b845a2745b..a935f19a457 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filtertable/TypeFilterInputDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filtertable/TypeFilterInputDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2022 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -148,7 +148,7 @@ private void doValidation() { status.setError(PreferencesMessages.TypeFilterInputDialog_error_enterName); } else { newText= newText.replace('*', 'X').replace('?', 'Y'); - IStatus val= JavaConventions.validatePackageName(newText, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + IStatus val= JavaConventions.validatePackageName(newText, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); if (val.matches(IStatus.ERROR)) { status.setError(Messages.format(PreferencesMessages.TypeFilterInputDialog_error_invalidName, val.getMessage())); } else { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AddAllCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AddAllCleanUp.java index f39c6ddd39d..a9179e79764 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AddAllCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AddAllCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -58,7 +58,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -297,8 +296,7 @@ public void rewriteASTInternal(final CompilationUnitRewrite cuRewrite, final Lin TextEditGroup group= createTextEditGroup(MultiFixMessages.AddAllCleanup_description, cuRewrite); ImportRewrite importRewrite= cuRewrite.getImportRewrite(); - if (JavaModelUtil.is50OrHigher(((CompilationUnit) toReplace.getRoot()).getJavaElement().getJavaProject()) - && affectedCollection.resolveTypeBinding() != null + if (affectedCollection.resolveTypeBinding() != null && affectedCollection.resolveTypeBinding().isRawType()) { String arraysNameText= importRewrite.addImport(Arrays.class.getCanonicalName()); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AutoboxingCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AutoboxingCleanUp.java index 37ddd58a3a0..27824c41bd0 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AutoboxingCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/AutoboxingCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019 Fabrice TIERCELIN and others. + * Copyright (c) 2019, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -45,7 +45,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -101,7 +100,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.USE_AUTOBOXING) || !JavaModelUtil.is50OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.USE_AUTOBOXING)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/BooleanLiteralCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/BooleanLiteralCleanUp.java index be1723136a4..d460c05c587 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/BooleanLiteralCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/BooleanLiteralCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -39,7 +39,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -83,7 +82,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.PREFER_BOOLEAN_LITERAL) || !JavaModelUtil.is50OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.PREFER_BOOLEAN_LITERAL)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/EmbeddedIfCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/EmbeddedIfCleanUp.java index 9ba443e093e..87826754401 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/EmbeddedIfCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/EmbeddedIfCleanUp.java @@ -23,14 +23,25 @@ import org.eclipse.text.edits.TextEditGroup; +import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; +import org.eclipse.jdt.core.IJavaElement; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; 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.Block; +import org.eclipse.jdt.core.dom.BlockComment; +import org.eclipse.jdt.core.dom.Comment; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.InfixExpression; +import org.eclipse.jdt.core.dom.LineComment; +import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; +import org.eclipse.jdt.core.dom.rewrite.ListRewrite; +import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; import org.eclipse.jdt.core.refactoring.CompilationUnitChange; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; @@ -40,6 +51,7 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; +import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -79,8 +91,8 @@ public String getPreview() { if (isActive && isValid) { int i = 0; } - - + + """; //$NON-NLS-1$ } @@ -168,8 +180,72 @@ public void rewriteASTInternal(final CompilationUnitRewrite cuRewrite, final Lin infixExpression.setLeftOperand(ASTNodeFactory.parenthesizeIfNeeded(ast, ASTNodes.createMoveTarget(rewrite, visited.getExpression()))); infixExpression.setOperator(InfixExpression.Operator.CONDITIONAL_AND); infixExpression.setRightOperand(ASTNodeFactory.parenthesizeIfNeeded(ast, ASTNodes.createMoveTarget(rewrite, innerIf.getExpression()))); + ASTNode visitedNode= visited.getThenStatement() instanceof Block ? visited.getThenStatement() : visited.getExpression(); + int offset= visited.getThenStatement() instanceof Block ? 1 : visited.getExpression().getLength(); + List visitedLineComments= ASTNodes.getTrailingLineComments(visitedNode, offset); + if (!visitedLineComments.isEmpty()) { + ASTNode innerNode= innerIf.getThenStatement() instanceof Block ? innerIf.getThenStatement() : innerIf.getExpression(); + int innerOffset= innerIf.getThenStatement() instanceof Block ? 1 : visited.getExpression().getLength(); + List innerComments= ASTNodes.getTrailingLineComments(innerNode, innerOffset); + StringBuilder blockBuilder= new StringBuilder("{"); //$NON-NLS-1$ + CompilationUnit root= cuRewrite.getRoot(); + IBuffer buffer= cuRewrite.getCu().getBuffer(); + appendComments(innerComments, blockBuilder, buffer); + appendComments(visitedLineComments, blockBuilder, buffer); + blockBuilder.append("\n"); //$NON-NLS-1$ + String fIndent= "\t"; //$NON-NLS-1$ + IJavaElement rootElement= root.getJavaElement(); + if (rootElement != null) { + IJavaProject project= rootElement.getJavaProject(); + if (project != null) { + String tab_option= project.getOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, true); + if (JavaCore.SPACE.equals(tab_option)) { + fIndent= ""; //$NON-NLS-1$ + for (int i= 0; i < CodeFormatterUtil.getTabWidth(project); ++i) { + fIndent += " "; //$NON-NLS-1$ + } + } + } + } + if (innerIf.getThenStatement() instanceof Block innerBlock) { + ListRewrite innerBlockStmts= rewrite.getListRewrite(innerBlock, Block.STATEMENTS_PROPERTY); + List originalList= innerBlockStmts.getOriginalList(); + for (Statement stmt : originalList) { + int startOffset= root.getExtendedStartPosition(stmt); + int endLength= root.getExtendedLength(stmt); + String text= buffer.getText(startOffset, endLength); + String[] textLines= text.split("\n"); //$NON-NLS-1$ + for (String textLine : textLines) { + blockBuilder.append(fIndent + textLine.trim() + "\n"); //$NON-NLS-1$ + } + } + } else { + int startOffset= root.getExtendedStartPosition(innerIf.getThenStatement()); + int endLength= root.getExtendedLength(innerIf.getThenStatement()); + String text= buffer.getText(startOffset, endLength); + String[] textLines= text.split("\n"); //$NON-NLS-1$ + for (String textLine : textLines) { + blockBuilder.append(fIndent + textLine.trim() + "\n"); //$NON-NLS-1$ + } + } + blockBuilder.append("}"); //$NON-NLS-1$ + Block newBlock= (Block) rewrite.createStringPlaceholder(blockBuilder.toString(), ASTNode.BLOCK); + rewrite.replace(innerIf.getThenStatement(), newBlock, group); + } ASTNodes.replaceButKeepComment(rewrite, innerIf.getExpression(), infixExpression, group); ASTNodes.replaceButKeepComment(rewrite, visited, ASTNodes.createMoveTarget(rewrite, innerIf), group); } + + private void appendComments(List commentList, StringBuilder buffer, IBuffer cuBuffer) { + for (Comment innerComment : commentList) { + if (innerComment instanceof LineComment lineComment) { + buffer.append(" "); //$NON-NLS-1$ + buffer.append(cuBuffer.getText(lineComment.getStartPosition(), lineComment.getLength())); + } else if (innerComment instanceof BlockComment blockComment) { + buffer.append(" //"); //$NON-NLS-1$ + buffer.append(cuBuffer.getText(blockComment.getStartPosition(), blockComment.getLength() - 2)); + } + } + } } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/HashCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/HashCleanUp.java index 81954b84269..fb32761a096 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/HashCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/HashCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2025 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -63,7 +63,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -128,7 +127,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.MODERNIZE_HASH) || !JavaModelUtil.is1d7OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.MODERNIZE_HASH)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/ObjectsEqualsCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/ObjectsEqualsCleanUp.java index 875ad6ee8fa..cce8afc473e 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/ObjectsEqualsCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/ObjectsEqualsCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2025 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -51,7 +51,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -93,10 +92,10 @@ public String getPreview() { if (!Objects.equals(aText, other.aText)) { return false; } - - - - + + + + """; //$NON-NLS-1$ } @@ -113,7 +112,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.USE_OBJECTS_EQUALS) || !JavaModelUtil.is1d7OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.USE_OBJECTS_EQUALS)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PatternCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PatternCleanUp.java index a36ea45e0c3..af2a8a31207 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PatternCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PatternCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -65,7 +65,6 @@ import org.eclipse.jdt.internal.corext.fix.FixMessages; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -133,7 +132,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.PRECOMPILE_REGEX) || !JavaModelUtil.is1d4OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.PRECOMPILE_REGEX)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PrimitiveParsingCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PrimitiveParsingCleanUp.java index c651bd0c750..66ea021efd9 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PrimitiveParsingCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/PrimitiveParsingCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2021 Fabrice TIERCELIN and others. + * Copyright (c) 2021, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -23,7 +23,6 @@ import org.eclipse.text.edits.TextEditGroup; import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTVisitor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; @@ -40,7 +39,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -124,7 +122,7 @@ public boolean visit(final MethodInvocation visited) { return false; } - String parsingMethodName= getParsingMethodName(canonicalName, wrapperClass.getSimpleName(), visited); + String parsingMethodName= getParsingMethodName(canonicalName, wrapperClass.getSimpleName()); if (parsingMethodName != null && isValueOfString(visited, canonicalName)) { @@ -139,7 +137,7 @@ && isValueOfString(visited, canonicalName)) { if (typeBinding != null && visited.arguments().isEmpty()) { String primitiveValueMethodName= getPrimitiveValueMethodName(typeBinding.getQualifiedName()); - String parsingMethodName= getParsingMethodName(typeBinding.getQualifiedName(), typeBinding.getName(), visited); + String parsingMethodName= getParsingMethodName(typeBinding.getQualifiedName(), typeBinding.getName()); if (primitiveValueMethodName != null && primitiveValueMethodName.equals(methodName) @@ -185,17 +183,15 @@ private String getPrimitiveValueMethodName(final String wrapperFullyQualifiedNam return null; } - private String getParsingMethodName(final String wrapperFullyQualifiedName, final String wrapperSimpleName, final MethodInvocation visited) { + private String getParsingMethodName(final String wrapperFullyQualifiedName, final String wrapperSimpleName) { if (Integer.class.getCanonicalName().equals(wrapperFullyQualifiedName)) { return "parseInt"; //$NON-NLS-1$ } - IJavaProject javaProject= ((CompilationUnit) visited.getRoot()).getJavaElement().getJavaProject(); - - if ((Boolean.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is50OrHigher(javaProject)) + if (Boolean.class.getCanonicalName().equals(wrapperFullyQualifiedName) || Long.class.getCanonicalName().equals(wrapperFullyQualifiedName) - || (Double.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is1d2OrHigher(javaProject)) - || (Float.class.getCanonicalName().equals(wrapperFullyQualifiedName) && JavaModelUtil.is1d2OrHigher(javaProject)) + || Double.class.getCanonicalName().equals(wrapperFullyQualifiedName) + || Float.class.getCanonicalName().equals(wrapperFullyQualifiedName) || Short.class.getCanonicalName().equals(wrapperFullyQualifiedName) || Byte.class.getCanonicalName().equals(wrapperFullyQualifiedName)) { return "parse" + wrapperSimpleName; //$NON-NLS-1$ diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/StringBuilderCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/StringBuilderCleanUp.java index e9b409790ab..e2d2e2c2804 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/StringBuilderCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/StringBuilderCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -70,7 +70,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -604,12 +603,7 @@ private void refactorCreation(final ASTRewrite rewrite, final AST ast, final Tex // StringBuilder builder = new StringBuilder().append(i).append("bar"); // StringBuilder builder = new StringBuilder("foo").append(i); - Class builder; - if (JavaModelUtil.is50OrHigher(((CompilationUnit) type.getRoot()).getJavaElement().getJavaProject())) { - builder= StringBuilder.class; - } else { - builder= StringBuffer.class; - } + Class builder= StringBuilder.class; ASTNodes.replaceButKeepComment(rewrite, type, ast.newSimpleType(ASTNodeFactory.newName(ast, builder.getSimpleName())), group); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/TryWithResourceCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/TryWithResourceCleanUp.java index a40e53cfca6..254bb4396fc 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/TryWithResourceCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/TryWithResourceCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2020 Fabrice TIERCELIN and others. + * Copyright (c) 2020, 2025 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -25,7 +25,6 @@ import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.internal.corext.fix.TryWithResourceFixCore; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -66,8 +65,8 @@ public String getPreview() { try (inputStream) { System.out.println(inputStream.read()); } - - + + """; //$NON-NLS-1$ } @@ -83,7 +82,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(final CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.TRY_WITH_RESOURCE) || !JavaModelUtil.is1d7OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.TRY_WITH_RESOURCE)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/UnboxingCleanUp.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/UnboxingCleanUp.java index 7022821ec0a..50a6a99ea05 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/UnboxingCleanUp.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/fix/UnboxingCleanUp.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2019, 2022 Fabrice TIERCELIN and others. + * Copyright (c) 2019, 2024 Fabrice TIERCELIN and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -43,7 +43,6 @@ import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore.CompilationUnitRewriteOperationWithSourceRange; import org.eclipse.jdt.internal.corext.fix.LinkedProposalModelCore; import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.cleanup.CleanUpRequirements; import org.eclipse.jdt.ui.cleanup.ICleanUpFix; @@ -109,7 +108,7 @@ public String getPreview() { @Override protected ICleanUpFix createFix(CompilationUnit unit) throws CoreException { - if (!isEnabled(CleanUpConstants.USE_UNBOXING) || !JavaModelUtil.is50OrHigher(unit.getJavaElement().getJavaProject())) { + if (!isEnabled(CleanUpConstants.USE_UNBOXING)) { return null; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java index 9871e7c6aa1..b5ad597e192 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -594,7 +594,7 @@ protected void doValidation(JavadocTree javadocstatus) { if (doclet.length() == 0) { fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_nodocletname_error); - } else if (JavaConventions.validateJavaTypeName(doclet, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null).matches(IStatus.ERROR)) { + } else if (JavaConventions.validateJavaTypeName(doclet, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null).matches(IStatus.ERROR)) { fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invaliddocletname_error); } else if ((docletPath.length() == 0) || !validDocletPath(docletPath)) { fDocletStatus.setError(JavadocExportMessages.JavadocTreeWizardPage_invaliddocletpath_error); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java index 5ee9e7acb3f..225816cf551 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java @@ -73,7 +73,6 @@ import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ITypeRoot; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IBinding; @@ -609,7 +608,7 @@ private boolean targetIsInString() { private void addImports(final ICompilationUnit unit, ClipboardData data) throws CoreException { final ImportRewrite rewrite= StubUtility.createImportRewrite(unit, true); for (String type : data.getTypeImports()) { - if (type.indexOf('.') != -1 || JavaModelUtil.isVersionLessThan(unit.getJavaProject().getOption(JavaCore.COMPILER_COMPLIANCE, true), JavaCore.VERSION_1_4)) { + if (type.indexOf('.') != -1) { rewrite.addImport(type); } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java index 80c2a10ce5f..3fdf285ea46 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java @@ -403,7 +403,6 @@ private class BracketInserter implements VerifyKeyListener, ILinkedModeListener private boolean fCloseBrackets= true; private boolean fCloseStrings= true; - private boolean fCloseAngularBrackets= true; private final String CATEGORY= toString(); private final IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY); private final Stack fBracketLevelStack= new Stack<>(); @@ -416,10 +415,6 @@ public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } - public void setCloseAngularBracketsEnabled(boolean enabled) { - fCloseAngularBrackets= enabled; - } - private boolean isTypeArgumentStart(String identifier) { return identifier.length() > 0 && Character.isUpperCase(identifier.charAt(0)); @@ -495,7 +490,7 @@ public void verifyKey(VerifyEvent event) { break; case '<': - if (!fCloseAngularBrackets || !fCloseBrackets + if (!fCloseBrackets || nextToken == Symbols.TokenLESSTHAN || nextToken == Symbols.TokenQUESTIONMARK || nextToken == Symbols.TokenIDENT && isTypeArgumentStart(next) @@ -1528,11 +1523,9 @@ public void createPartControl(Composite parent) { IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); - boolean closeAngularBrackets= JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, preferenceStore.getString(JavaCore.COMPILER_SOURCE)) <= 0; fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); - fBracketInserter.setCloseAngularBracketsEnabled(closeAngularBrackets); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) @@ -1608,10 +1601,6 @@ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { else uninstallTabsToSpacesConverter(); return; - case JavaCore.COMPILER_SOURCE: - boolean closeAngularBrackets= JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, getPreferenceStore().getString(p)) <= 0; - fBracketInserter.setCloseAngularBracketsEnabled(closeAngularBrackets); - break; case PreferenceConstants.EDITOR_SMART_TAB: if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java index a35ed9947ec..f9655533da1 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java @@ -2947,12 +2947,6 @@ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { return; } - if (JavaCore.COMPILER_SOURCE.equals(property)) { - if (event.getNewValue() instanceof String) - fBracketMatcher.setSourceVersion((String) event.getNewValue()); - // fall through as others are interested in source change as well. - } - ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event); if (affectsOverrideIndicatorAnnotations(event)) { @@ -3128,7 +3122,6 @@ public void createPartControl(Composite parent) { @Override protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { - fBracketMatcher.setSourceVersion(getPreferenceStore().getString(JavaCore.COMPILER_SOURCE)); support.setCharacterPairMatcher(fBracketMatcher); support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR, HIGHLIGHT_BRACKET_AT_CARET_LOCATION, ENCLOSING_BRACKETS); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingManager.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingManager.java index 0700fc38a69..7b8735cd01f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingManager.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingManager.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -36,6 +36,7 @@ import org.eclipse.jdt.ui.text.IColorManagerExtension; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; +import org.eclipse.jdt.internal.ui.preferences.SyntaxColorHighlighting; import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler; /** @@ -54,15 +55,18 @@ static class Highlighting { // TODO: rename to HighlightingStyle private TextAttribute fTextAttribute; /** Enabled state */ private boolean fIsEnabled; + /** Preference Key */ + private final String fPreferenceKey; /** * Initialize with the given text attribute. * @param textAttribute The text attribute * @param isEnabled the enabled state */ - public Highlighting(TextAttribute textAttribute, boolean isEnabled) { + public Highlighting(String preferenceKey, TextAttribute textAttribute, boolean isEnabled) { setTextAttribute(textAttribute); setEnabled(isEnabled); + this.fPreferenceKey = preferenceKey; } /** @@ -92,6 +96,11 @@ public boolean isEnabled() { public void setEnabled(boolean isEnabled) { fIsEnabled= isEnabled; } + + public String getPreferenceKey() { + return fPreferenceKey; + } + } /** @@ -252,6 +261,7 @@ public int hashCode() { private SemanticHighlighting[] fSemanticHighlightings; /** Highlightings */ private Highlighting[] fHighlightings; + private Highlighting[] fSyntaxHighlightings; /** The editor */ private JavaEditor fEditor; @@ -338,7 +348,7 @@ private void enable() { if (fEditor != null) { fReconciler= createSemanticHighlightingReconciler(); - fReconciler.install(fEditor, fSourceViewer, fPresenter, fSemanticHighlightings, fHighlightings); + fReconciler.install(fEditor, fSourceViewer, fPresenter, fSemanticHighlightings, fHighlightings, fSyntaxHighlightings); } else { fPresenter.updatePresentation(null, createHardcodedPositions(), new HighlightedPosition[0]); } @@ -374,10 +384,9 @@ private HighlightedPosition[] createHardcodedPositions() { * @return the corresponding highlighting */ private Highlighting getHighlighting(String key) { - for (int i= 0; i < fSemanticHighlightings.length; i++) { - SemanticHighlighting semanticHighlighting= fSemanticHighlightings[i]; - if (key.equals(semanticHighlighting.getPreferenceKey())) - return fHighlightings[i]; + for (Highlighting highlighting : fHighlightings) { + if (key.equals(highlighting.getPreferenceKey())) + return highlighting; } return null; } @@ -432,42 +441,58 @@ private boolean isEnabled() { private void initializeHighlightings() { fSemanticHighlightings= SemanticHighlightings.getSemanticHighlightings(); fHighlightings= new Highlighting[fSemanticHighlightings.length]; - for (int i= 0, n= fSemanticHighlightings.length; i < n; i++) { SemanticHighlighting semanticHighlighting= fSemanticHighlightings[i]; - String colorKey= SemanticHighlightings.getColorPreferenceKey(semanticHighlighting); - addColor(colorKey); + String colorKey= SemanticHighlightings.getColorPreferenceKey(semanticHighlighting); String boldKey= SemanticHighlightings.getBoldPreferenceKey(semanticHighlighting); - int style= fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL; - String italicKey= SemanticHighlightings.getItalicPreferenceKey(semanticHighlighting); - if (fPreferenceStore.getBoolean(italicKey)) - style |= SWT.ITALIC; - String strikethroughKey= SemanticHighlightings.getStrikethroughPreferenceKey(semanticHighlighting); - if (fPreferenceStore.getBoolean(strikethroughKey)) - style |= TextAttribute.STRIKETHROUGH; - String underlineKey= SemanticHighlightings.getUnderlinePreferenceKey(semanticHighlighting); - if (fPreferenceStore.getBoolean(underlineKey)) - style |= TextAttribute.UNDERLINE; - boolean isEnabled= fPreferenceStore.getBoolean(SemanticHighlightings.getEnabledPreferenceKey(semanticHighlighting)); - fHighlightings[i]= new Highlighting(new TextAttribute(fColorManager.getColor(PreferenceConverter.getColor(fPreferenceStore, colorKey)), null, style), isEnabled); + fHighlightings[i]= createHighlightingFromPereferences(semanticHighlighting.getPreferenceKey(), isEnabled, colorKey, boldKey, italicKey, strikethroughKey, underlineKey); + } + + SyntaxColorHighlighting[] syntaxHighlightings= SyntaxColorHighlighting.getSyntaxColorHighlightings(); + fSyntaxHighlightings= new Highlighting[syntaxHighlightings.length]; + for (int i= 0; i < syntaxHighlightings.length; i++) { + SyntaxColorHighlighting h= syntaxHighlightings[i]; + fSyntaxHighlightings[i]= createHighlightingFromPereferences(h.preferenceKey(), true, h.preferenceKey(), h.getBoldPreferenceKey(), h.getItalicPreferenceKey(), h.getStrikethroughPreferenceKey(), h.getUnderlinePreferenceKey()); } } + private Highlighting createHighlightingFromPereferences(String key, boolean isEnabled, String colorKey, String boldKey, String italicKey, String strikethroughKey, String underlineKey) { + addColor(colorKey); + + int style= fPreferenceStore.getBoolean(boldKey) ? SWT.BOLD : SWT.NORMAL; + + if (fPreferenceStore.getBoolean(italicKey)) + style |= SWT.ITALIC; + + if (fPreferenceStore.getBoolean(strikethroughKey)) + style |= TextAttribute.STRIKETHROUGH; + + if (fPreferenceStore.getBoolean(underlineKey)) + style |= TextAttribute.UNDERLINE; + + return new Highlighting(key, new TextAttribute(fColorManager.getColor(PreferenceConverter.getColor(fPreferenceStore, colorKey)), null, style), isEnabled); + } + /** * Dispose the semantic highlightings. */ private void disposeHighlightings() { - for (SemanticHighlighting fSemanticHighlighting : fSemanticHighlightings) + for (SemanticHighlighting fSemanticHighlighting : fSemanticHighlightings) { removeColor(SemanticHighlightings.getColorPreferenceKey(fSemanticHighlighting)); + } + for (Highlighting h : fSyntaxHighlightings) { + removeColor(h.getPreferenceKey()); + } fSemanticHighlightings= null; fHighlightings= null; + fSyntaxHighlightings= null; } /* @@ -554,6 +579,52 @@ private void handlePropertyChangeEvent(PropertyChangeEvent event) { } } + SyntaxColorHighlighting[] editorHighlightings= SyntaxColorHighlighting.getSyntaxColorHighlightings(); + for (int i= 0, n= editorHighlightings.length; i < n; i++) { + SyntaxColorHighlighting h= editorHighlightings[i]; + + String colorKey= h.preferenceKey(); + if (colorKey.equals(event.getProperty())) { + adaptToTextForegroundChange(fSyntaxHighlightings[i], event); + fPresenter.highlightingStyleChanged(fSyntaxHighlightings[i]); + refreshNeeded= true; + continue; + } + + String boldKey= h.getBoldPreferenceKey(); + if (boldKey.equals(event.getProperty())) { + adaptToTextStyleChange(fSyntaxHighlightings[i], event, SWT.BOLD); + fPresenter.highlightingStyleChanged(fSyntaxHighlightings[i]); + refreshNeeded= true; + continue; + } + + String italicKey= h.getItalicPreferenceKey(); + if (italicKey.equals(event.getProperty())) { + adaptToTextStyleChange(fSyntaxHighlightings[i], event, SWT.ITALIC); + fPresenter.highlightingStyleChanged(fSyntaxHighlightings[i]); + refreshNeeded= true; + continue; + } + + String strikethroughKey= h.getStrikethroughPreferenceKey(); + if (strikethroughKey.equals(event.getProperty())) { + adaptToTextStyleChange(fSyntaxHighlightings[i], event, TextAttribute.STRIKETHROUGH); + fPresenter.highlightingStyleChanged(fSyntaxHighlightings[i]); + refreshNeeded= true; + continue; + } + + String underlineKey= h.getUnderlinePreferenceKey(); + if (underlineKey.equals(event.getProperty())) { + adaptToTextStyleChange(fSyntaxHighlightings[i], event, TextAttribute.UNDERLINE); + fPresenter.highlightingStyleChanged(fSyntaxHighlightings[i]); + refreshNeeded= true; + continue; + } + + } + if (refreshNeeded && fReconciler != null) fReconciler.refresh(); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java index 9453d16ab8a..667bd3b73e3 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SemanticHighlightingReconciler.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2022 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -15,13 +15,18 @@ package org.eclipse.jdt.internal.ui.javaeditor; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Objects; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; +import org.eclipse.core.runtime.IConfigurationElement; +import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; @@ -52,6 +57,9 @@ import org.eclipse.jdt.core.dom.YieldStatement; import org.eclipse.jdt.core.manipulation.SharedASTProviderCore; +import org.eclipse.jdt.ui.PreferenceConstants; +import org.eclipse.jdt.ui.text.java.ISemanticTokensProvider; + import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.HighlightedPosition; import org.eclipse.jdt.internal.ui.javaeditor.SemanticHighlightingManager.Highlighting; @@ -259,33 +267,6 @@ public boolean visit(SimpleName node) { return false; } - /** - * Add a position with the given range and highlighting iff it does not exist already. - * @param offset The range offset - * @param length The range length - * @param highlighting The highlighting - */ - private void addPosition(int offset, int length, Highlighting highlighting) { - boolean isExisting= false; - // TODO: use binary search - for (int i= 0, n= fRemovedPositions.size(); i < n; i++) { - HighlightedPosition position= (HighlightedPosition) fRemovedPositions.get(i); - if (position == null) - continue; - if (position.isEqual(offset, length, highlighting)) { - isExisting= true; - fRemovedPositions.set(i, null); - fNOfRemovedPositions--; - break; - } - } - - if (!isExisting) { - Position position= fJobPresenter.createHighlightedPosition(offset, length, highlighting); - fAddedPositions.add(position); - } - } - /** * Retain the positions completely contained in the given range. * @param offset The range offset @@ -326,6 +307,38 @@ public boolean visit(GuardedPattern node) { } } + /** + * Add a position with the given range and highlighting iff it does not exist already. + * @param offset The range offset + * @param length The range length + * @param highlighting The highlighting + */ + private void addPosition(int offset, int length, Highlighting highlighting) { + boolean isExisting= false; + // TODO: use binary search + for (int i= 0, n= fRemovedPositions.size(); i < n; i++) { + HighlightedPosition position= (HighlightedPosition) fRemovedPositions.get(i); + if (position == null) + continue; + if (position.isEqual(offset, length, highlighting)) { + isExisting= true; + fRemovedPositions.set(i, null); + fNOfRemovedPositions--; + break; + } + } + + if (!isExisting) { + Position position= fJobPresenter.createHighlightedPosition(offset, length, highlighting); + fAddedPositions.add(position); + } + } + + private static final String JAVA_EDITOR_SEMANTIC_TOKENS_EXTENSION_POINT= "org.eclipse.jdt.ui.semanticTokens"; //$NON-NLS-1$ + private static final String ATTR_CLASS = "class"; //$NON-NLS-1$ + + private static ISemanticTokensProvider[] fSemanticTokensProviders; + /** Position collector */ private PositionCollector fCollector= new PositionCollector(); @@ -339,6 +352,8 @@ public boolean visit(GuardedPattern node) { private SemanticHighlighting[] fSemanticHighlightings; /** Highlightings */ private Highlighting[] fHighlightings; + /** Syntax Highlightings */ + private Highlighting[] fSyntaxHighlightings; /** Background job's added highlighted positions */ private List fAddedPositions= new ArrayList<>(); @@ -369,6 +384,7 @@ public boolean visit(GuardedPattern node) { private SemanticHighlighting[] fJobSemanticHighlightings; /** Highlightings - cache for background thread, only valid during {@link #reconciled(CompilationUnit, boolean, IProgressMonitor)} */ private Highlighting[] fJobHighlightings; + private Highlighting[] fJobSyntaxHighlightings; /** * XXX Hack for performance reasons (should loop over fJobSemanticHighlightings can call consumes(*)) @@ -384,6 +400,30 @@ public void aboutToBeReconciled() { // Do nothing } + private static synchronized ISemanticTokensProvider[] getContributedSemanticTokensProviders() { + if (fSemanticTokensProviders == null) { + IExtensionRegistry registry= Platform.getExtensionRegistry(); + IConfigurationElement[] elements= registry.getConfigurationElementsFor(JAVA_EDITOR_SEMANTIC_TOKENS_EXTENSION_POINT); + fSemanticTokensProviders = Arrays.stream(elements).map(ce -> { + try { + return (ISemanticTokensProvider) ce.createExecutableExtension(ATTR_CLASS); + } catch (Exception e) { + JavaPlugin.getDefault().getLog().error("Cannot instatiate semantic tokens provider '%s' contributed by '%s'".formatted(ce.getAttribute(ATTR_CLASS), ce.getContributor().getName()), e); //$NON-NLS-1$ + return null; + } + }).filter(Objects::nonNull).toArray(ISemanticTokensProvider[]::new); + } + return fSemanticTokensProviders; + } + + private List getContributedSemanticTokens(CompilationUnit ast) { + List contributedTokens = new ArrayList<>(); + for (ISemanticTokensProvider provider : getContributedSemanticTokensProviders()) { + contributedTokens.addAll(provider.computeSemanticTokens(ast)); + } + return contributedTokens; + } + /* * @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor) */ @@ -399,6 +439,7 @@ public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor pro fJobPresenter= fPresenter; fJobSemanticHighlightings= fSemanticHighlightings; fJobHighlightings= fHighlightings; + fJobSyntaxHighlightings = fSyntaxHighlightings; try { if (fJobPresenter == null || fJobSemanticHighlightings == null || fJobHighlightings == null) @@ -424,7 +465,9 @@ public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor pro break; } } - reconcilePositions(subtrees); + + reconcilePositions(subtrees, getContributedSemanticTokens(ast)); + } TextPresentation textPresentation= null; @@ -440,6 +483,7 @@ public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor pro fJobSemanticHighlightings= null; fJobHighlightings= null; fJobDeprecatedMemberHighlighting= null; + fJobSyntaxHighlightings = null; synchronized (fReconcileLock) { fIsReconciling= false; } @@ -467,14 +511,22 @@ private void startReconcilingPositions() { * Reconcile positions based on the AST subtrees * * @param subtrees the AST subtrees + * @param contributedTokens contributed semantic tokens data */ - private void reconcilePositions(ASTNode[] subtrees) { + private void reconcilePositions(ASTNode[] subtrees, List contributedTokens) { // FIXME: remove positions not covered by subtrees - - for (ASTNode subtree : subtrees) subtree.accept(fCollector); + + for (ISemanticTokensProvider.SemanticToken t : contributedTokens) { + Highlighting h = fromSemanticTokenType(t.tokenType()); + if (h == null) { + JavaPlugin.logErrorMessage("Cannot find semantic highlighting for %s".formatted(t)); //$NON-NLS-1$ + } else { + addPosition(t.ofset(), t.length(), h); + } + } List oldPositions= fRemovedPositions; List newPositions= new ArrayList<>(fNOfRemovedPositions); for (Position current : oldPositions) { @@ -484,6 +536,101 @@ private void reconcilePositions(ASTNode[] subtrees) { fRemovedPositions= newPositions; } + private Highlighting fromSemanticTokenType(ISemanticTokensProvider.TokenType type) { + if (type == null) { + return null; + } + switch (type) { + case OPERATOR: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR); + case SINGLE_LINE_COMMENT: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR); + case KEYWORD: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR); + case BRACKET: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR); + case MULTI_LINE_COMMENT: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR); + case STRING: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_STRING_COLOR); + case METHOD: + return findSemanticHighlighting(SemanticHighlightings.METHOD); + case ABSTRACT_CLASS: + return findSemanticHighlighting(SemanticHighlightings.ABSTRACT_CLASS); + case ABSTRACT_METHOD_INVOCATION: + return findSemanticHighlighting(SemanticHighlightings.ABSTRACT_METHOD_INVOCATION); + case ANNOTATION: + return findSemanticHighlighting(SemanticHighlightings.ANNOTATION); + case ANNOTATION_ELEMENT_REFERENCE: + return findSemanticHighlighting(SemanticHighlightings.ANNOTATION_ELEMENT_REFERENCE); + case AUTOBOXING: + return findSemanticHighlighting(SemanticHighlightings.AUTOBOXING); + case CLASS: + return findSemanticHighlighting(SemanticHighlightings.CLASS); + case DEPRECATED_MEMBER: + return findSemanticHighlighting(SemanticHighlightings.DEPRECATED_MEMBER); + case ENUM: + return findSemanticHighlighting(SemanticHighlightings.ENUM); + case FIELD: + return findSemanticHighlighting(SemanticHighlightings.FIELD); + case INHERITED_FIELD: + return findSemanticHighlighting(SemanticHighlightings.INHERITED_FIELD); + case INHERITED_METHOD_INVOCATION: + return findSemanticHighlighting(SemanticHighlightings.INHERITED_METHOD_INVOCATION); + case INTERFACE: + return findSemanticHighlighting(SemanticHighlightings.INTERFACE); + case LOCAL_VARIABLE: + return findSemanticHighlighting(SemanticHighlightings.LOCAL_VARIABLE); + case LOCAL_VARIABLE_DECLARATION: + return findSemanticHighlighting(SemanticHighlightings.LOCAL_VARIABLE_DECLARATION); + case METHOD_DECLARATION: + return findSemanticHighlighting(SemanticHighlightings.METHOD_DECLARATION); + case NUMBER: + return findSemanticHighlighting(SemanticHighlightings.NUMBER); + case PARAMETER_VARIABLE: + return findSemanticHighlighting(SemanticHighlightings.PARAMETER_VARIABLE); + case STATIC_FIELD: + return findSemanticHighlighting(SemanticHighlightings.STATIC_FIELD); + case STATIC_FINAL_FIELD: + return findSemanticHighlighting(SemanticHighlightings.STATIC_FINAL_FIELD); + case STATIC_METHOD_INVOCATION: + return findSemanticHighlighting(SemanticHighlightings.STATIC_METHOD_INVOCATION); + case TYPE_ARGUMENT: + return findSemanticHighlighting(SemanticHighlightings.TYPE_ARGUMENT); + case TYPE_VARIABLE: + return findSemanticHighlighting(SemanticHighlightings.TYPE_VARIABLE); + case RESTRICTED_IDENTIFIER: + return findSemanticHighlighting(SemanticHighlightingsCore.RESTRICTED_KEYWORDS); + case DEFAULT: + default: + return findSyntaxHighlighting(PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR); + } + } + + private Highlighting findSemanticHighlighting(String preferenceKey) { + for (Highlighting h : fJobHighlightings) { + if (Objects.equals(preferenceKey, h.getPreferenceKey())) { + if (!h.isEnabled()) { + break; + } + return h; + } + } + return null; + } + + private Highlighting findSyntaxHighlighting(String key) { + for (Highlighting h : fJobSyntaxHighlightings) { + if (Objects.equals(key, h.getPreferenceKey())) { + if (!h.isEnabled()) { + break; + } + return h; + } + } + return null; + } + /** * Update the presentation. * @@ -537,11 +684,13 @@ private void stopReconcilingPositions() { * @param presenter the semantic highlighting presenter * @param semanticHighlightings the semantic highlightings * @param highlightings the highlightings + * @param syntaxHighlightings editor syntax highlightings */ - public void install(JavaEditor editor, ISourceViewer sourceViewer, SemanticHighlightingPresenter presenter, SemanticHighlighting[] semanticHighlightings, Highlighting[] highlightings) { + public void install(JavaEditor editor, ISourceViewer sourceViewer, SemanticHighlightingPresenter presenter, SemanticHighlighting[] semanticHighlightings, Highlighting[] highlightings, Highlighting[] syntaxHighlightings) { fPresenter= presenter; fSemanticHighlightings= semanticHighlightings; fHighlightings= highlightings; + fSyntaxHighlightings= syntaxHighlightings; fEditor= editor; fSourceViewer= sourceViewer; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/breadcrumb/EditorBreadcrumb.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/breadcrumb/EditorBreadcrumb.java index 9ee7873b688..ac45b5d55d3 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/breadcrumb/EditorBreadcrumb.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/breadcrumb/EditorBreadcrumb.java @@ -282,7 +282,7 @@ public Control createContent(Composite parent) { if (menu != null && !menu.isDisposed() && menu.getDisplay() != null - && Platform.OS_WIN32.equals(Platform.getOS())) { + && Platform.OS.isWindows()) { menu.getDisplay().readAndDispatch(); } actionGroup.dispose(); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/codemining/CalleeJavaMethodParameterVisitor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/codemining/CalleeJavaMethodParameterVisitor.java index 11f14a89ef0..9a38f907b0f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/codemining/CalleeJavaMethodParameterVisitor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/codemining/CalleeJavaMethodParameterVisitor.java @@ -129,7 +129,7 @@ protected void collectParameterNamesCodeMinings(IMethod method, List argument protected void collectParameterNamesCodeMinings(IMethodBinding mbinding, List arguments, boolean isVarArgs) { // synthetic method of a record - if (mbinding.getDeclaringClass().isRecord()) { + if (mbinding.getDeclaringClass().isRecord() && !skipParameterNamesCodeMinings(mbinding)) { String[] parameterNames= mbinding.getParameterNames(); for (int i= 0; i < Math.min(arguments.size(), parameterNames.length); i++) { if (!skipParameterNameCodeMining(parameterNames, arguments, i)) { @@ -165,7 +165,15 @@ private boolean skipParameterNameCodeMining(String[] parameterNames, List arg } private boolean skipParameterNamesCodeMinings(IMethod method) { - return method.getNumberOfParameters() <= 1; + boolean showNamesOfSingleArguments= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG); + return !showNamesOfSingleArguments && method.getNumberOfParameters() == 1 + || method.getNumberOfParameters() == 0; + } + + private boolean skipParameterNamesCodeMinings(IMethodBinding methodBinding) { + boolean showNamesOfSingleArguments= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG); + return !showNamesOfSingleArguments && methodBinding.getParameterNames().length == 1 + || methodBinding.getParameterNames().length == 0; } private boolean skipParameterNamesCodeMinings(IMethod method, String[] parameterNames) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java index c5a5ef5569e..74a897d2cf9 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeAssistFavoritesConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2007, 2016 IBM Corporation and others. + * Copyright (c) 2007, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -208,7 +208,7 @@ private void doValidation() { if (newText.length() == 0) { status.setError(""); //$NON-NLS-1$ } else { - IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null); + IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null); if (val.matches(IStatus.ERROR)) { if (fIsEditingMember) status.setError(PreferencesMessages.FavoriteStaticMemberInputDialog_error_invalidMemberName); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java index 1e8c7b04f61..a3339a30c03 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ComplianceConfigurationBlock.java @@ -653,7 +653,7 @@ private void validateComplianceStatus() { args[1]= getVersionLabel(version); } if (JavaModelUtil.is9OrHigher(compilerCompliance)) { - if (!JavaModelUtil.is1d6OrHigher(compliance) || !fCompilerReleaseCheck.getSelection()) { + if (!fCompilerReleaseCheck.getSelection()) { if (fProject == null) { fJRE50InfoText.setText(Messages.format(PreferencesMessages.ComplianceConfigurationBlock_jrecompliance_info, args)); } else { @@ -750,7 +750,6 @@ private void updateReleaseOptionStatus() { if (!compilerCompliance.equals(compliance)) { // Discourage using compiler with version other than compliance if (JavaModelUtil.is9OrHigher(compilerCompliance)) { if (!JavaModelUtil.isVersionLessThan(compliance, compilerCompliance) - || !JavaModelUtil.is1d6OrHigher(compliance) || ( JavaModelUtil.is12OrHigher(compilerCompliance)) && !JavaModelUtil.is1d7OrHigher(compliance)) { fCompilerReleaseCheck.setEnabled(false); @@ -775,7 +774,7 @@ private void updateReleaseOptionStatus() { setValue(PREF_RELEASE, JavaCore.DISABLED); } else { if (fProject == null - || (isJREUnsupportedAndGreater && JavaModelUtil.is1d6OrHigher(compliance)) + || isJREUnsupportedAndGreater || JavaModelUtil.is9OrHigher(compliance)) { fCompilerReleaseCheck.setEnabled(true); } @@ -923,7 +922,7 @@ private void updateComplianceEnableSourceTargetState() { String complianceFollowsEE= getValue(INTR_COMPLIANCE_FOLLOWS_EE); enableComplianceControls= hasProjectSpecificOptions && !DEFAULT_CONF.equals(complianceFollowsEE); // is disabled or user } - boolean enableBasedOnRelease= !fCompilerReleaseCheck.getSelection() || !JavaModelUtil.is1d6OrHigher(getValue(PREF_COMPLIANCE)); + boolean enableBasedOnRelease= !fCompilerReleaseCheck.getSelection(); boolean enableComplianceChildren= enableComplianceControls && checkValue(INTR_DEFAULT_COMPLIANCE, USER_CONF) && enableBasedOnRelease; for (int i= fComplianceChildControls.size() - 1; i >= 0; i--) { Control curr= fComplianceChildControls.get(i); @@ -1057,7 +1056,7 @@ private void updateComplianceDefaultSettings(boolean rememberOld, String oldComp boolean isDefault= checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT_CONF); boolean isFollowEE= checkValue(INTR_COMPLIANCE_FOLLOWS_EE, DEFAULT_CONF); String complianceLevel= getValue(PREF_COMPLIANCE); - boolean isRelease= checkValue(PREF_RELEASE, JavaCore.ENABLED) && JavaModelUtil.is1d6OrHigher(complianceLevel) && !isDefault; + boolean isRelease= checkValue(PREF_RELEASE, JavaCore.ENABLED) && !isDefault; if (isDefault || isFollowEE || isRelease) { if (rememberOld) { @@ -1141,7 +1140,7 @@ private void updateComplianceDefaultSettings(boolean rememberOld, String oldComp private void updateComplianceReleaseSettings() { String compliance= getValue(PREF_COMPLIANCE); - boolean isRelease= checkValue(PREF_RELEASE, JavaCore.ENABLED) && JavaModelUtil.is1d6OrHigher(compliance); + boolean isRelease= checkValue(PREF_RELEASE, JavaCore.ENABLED); if (isRelease) { setValue(PREF_SOURCE_COMPATIBILITY, compliance); setValue(PREF_CODEGEN_TARGET_PLATFORM, compliance); @@ -1241,7 +1240,7 @@ protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { private void setDefaultCompilerComplianceValues() { IVMInstall defaultVMInstall= JavaRuntime.getDefaultVMInstall(); if (defaultVMInstall instanceof IVMInstall2) { - String complianceLevel= JavaModelUtil.getCompilerCompliance((IVMInstall2)defaultVMInstall, JavaCore.VERSION_1_4); + String complianceLevel= JavaModelUtil.getCompilerCompliance((IVMInstall2)defaultVMInstall, JavaCore.VERSION_1_8); if (isOriginalDefaultCompliance(complianceLevel)) { Map complianceOptions= new HashMap<>(); JavaModelUtil.setComplianceOptions(complianceOptions, complianceLevel); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java index f8f919640fe..77616e104ef 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -329,7 +329,7 @@ private List loadFromProperties(Properties properties) { String curr= properties.getProperty(String.valueOf(i)); if (curr != null) { ImportOrderEntry entry= ImportOrderEntry.fromSerialized(curr); - if (entry.name.length() == 0 || !JavaConventions.validatePackageName(entry.name, JavaCore.VERSION_1_3, JavaCore.VERSION_1_5).matches(IStatus.ERROR)) { + if (entry.name.length() == 0 || !JavaConventions.validatePackageName(entry.name, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8).matches(IStatus.ERROR)) { res.add(entry); } else { return null; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeInputDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeInputDialog.java index 70275877085..a56c3ea8fa4 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeInputDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizeInputDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2013 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -224,7 +224,7 @@ private void doValidation() { status.setError(PreferencesMessages.ImportOrganizeInputDialog_error_entryExists); } } else { - IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null); + IStatus val= JavaConventions.validateJavaTypeName(newText, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null); if (val.matches(IStatus.ERROR)) { status.setError(PreferencesMessages.ImportOrganizeInputDialog_error_invalidName); } else { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorCodeMiningConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorCodeMiningConfigurationBlock.java index 06c4ebfd659..acd7b42ebac 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorCodeMiningConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorCodeMiningConfigurationBlock.java @@ -81,6 +81,9 @@ public class JavaEditorCodeMiningConfigurationBlock extends OptionsConfiguration private static final Key PREF_DEFAULT_FILTER_FOR_PARAMETER_NAMES= getJDTUIKey( PreferenceConstants.EDITOR_JAVA_CODEMINING_DEFAULT_FILTER_FOR_PARAMETER_NAMES); + private static final Key PREF_SHOW_ONE_PARAMETER= getJDTUIKey( + PreferenceConstants.EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG); + private static final String SETTINGS_SECTION_NAME= "JavaEditorCodeMiningConfigurationBlock"; //$NON-NLS-1$ private static final String[] TRUE_FALSE= new String[] { "true", "false" }; //$NON-NLS-1$ //$NON-NLS-2$ @@ -101,7 +104,7 @@ public JavaEditorCodeMiningConfigurationBlock(IStatusChangeListener context, public static Key[] getAllKeys() { return new Key[] { PREF_CODEMINING_ENABLED, PREF_SHOW_CODEMINING_AT_LEAST_ONE, PREF_SHOW_REFERENCES, PREF_SHOW_REFERENCES_ON_TYPES, PREF_SHOW_REFERENCES_ON_FIELDS, PREF_SHOW_REFERENCES_ON_METHODS, - PREF_SHOW_IMPLEMENTATIONS, PREF_SHOW_PARAMETER_NAMES, PREF_IGNORE_INEXACT_MATCHES, PREF_FILTER_IMPLIED_PARAMETER_NAMES, PREF_DEFAULT_FILTER_FOR_PARAMETER_NAMES }; + PREF_SHOW_IMPLEMENTATIONS, PREF_SHOW_PARAMETER_NAMES, PREF_IGNORE_INEXACT_MATCHES, PREF_FILTER_IMPLIED_PARAMETER_NAMES, PREF_DEFAULT_FILTER_FOR_PARAMETER_NAMES, PREF_SHOW_ONE_PARAMETER }; } @Override @@ -227,6 +230,9 @@ private void createGeneralSection(int nColumns, Composite parent) { PreferencesMessages.JavaEditorCodeMiningConfigurationBlock_defaultFilterForParameterNames_label, PREF_DEFAULT_FILTER_FOR_PARAMETER_NAMES, TRUE_FALSE, extraIndent, section); + fFilteredPrefTree.addCheckBox(inner, + PreferencesMessages.JavaEditorCodeMiningShowOneParameter_label, + PREF_SHOW_ONE_PARAMETER, TRUE_FALSE, extraIndent, section); } private void updateEnableStates() { @@ -244,8 +250,11 @@ private void updateEnableStates() { // Show implementations checkboxes getCheckBox(PREF_SHOW_IMPLEMENTATIONS).getSelection(); boolean showParameterNames= getCheckBox(PREF_SHOW_PARAMETER_NAMES).getSelection(); + getCheckBox(PREF_FILTER_IMPLIED_PARAMETER_NAMES).setEnabled(showParameterNames); getCheckBox(PREF_DEFAULT_FILTER_FOR_PARAMETER_NAMES).setEnabled(showParameterNames); + getCheckBox(PREF_SHOW_ONE_PARAMETER).setEnabled(showParameterNames); + } else { atLeastOneCheckBox.setEnabled(false); ignoreInexactReferenceMatches.setEnabled(false); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java index 125583eaf10..896eba629c5 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorColoringConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -289,43 +289,10 @@ public boolean hasChildren(Object element) { } } - private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; - /** - * Preference key suffix for italic preferences. - * @since 3.0 - */ - private static final String ITALIC= PreferenceConstants.EDITOR_ITALIC_SUFFIX; - /** - * Preference key suffix for strikethrough preferences. - * @since 3.1 - */ - private static final String STRIKETHROUGH= PreferenceConstants.EDITOR_STRIKETHROUGH_SUFFIX; - /** - * Preference key suffix for underline preferences. - * @since 3.1 - */ - private static final String UNDERLINE= PreferenceConstants.EDITOR_UNDERLINE_SUFFIX; - private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; /** * The keys of the overlay store. */ - private final String[][] fSyntaxColorListModel= new String[][] { - { PreferencesMessages.JavaEditorPreferencePage_javaDocKeywords, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_javaDocHtmlTags, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_javaDocLinks, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_javaDocOthers, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_multiLineComment, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_singleLineComment, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_javaCommentTaskTags, PreferenceConstants.EDITOR_TASK_TAG_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_keywords, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_returnKeyword, PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_operators, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_brackets, PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_strings, PreferenceConstants.EDITOR_STRING_COLOR }, - { PreferencesMessages.JavaEditorPreferencePage_others, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, - }; - private final String fJavaCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_java; private final String fJavadocCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_javadoc; private final String fCommentsCategory= PreferencesMessages.JavaEditorPreferencePage_coloring_category_comments; @@ -385,8 +352,8 @@ public JavaEditorColoringConfigurationBlock(OverlayPreferenceStore store) { fColorManager= new JavaColorManager(); - for (String[] syntaxColor : fSyntaxColorListModel) - fListModel.add(new HighlightingColorListItem (syntaxColor[0], syntaxColor[1], syntaxColor[1] + BOLD, syntaxColor[1] + ITALIC, syntaxColor[1] + STRIKETHROUGH, syntaxColor[1] + UNDERLINE)); + for (SyntaxColorHighlighting syntaxColor : SyntaxColorHighlighting.getSyntaxColorHighlightings()) + fListModel.add(new HighlightingColorListItem (syntaxColor.label(), syntaxColor.preferenceKey(), syntaxColor.getBoldPreferenceKey(), syntaxColor.getItalicPreferenceKey(), syntaxColor.getStrikethroughPreferenceKey(), syntaxColor.getUnderlinePreferenceKey())); SemanticHighlighting[] semanticHighlightings= SemanticHighlightings.getSemanticHighlightings(); for (SemanticHighlighting semanticHighlighting : semanticHighlightings) @@ -815,8 +782,8 @@ private Control createPreviewer(Composite parent) { fPreviewViewer= new JavaSourceViewer(parent, null, null, false, SWT.H_SCROLL | SWT.BORDER, store); SimpleJavaSourceViewerConfiguration configuration= new SimpleJavaSourceViewerConfiguration(fColorManager, store, null, IJavaPartitions.JAVA_PARTITIONING, false); fPreviewViewer.configure(configuration); - // fake 1.5 source to get 1.5 features right. - configuration.handlePropertyChangeEvent(new PropertyChangeEvent(this, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_4, JavaCore.VERSION_1_5)); + // 1.8 source to get 1.8 features right. + configuration.handlePropertyChangeEvent(new PropertyChangeEvent(this, JavaCore.COMPILER_SOURCE, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8)); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); fPreviewViewer.getTextWidget().setFont(font); new JavaSourcePreviewerUpdater(fPreviewViewer, configuration, store); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java index 8ba052e753b..769f6199997 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -192,7 +192,7 @@ private IStatus validateIdentifiers(String[] values, boolean prefix) { } } String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$ - IStatus status= JavaConventions.validateIdentifier(name, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + IStatus status= JavaConventions.validateIdentifier(name, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); if (status.matches(IStatus.ERROR)) { if (prefix) { return new StatusInfo(IStatus.ERROR, Messages.format(PreferencesMessages.NameConventionConfigurationBlock_error_invalidprefix, val)); @@ -446,7 +446,7 @@ protected final void updateModel(DialogField field) { setValue(PREF_EXCEPTION_NAME, name); // validation - IStatus status = JavaConventions.validateIdentifier(name, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + IStatus status = JavaConventions.validateIdentifier(name, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); if (!status.isOK()) { fContext.statusChanged(status); } else { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java index d42a3534863..a1886d94f9c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.java @@ -913,6 +913,7 @@ private PreferencesMessages() { public static String JavaEditorCodeMiningConfigurationBlock_showParameterNames_label; public static String JavaEditorCodeMiningConfigurationBlock_filterImpliedParameterNames_label; public static String JavaEditorCodeMiningConfigurationBlock_defaultFilterForParameterNames_label; + public static String JavaEditorCodeMiningShowOneParameter_label; public static String JavaLaunchingConfigurationBlock_application_name_fully_qualified_label; public static String JavaLaunchingConfigurationBlock_applet_name_fully_qualified_label; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties index 9964119d413..6c16e9b0575 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/PreferencesMessages.properties @@ -1038,6 +1038,7 @@ JavaEditorCodeMiningConfigurationBlock_showImplementations_label=Show &implement JavaEditorCodeMiningConfigurationBlock_showParameterNames_label=Show method ¶meter names JavaEditorCodeMiningConfigurationBlock_defaultFilterForParameterNames_label=&Default filter for some specified methods and method parameter names (e.g. compare()) JavaEditorCodeMiningConfigurationBlock_filterImpliedParameterNames_label=Filter parameter &names that are implied by parameter +JavaEditorCodeMiningShowOneParameter_label=Show code minings when method has one parameter #Launching preferences JavaLaunchingConfigurationBlock_application_name_fully_qualified_label=Use fully qualified name for new Java Application diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SyntaxColorHighlighting.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SyntaxColorHighlighting.java new file mode 100644 index 00000000000..b53cba5175a --- /dev/null +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SyntaxColorHighlighting.java @@ -0,0 +1,62 @@ +/******************************************************************************* + * Copyright (c) 2024 Broadcom Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Alex Boyko (Broadcom Inc.) - Initial implementation + *******************************************************************************/ +package org.eclipse.jdt.internal.ui.preferences; + +import org.eclipse.jdt.ui.PreferenceConstants; + +public record SyntaxColorHighlighting(String label, String preferenceKey) { + + private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX; + private static final String ITALIC= PreferenceConstants.EDITOR_ITALIC_SUFFIX; + private static final String STRIKETHROUGH= PreferenceConstants.EDITOR_STRIKETHROUGH_SUFFIX; + private static final String UNDERLINE= PreferenceConstants.EDITOR_UNDERLINE_SUFFIX; + + private static SyntaxColorHighlighting[] fgSyntaxColorHighlighting = null; + + public static SyntaxColorHighlighting[] getSyntaxColorHighlightings() { + if (fgSyntaxColorHighlighting == null) { + fgSyntaxColorHighlighting = new SyntaxColorHighlighting[] { + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_javaDocKeywords, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_javaDocHtmlTags, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_javaDocLinks, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_javaDocOthers, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_multiLineComment, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_singleLineComment, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_javaCommentTaskTags, PreferenceConstants.EDITOR_TASK_TAG_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_keywords, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_returnKeyword, PreferenceConstants.EDITOR_JAVA_KEYWORD_RETURN_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_operators, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_brackets, PreferenceConstants.EDITOR_JAVA_BRACKET_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_strings, PreferenceConstants.EDITOR_STRING_COLOR), + new SyntaxColorHighlighting(PreferencesMessages.JavaEditorPreferencePage_others, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR) + }; + } + return fgSyntaxColorHighlighting; + } + + public String getBoldPreferenceKey() { + return preferenceKey + BOLD; + } + + public String getItalicPreferenceKey() { + return preferenceKey + ITALIC; + } + + public String getStrikethroughPreferenceKey() { + return preferenceKey + STRIKETHROUGH; + } + + public String getUnderlinePreferenceKey() { + return preferenceKey + UNDERLINE; + } + +} diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java index 9344797d149..474201768f5 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -72,7 +72,6 @@ private final static class CorePrefs { final boolean prefIndentBracesForMethods; final boolean prefIndentBracesForTypes; final int prefContinuationIndent; - final boolean prefHasGenerics; final String prefTabChar; private final IJavaProject fProject; @@ -129,7 +128,6 @@ private String getCoreFormatterOption(String key) { prefIndentBracesForArrays= false; prefIndentBracesForMethods= false; prefIndentBracesForTypes= false; - prefHasGenerics= false; prefTabChar= JavaCore.TAB; } else { prefUseTabs= prefUseTabs(); @@ -158,7 +156,6 @@ private String getCoreFormatterOption(String key) { prefIndentBracesForArrays= prefIndentBracesForArrays(); prefIndentBracesForMethods= prefIndentBracesForMethods(); prefIndentBracesForTypes= prefIndentBracesForTypes(); - prefHasGenerics= hasGenerics(); prefTabChar= getCoreFormatterOption(DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR); } } @@ -363,9 +360,6 @@ private int prefContinuationIndentForArrayInitializer() { return 2; // sensible default } - private boolean hasGenerics() { - return JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, getCoreFormatterOption(JavaCore.COMPILER_SOURCE)) <= 0; - } } /** The document being scanned. */ @@ -1593,8 +1587,6 @@ private boolean skipScope() { case Symbols.TokenRBRACE: return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE); case Symbols.TokenGREATERTHAN: - if (!fPrefs.prefHasGenerics) - return false; int storedPosition= fPosition; int storedToken= fToken; nextToken(); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaPairMatcher.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaPairMatcher.java index 0b3b85dd637..d47b225a048 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaPairMatcher.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaPairMatcher.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -20,21 +20,12 @@ import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.source.DefaultCharacterPairMatcher; -import org.eclipse.jdt.core.JavaCore; - import org.eclipse.jdt.ui.text.IJavaPartitions; /** * Helper class for match pairs of characters. */ -public final class JavaPairMatcher extends DefaultCharacterPairMatcher implements ISourceVersionDependent { - - /** - * Stores the source version state. - * @since 3.1 - */ - private boolean fHighlightAngularBrackets= false; - +public final class JavaPairMatcher extends DefaultCharacterPairMatcher { public JavaPairMatcher(char[] pairs) { super(pairs, IJavaPartitions.JAVA_PARTITIONING, true); @@ -68,8 +59,6 @@ private IRegion performMatch(IDocument document, int offset) throws BadLocationE currChar= document.getChar(offset); } - if ((prevChar == '<' || currChar == '>') && !fHighlightAngularBrackets) - return null; if (prevChar == '<' && isLessThanOperator(document, offset - 1)) return null; final IRegion region= super.match(document, offset); @@ -216,17 +205,6 @@ private boolean isTypeParameterIntroducer(String identifier) { || identifier.startsWith("private")); //$NON-NLS-1$ } - /* - * @see org.eclipse.jdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String) - */ - @Override - public void setSourceVersion(String version) { - if (JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, version) <= 0) - fHighlightAngularBrackets= true; - else - fHighlightAngularBrackets= false; - } - /* * @see org.eclipse.jface.text.source.ICharacterPairMatcherExtension#isMatchedChar(char, org.eclipse.jface.text.IDocument, int) */ diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java index 4a3cfe289a9..0570399cbb2 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/AdvancedQuickAssistProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -34,7 +34,6 @@ 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.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; @@ -115,7 +114,6 @@ import org.eclipse.jdt.internal.corext.fix.IProposableFix; import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer; import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.cleanup.CleanUpOptions; @@ -1837,7 +1835,6 @@ private static boolean getReplaceIfElseWithConditionalProposals(IInvocationConte Expression thenExpression= null; Expression elseExpression= null; - ITypeBinding exprBinding= null; if (thenStatement instanceof ReturnStatement && elseStatement instanceof ReturnStatement) { thenExpression= ((ReturnStatement) thenStatement).getExpression(); elseExpression= ((ReturnStatement) elseStatement).getExpression(); @@ -1845,7 +1842,6 @@ private static boolean getReplaceIfElseWithConditionalProposals(IInvocationConte if (declaration == null || declaration.isConstructor()) { return false; } - exprBinding= declaration.getReturnType2().resolveBinding(); } else if (thenStatement instanceof ExpressionStatement && elseStatement instanceof ExpressionStatement) { Expression inner1= ((ExpressionStatement) thenStatement).getExpression(); Expression inner2= ((ExpressionStatement) elseStatement).getExpression(); @@ -1859,7 +1855,6 @@ private static boolean getReplaceIfElseWithConditionalProposals(IInvocationConte IBinding bind2= ((Name) left2).resolveBinding(); if (bind1 == bind2 && bind1 instanceof IVariableBinding) { assigned= left1; - exprBinding= ((IVariableBinding) bind1).getType(); thenExpression= assign1.getRightHandSide(); elseExpression= assign2.getRightHandSide(); } @@ -1901,23 +1896,8 @@ private static boolean getReplaceIfElseWithConditionalProposals(IInvocationConte Expression thenCopy= (Expression) rewrite.createCopyTarget(thenExpression); Expression elseCopy= (Expression) rewrite.createCopyTarget(elseExpression); - - IJavaProject project= context.getCompilationUnit().getJavaProject(); - if (!JavaModelUtil.is50OrHigher(project)) { - ITypeBinding thenBinding= thenExpression.resolveTypeBinding(); - ITypeBinding elseBinding= elseExpression.resolveTypeBinding(); - if (thenBinding != null && elseBinding != null && exprBinding != null && !elseBinding.isAssignmentCompatible(thenBinding)) { - CastExpression castException= ast.newCastExpression(); - ImportRewrite importRewrite= proposal.createImportRewrite(context.getASTRoot()); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(node, importRewrite); - castException.setType(importRewrite.addImport(exprBinding, ast, importRewriteContext, TypeLocation.CAST)); - castException.setExpression(elseCopy); - elseCopy= castException; - } - } else if (JavaModelUtil.is1d7OrHigher(project)) { - addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression); - addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression); - } + addExplicitTypeArgumentsIfNecessary(rewrite, proposal, thenExpression); + addExplicitTypeArgumentsIfNecessary(rewrite, proposal, elseExpression); conditionalExpression.setThenExpression(thenCopy); conditionalExpression.setElseExpression(elseCopy); @@ -2963,8 +2943,6 @@ private static boolean getConvertIfElseToSwitchProposals(final IInvocationContex if (leftBinding != null) { if ("java.lang.String".equals(leftBinding.getQualifiedName())) { //$NON-NLS-1$ - if (!JavaModelUtil.is1d7OrHigher(context.getCompilationUnit().getJavaProject())) - return false; } else if (!leftBinding.isEnum()) { return false; } @@ -2981,8 +2959,6 @@ private static boolean getConvertIfElseToSwitchProposals(final IInvocationContex if (rightBinding != null) { if ("java.lang.String".equals(rightBinding.getQualifiedName())) { //$NON-NLS-1$ - if (!JavaModelUtil.is1d7OrHigher(context.getCompilationUnit().getJavaProject())) - return false; } else if (!rightBinding.isEnum()) { return false; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java index fa86dfe6ef8..9bdd21247a8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java @@ -20,13 +20,11 @@ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.eclipse.swt.graphics.Image; @@ -53,23 +51,17 @@ 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.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; -import org.eclipse.jdt.core.dom.ASTParser; 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.ArrayType; -import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; -import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CastExpression; -import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.ChildListPropertyDescriptor; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; @@ -78,25 +70,18 @@ import org.eclipse.jdt.core.dom.EnumDeclaration; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; -import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ForStatement; -import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.InfixExpression; -import org.eclipse.jdt.core.dom.Initializer; -import org.eclipse.jdt.core.dom.InstanceofExpression; -import org.eclipse.jdt.core.dom.LambdaExpression; import org.eclipse.jdt.core.dom.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.ParenthesizedExpression; import org.eclipse.jdt.core.dom.PrefixExpression; import org.eclipse.jdt.core.dom.PrimitiveType; @@ -107,18 +92,12 @@ import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Statement; -import org.eclipse.jdt.core.dom.StringLiteral; import org.eclipse.jdt.core.dom.StructuralPropertyDescriptor; import org.eclipse.jdt.core.dom.SwitchCase; -import org.eclipse.jdt.core.dom.SwitchExpression; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.ThrowStatement; -import org.eclipse.jdt.core.dom.TryStatement; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; -import org.eclipse.jdt.core.dom.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.rewrite.ASTRewrite; @@ -126,42 +105,28 @@ import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext; import org.eclipse.jdt.core.dom.rewrite.ImportRewrite.TypeLocation; import org.eclipse.jdt.core.dom.rewrite.ListRewrite; -import org.eclipse.jdt.core.refactoring.CompilationUnitChange; +import org.eclipse.jdt.core.manipulation.CUCorrectionProposalCore; -import org.eclipse.jdt.internal.core.manipulation.StubUtility; import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; import org.eclipse.jdt.internal.core.manipulation.dom.NecessaryParenthesesChecker; import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility2Core; -import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.BodyDeclarationRewrite; -import org.eclipse.jdt.internal.corext.dom.CodeScopeBuilder; -import org.eclipse.jdt.internal.corext.dom.IASTSharedValues; -import org.eclipse.jdt.internal.corext.dom.Selection; -import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.corext.fix.CleanUpConstants; import org.eclipse.jdt.internal.corext.fix.CodeStyleFixCore; -import org.eclipse.jdt.internal.corext.fix.CompilationUnitRewriteOperationsFixCore; import org.eclipse.jdt.internal.corext.fix.IProposableFix; import org.eclipse.jdt.internal.corext.fix.Java50FixCore; import org.eclipse.jdt.internal.corext.fix.RenameUnusedVariableFixCore; -import org.eclipse.jdt.internal.corext.fix.SealedClassFixCore; import org.eclipse.jdt.internal.corext.fix.StringFixCore; import org.eclipse.jdt.internal.corext.fix.TypeParametersFixCore; import org.eclipse.jdt.internal.corext.fix.UnimplementedCodeFixCore; import org.eclipse.jdt.internal.corext.fix.UnusedCodeFixCore; -import org.eclipse.jdt.internal.corext.refactoring.code.Invocations; 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.surround.ExceptionAnalyzer; -import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchAnalyzer; -import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; -import org.eclipse.jdt.internal.corext.refactoring.util.NoCommentSourceRangeComputer; -import org.eclipse.jdt.internal.corext.refactoring.util.SurroundWithAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.util.TightSourceRangeComputer; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; @@ -175,6 +140,7 @@ import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposal; +import org.eclipse.jdt.ui.text.java.correction.ASTRewriteCorrectionProposalCore; import org.eclipse.jdt.ui.text.java.correction.CUCorrectionProposal; import org.eclipse.jdt.ui.text.java.correction.ChangeCorrectionProposal; import org.eclipse.jdt.ui.text.java.correction.ICommandAccess; @@ -186,404 +152,55 @@ import org.eclipse.jdt.internal.ui.fix.StringCleanUp; import org.eclipse.jdt.internal.ui.fix.TypeParametersCleanUp; import org.eclipse.jdt.internal.ui.fix.UnimplementedCodeCleanUp; -import org.eclipse.jdt.internal.ui.fix.UnnecessaryCodeCleanUpCore; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard; import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.ChangeDescription; -import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.proposals.ChangeMethodSignatureProposalCore.RemoveDescription; import org.eclipse.jdt.internal.ui.text.correction.proposals.ConstructorFromSuperclassProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ConstructorFromSuperclassProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateNewObjectProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateNewObjectProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateObjectReferenceProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateObjectReferenceProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateVariableReferenceProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.CreateVariableReferenceProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.FixCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.LinkedNamesAssistProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.MissingAnnotationAttributesProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.MissingAnnotationAttributesProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.ModifierChangeCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ModifierChangeCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.NewCUUsingWizardProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.NewMethodCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.NewMethodCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.NewProviderMethodDeclaration; import org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposal; import org.eclipse.jdt.internal.ui.text.correction.proposals.NewVariableCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.RefactoringCorrectionProposalCore; import org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposal; +import org.eclipse.jdt.internal.ui.text.correction.proposals.ReplaceCorrectionProposalCore; import org.eclipse.jdt.internal.ui.util.ASTHelper; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; -public class LocalCorrectionsSubProcessor { - private static final String RAW_TYPE_REFERENCE_ID= "org.eclipse.jdt.ui.correction.rawTypeReference"; //$NON-NLS-1$ +public class LocalCorrectionsSubProcessor extends LocalCorrectionsBaseSubProcessor{ - private static final String ADD_EXCEPTION_TO_THROWS_ID= "org.eclipse.jdt.ui.correction.addThrowsDecl"; //$NON-NLS-1$ + private static final String RAW_TYPE_REFERENCE_ID= "org.eclipse.jdt.ui.correction.rawTypeReference"; //$NON-NLS-1$ private static final String ADD_NON_NLS_ID= "org.eclipse.jdt.ui.correction.addNonNLS"; //$NON-NLS-1$ - private static final String ADD_FIELD_QUALIFICATION_ID= "org.eclipse.jdt.ui.correction.qualifyField"; //$NON-NLS-1$ + private static final String REMOVE_UNNECESSARY_NLS_TAG_ID= "org.eclipse.jdt.ui.correction.removeNlsTag"; //$NON-NLS-1$ private static final String ADD_STATIC_ACCESS_ID= "org.eclipse.jdt.ui.correction.changeToStatic"; //$NON-NLS-1$ - private static final String REMOVE_UNNECESSARY_NLS_TAG_ID= "org.eclipse.jdt.ui.correction.removeNlsTag"; //$NON-NLS-1$ - public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ICompilationUnit cu= context.getCompilationUnit(); - - CompilationUnit astRoot= context.getASTRoot(); - ASTNode selectedNode= problem.getCoveringNode(astRoot); - if (selectedNode == null) { - return; - } - while (selectedNode != null && !(selectedNode instanceof Statement) && !(selectedNode instanceof VariableDeclarationExpression) - && (selectedNode.getLocationInParent() != LambdaExpression.BODY_PROPERTY) && !(selectedNode instanceof MethodReference)) { - selectedNode= selectedNode.getParent(); - } - if (selectedNode == null) { - return; - } - boolean isSelectedNodeThrowStatement= false; - if (selectedNode instanceof ThrowStatement) { - isSelectedNodeThrowStatement= true; - } - - int offset= selectedNode.getStartPosition(); - int length= selectedNode.getLength(); - int selectionEnd= context.getSelectionOffset() + context.getSelectionLength(); - if (selectionEnd > offset + length) { - // extend the selection if more than one statement is selected (bug 72149) - length= selectionEnd - offset; - } - - //Surround with proposals - SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length); - if (refactoring == null) - return; - - List affectedLocals= new ArrayList<>(); - SimpleName vName= null; - ITypeBinding vType= null; - if (selectedNode.getAST().apiLevel() >= ASTHelper.JLS10 && (selectedNode instanceof VariableDeclarationStatement)) { - for (Object o : ((VariableDeclarationStatement) selectedNode).fragments()) { - VariableDeclarationFragment v= ((VariableDeclarationFragment) o); - vName= v.getName(); - vType= ((VariableDeclarationStatement) selectedNode).getType().resolveBinding(); - } - - // If no references to 'var' type exist, entire statement will be placed in try block - SurroundWithTryCatchAnalyzer analyzer= new SurroundWithTryCatchAnalyzer(cu, Selection.createFromStartLength(offset, length)); - astRoot.accept(analyzer); - affectedLocals= Arrays.asList(analyzer.getAffectedLocals()).stream().map(f -> f.getName().getIdentifier()).collect(Collectors.toList()); - } - - refactoring.setLeaveDirty(true); - if (refactoring.checkActivationBasics(astRoot).isOK() && !isSelectedNodeThrowStatement) { - String label; - if ((vType != null) && (vName != null) && ASTNodes.isVarType(selectedNode, astRoot) && affectedLocals.contains(vName.getIdentifier())) { - label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_var_description, new Object[] { vName.getIdentifier(), vType.getName() }); - } else { - label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trycatch_description; - } - Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_CATCH, image); - proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel()); - proposals.add(proposal); - } - - if (JavaModelUtil.is1d7OrHigher(cu.getJavaProject())) { - refactoring= SurroundWithTryCatchRefactoring.create(cu, offset, length, true); - if (refactoring == null) - return; - - refactoring.setLeaveDirty(true); - if (refactoring.checkActivationBasics(astRoot).isOK()) { - String label; - if ((vType != null) && (vName != null) && ASTNodes.isVarType(selectedNode, astRoot) && affectedLocals.contains(vName.getIdentifier())) { - label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_var_description, new Object[] { vName.getIdentifier(), vType.getName() }); - } else { - label= CorrectionMessages.LocalCorrectionsSubProcessor_surroundwith_trymulticatch_description; - } - Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - RefactoringCorrectionProposal proposal= new RefactoringCorrectionProposal(label, cu, refactoring, IProposalRelevance.SURROUND_WITH_TRY_MULTICATCH, image); - proposal.setLinkedProposalModel(refactoring.getLinkedProposalModel()); - proposals.add(proposal); - } - } - - //Catch exception - BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); - if (decl == null) { - return; - } - - ASTNode enclosingNode= SurroundWithAnalyzer.getEnclosingNode(selectedNode); - if (enclosingNode == null) { - return; - } - - ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(enclosingNode, Selection.createFromStartLength(offset, length)); - if (uncaughtExceptions.length == 0) { - return; - } - - TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode); - AST ast= astRoot.getAST(); - if (surroundingTry != null && (ASTNodes.isParent(selectedNode, surroundingTry.getBody()) || selectedNode.getLocationInParent() == TryStatement.RESOURCES2_PROPERTY)) { - addAdditionalCatchProposal(context, proposals, cu, selectedNode, offset, length, decl, uncaughtExceptions, surroundingTry, ast); - - if (JavaModelUtil.is1d7OrHigher(cu.getJavaProject())) { - List catchClauses= surroundingTry.catchClauses(); - List filteredExceptions= SurroundWithTryCatchRefactoring.filterSubtypeExceptions(uncaughtExceptions); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - ASTRewrite rewrite= ASTRewrite.create(ast); - - if (catchClauses != null && catchClauses.size() == 1) { - String label= filteredExceptions.size() > 1 - ? CorrectionMessages.LocalCorrectionsSubProcessor_addexceptionstoexistingcatch_description - : CorrectionMessages.LocalCorrectionsSubProcessor_addexceptiontoexistingcatch_description; - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH, image); - ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); - - CatchClause catchClause= catchClauses.get(0); - Type originalType= catchClause.getException().getType(); - - if (originalType instanceof UnionType) { - UnionType unionType= (UnionType) originalType; - ListRewrite listRewrite= rewrite.getListRewrite(unionType, UnionType.TYPES_PROPERTY); - @SuppressWarnings("unchecked") - List existingTypes= new ArrayList<>(unionType.types()); - - for (int i= 0; i < filteredExceptions.size(); i++) { - Type addedType= addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i); - boolean isReplaced= false; - - for (Type existingType : existingTypes) { - if (existingType.resolveBinding().isSubTypeCompatible(filteredExceptions.get(i))) { - listRewrite.replace(existingType, addedType, null); - isReplaced= true; - break; - } - } - - if (!isReplaced) { - listRewrite.insertLast(addedType, null); - } - } - } else { - Type firstType= null; - List typesToAdd= new ArrayList<>(); - - for (int i= 0; i < filteredExceptions.size(); i++) { - Type addedType= addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i); - - if (originalType.resolveBinding().isSubTypeCompatible(filteredExceptions.get(i))) { - firstType= addedType; - } else { - typesToAdd.add(addedType); - } - } - - if (!typesToAdd.isEmpty()) { - UnionType newUnionType= ast.newUnionType(); - List types= newUnionType.types(); - - if (firstType == null) { - types.add(ASTNodes.createMoveTarget(rewrite, originalType)); - } else { - types.add(firstType); - } - types.addAll(typesToAdd); - - rewrite.replace(originalType, newUnionType, null); - } else if (firstType != null) { - rewrite.replace(originalType, firstType, null); - } - } - - proposals.add(proposal); - } else if (catchClauses != null && catchClauses.isEmpty() && filteredExceptions.size() > 1) { - String label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalmulticatch_description; - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_EXCEPTIONS_TO_EXISTING_CATCH, image); - ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); - - CodeScopeBuilder.Scope scope= CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length); - scope.setCursor(offset); - - CatchClause newCatchClause= ast.newCatchClause(); - String varName= StubUtility.getExceptionVariableName(cu.getJavaProject()); - String name= scope.createName(varName, false); - SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); - var.setName(ast.newSimpleName(name)); - - UnionType newUnionType= ast.newUnionType(); - List types= newUnionType.types(); - - for (int i= 0; i < filteredExceptions.size(); i++) { - types.add(addNewException(ast, filteredExceptions, rewrite, proposal, imports, importRewriteContext, i)); - } - - String nameKey= "name"; //$NON-NLS-1$ - proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey); - var.setType(newUnionType); - newCatchClause.setException(var); - String catchBody= StubUtility.getCatchBodyContent(cu, "Exception", name, selectedNode, String.valueOf('\n')); //$NON-NLS-1$ - - if (catchBody != null) { - ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT); - newCatchClause.getBody().statements().add(node); - } - - ListRewrite listRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY); - listRewrite.insertFirst(newCatchClause, null); - proposals.add(proposal); - } - } - } - - //Add throws declaration - if (enclosingNode instanceof MethodDeclaration) { - MethodDeclaration methodDecl= (MethodDeclaration) enclosingNode; - IMethodBinding binding= methodDecl.resolveBinding(); - boolean isApplicable= binding != null; - - if (isApplicable) { - IMethodBinding overriddenMethod= Bindings.findOverriddenMethod(binding, true); - - if (overriddenMethod != null) { - isApplicable= overriddenMethod.getDeclaringClass().isFromSource(); - - if (!isApplicable) { // bug 349051 - ITypeBinding[] exceptionTypes= overriddenMethod.getExceptionTypes(); - ArrayList unhandledExceptions= new ArrayList<>(uncaughtExceptions.length); - - for (ITypeBinding curr : uncaughtExceptions) { - if (isSubtype(curr, exceptionTypes)) { - unhandledExceptions.add(curr); - } - } - - uncaughtExceptions= unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]); - isApplicable= uncaughtExceptions.length > 0; - } - } - - if (isApplicable && binding != null) { - ITypeBinding[] methodExceptions= binding.getExceptionTypes(); - ArrayList unhandledExceptions= new ArrayList<>(uncaughtExceptions.length); - - for (ITypeBinding curr : uncaughtExceptions) { - if (!isSubtype(curr, methodExceptions)) { - unhandledExceptions.add(curr); - } - } - - uncaughtExceptions= unhandledExceptions.toArray(new ITypeBinding[unhandledExceptions.size()]); - - List exceptions= methodDecl.thrownExceptionTypes(); - int nExistingExceptions= exceptions.size(); - - ChangeDescription[] desc= new ChangeDescription[nExistingExceptions + uncaughtExceptions.length]; - for (int i= 0; i < exceptions.size(); i++) { - Type elem= exceptions.get(i); - - if (isSubtype(elem.resolveBinding(), uncaughtExceptions)) { - desc[i]= new RemoveDescription(); - } - } - - for (int i= 0; i < uncaughtExceptions.length; i++) { - desc[i + nExistingExceptions]= new InsertDescription(uncaughtExceptions[i], ""); //$NON-NLS-1$ - } - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_addthrows_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - - ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, desc, IProposalRelevance.ADD_THROWS_DECLARATION, image); - - for (int i= 0; i < uncaughtExceptions.length; i++) { - addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], proposal.getExceptionTypeGroupId(i + nExistingExceptions)); - } - - proposal.setCommandId(ADD_EXCEPTION_TO_THROWS_ID); - proposals.add(proposal); - } - } - } - } - - private static Type addNewException(AST ast, List filteredExceptions, ASTRewrite rewrite, LinkedCorrectionProposal proposal, ImportRewrite imports, - ImportRewriteContext importRewriteContext, int i) { - ITypeBinding excBinding= filteredExceptions.get(i); - Type type= imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION); - - String typeKey= "type" + i; //$NON-NLS-1$ - proposal.addLinkedPosition(rewrite.track(type), false, typeKey); - addExceptionTypeLinkProposals(proposal, excBinding, typeKey); - - return type; - } - - private static void addAdditionalCatchProposal(IInvocationContext context, Collection proposals, ICompilationUnit cu, ASTNode selectedNode, int offset, int length, - BodyDeclaration decl, - ITypeBinding[] uncaughtExceptions, TryStatement surroundingTry, AST ast) throws CoreException { - ASTRewrite rewrite= ASTRewrite.create(surroundingTry.getAST()); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_addadditionalcatch_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_ADDITIONAL_CATCH, image); - - ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot()); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(decl, imports); - - CodeScopeBuilder.Scope scope= CodeScopeBuilder.perform(decl, Selection.createFromStartLength(offset, length)).findScope(offset, length); - scope.setCursor(offset); - - ListRewrite clausesRewrite= rewrite.getListRewrite(surroundingTry, TryStatement.CATCH_CLAUSES_PROPERTY); - for (int i= 0; i < uncaughtExceptions.length; i++) { - ITypeBinding excBinding= uncaughtExceptions[i]; - String varName= StubUtility.getExceptionVariableName(cu.getJavaProject()); - String name= scope.createName(varName, false); - SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); - var.setName(ast.newSimpleName(name)); - var.setType(imports.addImport(excBinding, ast, importRewriteContext, TypeLocation.EXCEPTION)); - CatchClause newClause= ast.newCatchClause(); - newClause.setException(var); - String catchBody= StubUtility.getCatchBodyContent(cu, excBinding.getName(), name, selectedNode, String.valueOf('\n')); - if (catchBody != null) { - ASTNode node= rewrite.createStringPlaceholder(catchBody, ASTNode.RETURN_STATEMENT); - newClause.getBody().statements().add(node); - } - clausesRewrite.insertLast(newClause, null); - - String typeKey= "type" + i; //$NON-NLS-1$ - String nameKey= "name" + i; //$NON-NLS-1$ - proposal.addLinkedPosition(rewrite.track(var.getType()), false, typeKey); - proposal.addLinkedPosition(rewrite.track(var.getName()), false, nameKey); - addExceptionTypeLinkProposals(proposal, excBinding, typeKey); - } - proposals.add(proposal); - } - - private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) { - // all super classes except Object - while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$ - proposal.addLinkedPositionProposal(key, exc); - exc= exc.getSuperclass(); - } - } - - - private static boolean isSubtype(ITypeBinding curr, ITypeBinding[] addedExceptions) { - while (curr != null) { - for (ITypeBinding addedException : addedExceptions) { - if (curr == addedException) { - return true; - } - } - curr= curr.getSuperclass(); - } - return false; + new LocalCorrectionsSubProcessor().getUncaughtExceptionProposals(context, problem, proposals); } public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -641,12 +258,13 @@ public static void getUnnecessaryNLSTagProposals(IInvocationContext context, IPr /* - * Fix instance accesses and indirect (static) accesses to static fields/methods + * Fix instance accesses and indirect (static) accesses to fields/methods */ public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { IProposableFix fix= CodeStyleFixCore.createIndirectAccessToStaticFix(context.getASTRoot(), problem); + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + if (fix != null) { - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); Map options= new HashMap<>(); options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpOptions.TRUE); options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_SUBTYPE_ACCESS, CleanUpOptions.TRUE); @@ -659,7 +277,6 @@ public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProposableFix[] fixes= CodeStyleFixCore.createNonStaticAccessFixes(context.getASTRoot(), problem); if (fixes != null) { IProposableFix fix1= fixes[0]; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); Map options= new HashMap<>(); options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS, CleanUpOptions.TRUE); options.put(CleanUpConstants.MEMBER_ACCESSES_STATIC_QUALIFY_WITH_DECLARING_CLASS_INSTANCE_ACCESS, CleanUpOptions.TRUE); @@ -705,204 +322,23 @@ public static void addUnimplementedMethodsProposals(IInvocationContext context, } public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ICompilationUnit cu= context.getCompilationUnit(); - - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (!(selectedNode instanceof Name)) { - return; - } - Name name= (Name) selectedNode; - IBinding binding= name.resolveBinding(); - if (!(binding instanceof IVariableBinding)) { - return; - } - IVariableBinding varBinding= (IVariableBinding) binding; - - CompilationUnit astRoot= context.getASTRoot(); - ASTNode node= astRoot.findDeclaringNode(binding); - if (node instanceof VariableDeclarationFragment) { - ASTRewrite rewrite= ASTRewrite.create(node.getAST()); - - VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; - if (fragment.getInitializer() != null) { - return; - } - Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); - if (expression == null) { - return; - } - rewrite.set(fragment, VariableDeclarationFragment.INITIALIZER_PROPERTY, expression, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_uninitializedvariable_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.INITIALIZE_VARIABLE, image); - proposal.addLinkedPosition(rewrite.track(expression), false, "initializer"); //$NON-NLS-1$ - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getUninitializedLocalVariableProposal(context, problem, proposals); } public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode == null) { - return; - } - - TypeDeclaration typeDeclaration= null; - if (selectedNode.getLocationInParent() == TypeDeclaration.NAME_PROPERTY) { - typeDeclaration= (TypeDeclaration) selectedNode.getParent(); - } else { - BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode); - if (declaration instanceof Initializer && problem.getProblemId() == IProblem.UnhandledExceptionInDefaultConstructor) { - addUncaughtExceptionProposals(context, problem, proposals); - } - return; - } - - ITypeBinding binding= typeDeclaration.resolveBinding(); - if (binding == null || binding.getSuperclass() == null) { - return; - } - ICompilationUnit cu= context.getCompilationUnit(); - for (IMethodBinding curr : binding.getSuperclass().getDeclaredMethods()) { - if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) { - proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS)); - } - } + new LocalCorrectionsSubProcessor().getConstructorFromSuperclassProposal(context, problem, proposals); } public static void addNewObjectProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode == null) { - return; - } - ASTNode selectedExpressionStatement= ASTNodes.getParent(selectedNode, ASTNode.EXPRESSION_STATEMENT); - if (selectedExpressionStatement != null) { - ExpressionStatement expressionStatement= (ExpressionStatement) selectedExpressionStatement; - Expression expression= expressionStatement.getExpression(); - ITypeBinding binding= null; - if (expression instanceof MethodInvocation) { - Expression expression2= ((MethodInvocation) expression).getExpression(); - binding= expression2 == null ? null : expression2.resolveTypeBinding(); - } - if (binding == null) { - return; - } - ICompilationUnit cu= context.getCompilationUnit(); - CreateNewObjectProposal createNewObjectProposal= new CreateNewObjectProposal(cu, expressionStatement, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); - if (createNewObjectProposal.hasProposal()) { - proposals.add(createNewObjectProposal); - } - return; - } - - ASTNode selectedVariableDeclarationFragment= ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_FRAGMENT); - if (selectedVariableDeclarationFragment != null) { - VariableDeclarationFragment vdf= (VariableDeclarationFragment) selectedVariableDeclarationFragment; - VariableDeclarationStatement vds= (VariableDeclarationStatement) ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_STATEMENT); - if (vds == null) { - return; - } - Type type= vds.getType(); - ITypeBinding binding= type == null ? null : type.resolveBinding(); - if (binding == null) { - return; - } - ICompilationUnit cu= context.getCompilationUnit(); - CreateNewObjectProposal createNewObjectProposal= new CreateNewObjectProposal(cu, vdf, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); - if (createNewObjectProposal.hasProposal()) { - proposals.add(createNewObjectProposal); - } - /* create instance of qualifier, ex; X in X.s; */ - Expression initializer= vdf.getInitializer(); - if(initializer instanceof QualifiedName == false) { - return; - } - QualifiedName qualifiedName= (QualifiedName)initializer; - IBinding resolveBinding= qualifiedName.getName().resolveBinding(); - if(resolveBinding instanceof IVariableBinding == false) { - return; - } - CreateNewObjectProposal createNewObjectProposal2= new CreateNewObjectProposal(cu, vdf, (IVariableBinding)resolveBinding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); - if (createNewObjectProposal2.hasProposal()) { - proposals.add(createNewObjectProposal2); - } - return; - } - if (problem.getProblemId() == IProblem.StaticMethodRequested || - problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { - addUncaughtExceptionProposals(context, problem, proposals); - } + new LocalCorrectionsSubProcessor().getNewObjectProposal(context, problem, proposals); } public static void addObjectReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - ITypeBinding binding= null; - if (selectedNode == null) { - return; - } - if (problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { - if (selectedNode instanceof QualifiedName) { - QualifiedName qualifiedName= (QualifiedName) selectedNode; - Name qualifier= qualifiedName.getQualifier(); - binding= qualifier.resolveTypeBinding(); - } - } else { - selectedNode= ASTNodes.getParent(selectedNode, ASTNode.EXPRESSION_STATEMENT); - if (selectedNode == null) { - if (problem.getProblemId() == IProblem.StaticMethodRequested) { - addUncaughtExceptionProposals(context, problem, proposals); - } - return; - } - ExpressionStatement expressionStatement= (ExpressionStatement) selectedNode; - Expression expression= expressionStatement.getExpression(); - if (expression instanceof MethodInvocation) { - Expression expression2= ((MethodInvocation) expression).getExpression(); - binding= expression2 == null ? null : expression2.resolveTypeBinding(); - } - } - if (binding == null) { - return; - } - ICompilationUnit cu= context.getCompilationUnit(); - CreateObjectReferenceProposal createObjectReferenceProposal= new CreateObjectReferenceProposal(cu, selectedNode, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); - if (createObjectReferenceProposal.hasProposal()) { - proposals.add(createObjectReferenceProposal); - } + new LocalCorrectionsSubProcessor().getObjectReferenceProposal(context, problem, proposals); } public static void addVariableReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode == null) { - return; - } - selectedNode= ASTNodes.getParent(selectedNode, ASTNode.VARIABLE_DECLARATION_FRAGMENT); - if (selectedNode == null) { - if (problem.getProblemId() == IProblem.NonStaticFieldFromStaticInvocation) { - addUncaughtExceptionProposals(context, problem, proposals); - } - return; - } - VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode; - Type type= null; - if(fragment.getParent() instanceof VariableDeclarationStatement) { - type= ((VariableDeclarationStatement)fragment.getParent()).getType(); - } else if(fragment.getParent() instanceof FieldDeclaration) { - type= ((FieldDeclaration)fragment.getParent()).getType(); - } - if (type == null) { - return; - } - ITypeBinding binding= type.resolveBinding(); - if (binding == null) { - return; - } - ICompilationUnit cu= context.getCompilationUnit(); - CreateVariableReferenceProposal createVariableReferenceProposal= new CreateVariableReferenceProposal(cu, fragment, binding, IProposalRelevance.ADD_CONSTRUCTOR_FROM_SUPER_CLASS); - if (createVariableReferenceProposal.hasProposal()) { - proposals.add(createVariableReferenceProposal); - } + new LocalCorrectionsSubProcessor().getVariableReferenceProposal(context, problem, proposals); } public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -948,21 +384,7 @@ public static void addUnusedTypeParameterProposal(IInvocationContext context, IP } public static void addRedundantSuperInterfaceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (!(selectedNode instanceof Name)) { - return; - } - ASTNode node= ASTNodes.getNormalizedNode(selectedNode); - - ASTRewrite rewrite= ASTRewrite.create(node.getAST()); - rewrite.remove(node, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_redundant_superinterface; - Image image= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); - - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_REDUNDANT_SUPER_INTERFACE, image); - proposals.add(proposal); - + new LocalCorrectionsSubProcessor().getRedundantSuperInterfaceProposal(context, problem, proposals); } private static void addProposal(IInvocationContext context, Collection proposals, final UnusedCodeFixCore fix) { @@ -975,73 +397,26 @@ private static void addProposal(IInvocationContext context, Collection proposals, final RenameUnusedVariableFixCore fix) { if (fix != null) { - Image image= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_REDO); + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LINKED_RENAME); FixCorrectionProposal proposal= new FixCorrectionProposal(fix, fix.getCleanUp(), IProposalRelevance.UNUSED_MEMBER, image, context); proposals.add(proposal); } } public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - String label= CorrectionMessages.LocalCorrectionsSubProcessor_removesemicolon_description; - ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", IProposalRelevance.REMOVE_SEMICOLON); //$NON-NLS-1$ - proposals.add(proposal); + new LocalCorrectionsSubProcessor().getSuperfluousSemicolonProposal(context, problem, proposals); } public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - IProposableFix fix= UnusedCodeFixCore.createRemoveUnusedCastFix(context.getASTRoot(), problem); - if (fix != null) { - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - Map options= new Hashtable<>(); - options.put(CleanUpConstants.REMOVE_UNNECESSARY_CASTS, CleanUpOptions.TRUE); - FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new UnnecessaryCodeCleanUpCore(options), IProposalRelevance.REMOVE_UNUSED_CAST, image, context); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getUnnecessaryCastProposal(context, problem, proposals); } public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - - ASTNode curr= ASTNodes.getUnparenthesedExpression(selectedNode); - - if (curr instanceof InstanceofExpression) { - AST ast= curr.getAST(); - - ASTRewrite rewrite= ASTRewrite.create(ast); - - InstanceofExpression inst= (InstanceofExpression) curr; - - InfixExpression expression= ast.newInfixExpression(); - expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand())); - expression.setOperator(InfixExpression.Operator.NOT_EQUALS); - expression.setRightOperand(ast.newNullLiteral()); - - rewrite.replace(inst, expression, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.UNNECESSARY_INSTANCEOF, image); - proposals.add(proposal); - } - + new LocalCorrectionsSubProcessor().getUnnecessaryInstanceofProposal(context, problem, proposals); } public static void addIllegalQualifiedEnumConstantLabelProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode coveringNode= problem.getCoveringNode(context.getASTRoot()); - - ASTNode curr= ASTNodes.getUnparenthesedExpression(coveringNode); - - if (!(curr instanceof QualifiedName)) { - return; - } - - SimpleName simpleName= ((QualifiedName) curr).getName(); - final ASTRewrite rewrite= ASTRewrite.create(curr.getAST()); - rewrite.replace(coveringNode, simpleName, null); - - String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replace_with_unqualified_enum_constant, BasicElementLabels.getJavaElementName(simpleName.getIdentifier())); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_WITH_UNQUALIFIED_ENUM_CONSTANT, image); - proposals.add(proposal); + new LocalCorrectionsSubProcessor().getIllegalQualifiedEnumConstantLabelProposal(context, problem, proposals); } public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -1072,16 +447,7 @@ public static void addUnnecessaryThrownExceptionProposal(IInvocationContext cont } public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - IProposableFix fix= CodeStyleFixCore.createAddFieldQualifierFix(context.getASTRoot(), problem); - if (fix != null) { - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - Map options= new HashMap<>(); - options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS, CleanUpOptions.TRUE); - options.put(CleanUpConstants.MEMBER_ACCESSES_NON_STATIC_FIELD_USE_THIS_ALWAYS, CleanUpOptions.TRUE); - FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new CodeStyleCleanUpCore(options), IProposalRelevance.ADD_FIELD_QUALIFIER, image, context); - proposal.setCommandId(ADD_FIELD_QUALIFICATION_ID); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getUnqualifiedFieldAccessProposal(context, problem, proposals); } public static void addInvalidVariableNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -1253,89 +619,12 @@ public InfixExpression getParentInfixExpression() { } public static void getUnnecessaryElseProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - CompilationUnit root= context.getASTRoot(); - ASTNode selectedNode= problem.getCoveringNode(root); - if (selectedNode == null) { - return; - } - ASTNode parent= selectedNode.getParent(); - if (parent instanceof ExpressionStatement) { - parent= parent.getParent(); - } - if (!(parent instanceof IfStatement)) { - return; - } - IfStatement ifStatement= (IfStatement) parent; - ASTNode ifParent= ifStatement.getParent(); - if (!(ifParent instanceof Block) && !(ifParent instanceof SwitchStatement) && !ASTNodes.isControlStatementBody(ifStatement.getLocationInParent())) { - return; - } - - ASTRewrite rewrite= ASTRewrite.create(root.getAST()); - ASTNode placeholder= QuickAssistProcessor.getCopyOfInner(rewrite, ifStatement.getElseStatement(), false); - if (placeholder == null) { - return; - } - rewrite.remove(ifStatement.getElseStatement(), null); - - if (ifParent instanceof Block) { - ListRewrite listRewrite= rewrite.getListRewrite(ifParent, Block.STATEMENTS_PROPERTY); - listRewrite.insertAfter(placeholder, ifStatement, null); - } else if (ifParent instanceof SwitchStatement) { - ListRewrite listRewrite= rewrite.getListRewrite(ifParent, SwitchStatement.STATEMENTS_PROPERTY); - listRewrite.insertAfter(placeholder, ifStatement, null); - } else { - Block block= root.getAST().newBlock(); - rewrite.replace(ifStatement, block, null); - block.statements().add(rewrite.createCopyTarget(ifStatement)); - block.statements().add(placeholder); - } - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeelse_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_ELSE, image); - proposals.add(proposal); + new LocalCorrectionsSubProcessor().getUnnecessaryElseProposalsBase(context, problem, proposals); } public static void getInterfaceExtendsClassProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - CompilationUnit root= context.getASTRoot(); - ASTNode selectedNode= problem.getCoveringNode(root); - if (selectedNode == null) { - return; - } - while (selectedNode.getParent() instanceof Type) { - selectedNode= selectedNode.getParent(); - } - - StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); - if (locationInParent != TypeDeclaration.SUPERCLASS_TYPE_PROPERTY) { - return; - } - - TypeDeclaration typeDecl= (TypeDeclaration) selectedNode.getParent(); - { - ASTRewrite rewrite= ASTRewrite.create(root.getAST()); - ASTNode placeHolder= rewrite.createMoveTarget(selectedNode); - ListRewrite interfaces= rewrite.getListRewrite(typeDecl, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY); - interfaces.insertFirst(placeHolder, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_extendstoimplements_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_EXTENDS_TO_IMPLEMENTS, image); - proposals.add(proposal); - } - { - ASTRewrite rewrite= ASTRewrite.create(root.getAST()); - - rewrite.set(typeDecl, TypeDeclaration.INTERFACE_PROPERTY, Boolean.TRUE, null); - - String typeName= typeDecl.getName().getIdentifier(); - String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_classtointerface_description, BasicElementLabels.getJavaElementName(typeName)); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.CHANGE_CLASS_TO_INTERFACE, image); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getInterfaceExtendsClassProposalsBase(context, problem, proposals); } public static void createNewTypeAsPermittedSubTypeProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int relevance) throws JavaModelException { @@ -1385,38 +674,11 @@ public static void createNewTypeAsPermittedSubTypeProposal(IInvocationContext co } public static void addTypeAsPermittedSubTypeProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - SealedClassFixCore fix= SealedClassFixCore.addTypeAsPermittedSubTypeProposal(context.getASTRoot(), problem); - if (fix != null) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - IType sealedType= SealedClassFixCore.getSealedType(selectedNode); - ICompilationUnit unit= SealedClassFixCore.getCompilationUnitForSealedType(sealedType); - - CUCorrectionProposal proposal= createCorrectionProposalFromCURewriteOperation(unit, fix, fix.getDisplayString(), IProposalRelevance.DECLARE_SEALED_AS_DIRECT_SUPER_TYPE, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getTypeAsPermittedSubTypeProposal(context, problem, proposals); } public static void addSealedAsDirectSuperTypeProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - SealedClassFixCore fix= SealedClassFixCore.addSealedAsDirectSuperTypeProposal(context.getASTRoot(), problem); - if (fix != null) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - IType permittedType= SealedClassFixCore.getPermittedType(selectedNode); - ICompilationUnit unit= permittedType.getCompilationUnit(); - - CUCorrectionProposal proposal= createCorrectionProposalFromCURewriteOperation(unit, fix, fix.getDisplayString(), IProposalRelevance.DECLARE_SEALED_AS_DIRECT_SUPER_TYPE, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); - proposals.add(proposal); - } - } - - private static CUCorrectionProposal createCorrectionProposalFromCURewriteOperation(ICompilationUnit unit, CompilationUnitRewriteOperationsFixCore fix, String label, int relevance, Image image) { - try { - CompilationUnitChange change= fix.createChange(null); - CUCorrectionProposal proposal= new CUCorrectionProposal(label, unit, change, relevance, image); - return proposal; - } catch (CoreException e) { - // do nothing - } - return null; + new LocalCorrectionsSubProcessor().getSealedAsDirectSuperTypeProposal(context, problem, proposals); } public static void getUnreachableCodeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -1683,84 +945,11 @@ public static void getUnusedObjectAllocationProposals(IInvocationContext context } public static void getAssignmentHasNoEffectProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - CompilationUnit root= context.getASTRoot(); - ASTNode selectedNode= problem.getCoveringNode(root); - if (!(selectedNode instanceof Assignment)) { - return; - } - ASTNode assignedNode= ((Assignment) selectedNode).getLeftHandSide(); - ASTNode assignExpression= ((Assignment) selectedNode).getRightHandSide(); - if (!(assignedNode instanceof SimpleName) && !(assignExpression instanceof SimpleName)) { - return; - } - - IBinding binding= (assignedNode instanceof SimpleName) ? ((SimpleName) assignedNode).resolveBinding() : ((SimpleName) assignExpression).resolveBinding(); - if (!(binding instanceof IVariableBinding)) { - return; - } - ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); - if (typeBinding == null) { - return; - } - IVariableBinding fieldBinding= Bindings.findFieldInHierarchy(typeBinding, binding.getName()); - if (fieldBinding == null || fieldBinding.getDeclaringClass() != typeBinding && Modifier.isPrivate(fieldBinding.getModifiers())) { - return; - } - - if (binding != fieldBinding) { - if (assignedNode instanceof SimpleName) { - String label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_left_hand_side_description; - proposals.add(createNoSideEffectProposal(context, (SimpleName) assignedNode, fieldBinding, label, IProposalRelevance.QUALIFY_LHS)); - } - if (assignExpression instanceof SimpleName) { - String label= CorrectionMessages.LocalCorrectionsSubProcessor_qualify_right_hand_side_description; - proposals.add(createNoSideEffectProposal(context, (SimpleName) assignExpression, fieldBinding, label, IProposalRelevance.QUALIFY_RHS)); - } - } - - if (binding == fieldBinding && ASTResolving.findParentBodyDeclaration(selectedNode) instanceof MethodDeclaration) { - SimpleName simpleName= (SimpleName) ((assignedNode instanceof SimpleName) ? assignedNode : assignExpression); - String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createparameter_description, BasicElementLabels.getJavaElementName(simpleName.getIdentifier())); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); - proposals.add(new NewVariableCorrectionProposal(label, context.getCompilationUnit(), NewVariableCorrectionProposalCore.PARAM, simpleName, null, IProposalRelevance.CREATE_PARAMETER, image)); - } - - - } - - private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) { - AST ast= nodeToQualify.getAST(); - - Expression qualifier; - if (Modifier.isStatic(fieldBinding.getModifiers())) { - ITypeBinding declaringClass= fieldBinding.getDeclaringClass(); - qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName()); - } else { - qualifier= ast.newThisExpression(); - } - - ASTRewrite rewrite= ASTRewrite.create(ast); - FieldAccess access= ast.newFieldAccess(); - access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify)); - access.setExpression(qualifier); - rewrite.replace(nodeToQualify, access, null); - - - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image); + new LocalCorrectionsSubProcessor().getAssignmentHasNoEffectProposalsBase(context, problem, proposals); } public static void addValueForAnnotationProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ICompilationUnit cu= context.getCompilationUnit(); - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof Annotation) { - Annotation annotation= (Annotation) selectedNode; - if (annotation.resolveTypeBinding() == null) { - return; - } - MissingAnnotationAttributesProposal proposal= new MissingAnnotationAttributesProposal(cu, annotation, 10); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getValueForAnnotationProposals(context, problem, proposals); } public static void addTypePrametersToRawTypeReference(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -1943,484 +1132,39 @@ public static void addRemoveRedundantTypeArgumentsProposals(IInvocationContext c } public static void addFallThroughProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof SwitchCase && selectedNode.getLocationInParent() == SwitchStatement.STATEMENTS_PROPERTY) { - AST ast= selectedNode.getAST(); - ASTNode parent= selectedNode.getParent(); - - // insert break: - ASTRewrite rewrite= ASTRewrite.create(ast); - ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - listRewrite.insertBefore(ast.newBreakStatement(), selectedNode, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_break_statement; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_BREAK_STATEMENT, image); - proposals.add(proposal); - - if (problem.getProblemId() == IProblem.IllegalFallthroughToPattern) - return; - - // insert //$FALL-THROUGH$: - rewrite= ASTRewrite.create(ast); - rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); - listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - ASTNode fallThroughComment= rewrite.createStringPlaceholder("//$FALL-THROUGH$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ - listRewrite.insertBefore(fallThroughComment, selectedNode, null); - - label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_fall_through; - image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_FALL_THROUGH, image); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().getFallThroughProposals(context, problem, proposals); } public static void addCasesOmittedProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof Expression && selectedNode.getLocationInParent() == SwitchStatement.EXPRESSION_PROPERTY) { - AST ast= selectedNode.getAST(); - SwitchStatement parent= (SwitchStatement) selectedNode.getParent(); - - for (Statement statement : (List) parent.statements()) { - if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { - - // insert //$CASES-OMITTED$: - ASTRewrite rewrite= ASTRewrite.create(ast); - rewrite.setTargetSourceRangeComputer(new NoCommentSourceRangeComputer()); - ListRewrite listRewrite= rewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - ASTNode casesOmittedComment= rewrite.createStringPlaceholder("//$CASES-OMITTED$", ASTNode.EMPTY_STATEMENT); //$NON-NLS-1$ - listRewrite.insertBefore(casesOmittedComment, statement, null); - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_insert_cases_omitted; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.INSERT_CASES_OMITTED, image); - proposals.add(proposal); - break; - } - } - } + new LocalCorrectionsSubProcessor().getCasesOmittedProposals(context, problem, proposals); } public static void addDeprecatedFieldsToMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof Name) { - IBinding binding= ((Name) selectedNode).resolveBinding(); - if (binding instanceof IVariableBinding) { - IVariableBinding variableBinding= (IVariableBinding) binding; - if (variableBinding.isField()) { - String qualifiedName= variableBinding.getDeclaringClass().getTypeDeclaration().getQualifiedName(); - String fieldName= variableBinding.getName(); - String[] methodName= getMethod(JavaModelUtil.concatenateName(qualifiedName, fieldName)); - if (methodName != null) { - AST ast= selectedNode.getAST(); - ASTRewrite astRewrite= ASTRewrite.create(ast); - ImportRewrite importRewrite= StubUtility.createImportRewrite(context.getASTRoot(), true); - - MethodInvocation method= ast.newMethodInvocation(); - String qfn= importRewrite.addImport(methodName[0]); - method.setExpression(ast.newName(qfn)); - method.setName(ast.newSimpleName(methodName[1])); - ASTNode parent= selectedNode.getParent(); - ICompilationUnit cu= context.getCompilationUnit(); - // add explicit type arguments if necessary (for 1.8 and later, we're optimistic that inference just works): - if (Invocations.isInvocationWithArguments(parent) && !JavaModelUtil.is1d8OrHigher(cu.getJavaProject())) { - IMethodBinding methodBinding= Invocations.resolveBinding(parent); - if (methodBinding != null) { - ITypeBinding[] parameterTypes= methodBinding.getParameterTypes(); - int i= Invocations.getArguments(parent).indexOf(selectedNode); - if (parameterTypes.length >= i && parameterTypes[i].isParameterizedType()) { - ITypeBinding[] typeArguments= parameterTypes[i].getTypeArguments(); - for (ITypeBinding typeArgument : typeArguments) { - typeArgument= Bindings.normalizeForDeclarationUse(typeArgument, ast); - if (!TypeRules.isJavaLangObject(typeArgument)) { - // add all type arguments if at least one is found to be necessary: - List typeArgumentsList= method.typeArguments(); - for (ITypeBinding t : typeArguments) { - typeArgument= Bindings.normalizeForDeclarationUse(t, ast); - typeArgumentsList.add(importRewrite.addImport(typeArgument, ast)); - } - break; - } - } - } - } - } - - astRewrite.replace(selectedNode, method, null); - - String label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_replacefieldaccesswithmethod_description, - BasicElementLabels.getJavaElementName(ASTNodes.asString(method))); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, astRewrite, IProposalRelevance.REPLACE_FIELD_ACCESS_WITH_METHOD, image); - proposal.setImportRewrite(importRewrite); - proposals.add(proposal); - } - } - } - } - } - - private static Map resolveMap; - - private static String[] getMethod(String fieldName) { - if (resolveMap == null) { - resolveMap= new HashMap<>(); - resolveMap.put("java.util.Collections.EMPTY_MAP", new String[] { "java.util.Collections", "emptyMap" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - resolveMap.put("java.util.Collections.EMPTY_SET", new String[] { "java.util.Collections", "emptySet" }); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - resolveMap.put("java.util.Collections.EMPTY_LIST", new String[] { "java.util.Collections", "emptyList" });//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$ - } - return resolveMap.get(fieldName); + new LocalCorrectionsSubProcessor().getDeprecatedFieldsToMethodsProposals(context, problem, proposals); } public static void getMissingEnumConstantCaseProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { - for (ICommandAccess proposal : proposals) { - if (proposal instanceof ChangeCorrectionProposal) { - if (CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description.equals(((ChangeCorrectionProposal) proposal).getName())) { - return; - } - } - } - - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof Expression) { - StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); - ASTNode parent= selectedNode.getParent(); - ITypeBinding binding; - List statements; - - if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) { - SwitchStatement statement= (SwitchStatement) parent; - binding= statement.getExpression().resolveTypeBinding(); - statements= statement.statements(); - } else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) { - SwitchExpression switchExpression= (SwitchExpression) parent; - binding= switchExpression.getExpression().resolveTypeBinding(); - statements= switchExpression.statements(); - } else { - return; - } - - if (binding == null || !binding.isEnum()) { - return; - } - - ArrayList missingEnumCases= new ArrayList<>(); - boolean hasDefault= evaluateMissingSwitchCases(binding, statements, missingEnumCases); - if (missingEnumCases.size() == 0 && hasDefault) - return; - - createMissingCaseProposals(context, parent, missingEnumCases, proposals); - } + new LocalCorrectionsSubProcessor().getMissingEnumConstantCaseProposalsBase(context, problem, proposals); } - @SuppressWarnings("deprecation") public static boolean evaluateMissingSwitchCases(ITypeBinding enumBindings, List switchStatements, ArrayList enumConstNames) { - for (IVariableBinding field : enumBindings.getDeclaredFields()) { - if (field.isEnumConstant()) { - enumConstNames.add(field.getName()); - } - } - - boolean hasDefault= false; - for (Statement curr : switchStatements) { - if (curr instanceof SwitchCase) { - SwitchCase switchCase= (SwitchCase) curr; - if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(switchCase.getAST())) { - List expressions= switchCase.expressions(); - if (expressions.size() == 0) { - hasDefault= true; - } else { - for (Expression expression : expressions) { - if (expression instanceof SimpleName) { - enumConstNames.remove(((SimpleName) expression).getFullyQualifiedName()); - } - } - } - } else { - Expression expression= ((SwitchCase) curr).getExpression(); - if (expression instanceof SimpleName) { - enumConstNames.remove(((SimpleName) expression).getFullyQualifiedName()); - } else if (expression == null) { - hasDefault= true; - } - } - } - } - return hasDefault; + return new LocalCorrectionsSubProcessor().evaluateMissingSwitchCasesBase(enumBindings, switchStatements, enumConstNames); } - @SuppressWarnings("deprecation") public static void createMissingCaseProposals(IInvocationContext context, ASTNode parent, ArrayList enumConstNames, Collection proposals) { - List statements; - Expression expression; - if (parent instanceof SwitchStatement) { - SwitchStatement switchStatement= (SwitchStatement) parent; - statements= switchStatement.statements(); - expression= switchStatement.getExpression(); - } else if (parent instanceof SwitchExpression) { - SwitchExpression switchExpression= (SwitchExpression) parent; - statements= switchExpression.statements(); - expression= switchExpression.getExpression(); - } else { - return; - } - int defaultIndex= statements.size(); - for (int i= 0; i < statements.size(); i++) { - Statement curr= statements.get(i); - if (curr instanceof SwitchCase) { - SwitchCase switchCase= (SwitchCase) curr; - if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(switchCase.getAST())) { - if (switchCase.expressions().size() == 0) { - defaultIndex= i; - break; - } - } else if (switchCase.getExpression() == null) { - defaultIndex= i; - break; - } - } - } - boolean hasDefault= defaultIndex < statements.size(); - - AST ast= parent.getAST(); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - - if (enumConstNames.size() > 0) { - ASTRewrite astRewrite= ASTRewrite.create(ast); - ListRewrite listRewrite; - if (parent instanceof SwitchStatement) { - listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - } else { - listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); - } - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_missing_cases_description; - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_CASE_STATEMENTS, image); - - for (String enumConstName : enumConstNames) { - SwitchCase newSwitchCase= ast.newSwitchCase(); - Name newName= ast.newName(enumConstName); - if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(ast)) { - newSwitchCase.expressions().add(newName); - } else { - newSwitchCase.setExpression(newName); - } - listRewrite.insertAt(newSwitchCase, defaultIndex, null); - defaultIndex++; - if (!hasDefault) { - if (ASTHelper.isSwitchExpressionNodeSupportedInAST(ast)) { - if (statements.size() > 0) { - Statement firstStatement= statements.get(0); - SwitchCase switchCase= (SwitchCase) firstStatement; - boolean isArrow= switchCase.isSwitchLabeledRule(); - newSwitchCase.setSwitchLabeledRule(isArrow); - if (isArrow || parent instanceof SwitchExpression) { - ThrowStatement newThrowStatement= getThrowForUnsupportedCase(expression, ast, astRewrite); - listRewrite.insertLast(newThrowStatement, null); - proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, enumConstName); - } else { - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - } else { - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - } else { - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - - defaultIndex++; - } - } - if (!hasDefault) { - SwitchCase newSwitchCase= ast.newSwitchCase(); - listRewrite.insertAt(newSwitchCase, defaultIndex, null); - defaultIndex++; - - if (ASTHelper.isSwitchExpressionNodeSupportedInAST(ast)) { - if (statements.size() > 0) { - Statement firstStatement= statements.get(0); - SwitchCase switchCase= (SwitchCase) firstStatement; - boolean isArrow= switchCase.isSwitchLabeledRule(); - newSwitchCase.setSwitchLabeledRule(isArrow); - if (isArrow || parent instanceof SwitchExpression) { - ThrowStatement newThrowStatement= getThrowForUnexpectedDefault(expression, ast, astRewrite); - listRewrite.insertLast(newThrowStatement, null); - proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, "defaultCase"); //$NON-NLS-1$ - } else { - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - } else { - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - } else { - newSwitchCase.setExpression(null); - listRewrite.insertAt(ast.newBreakStatement(), defaultIndex, null); - } - } - proposals.add(proposal); - } - if (!hasDefault) { - createMissingDefaultProposal(context, parent, image, proposals); - } - } - - private static ThrowStatement getThrowForUnsupportedCase(Expression switchExpr, AST ast, ASTRewrite astRewrite) { - ThrowStatement newThrowStatement= ast.newThrowStatement(); - ClassInstanceCreation newCic= ast.newClassInstanceCreation(); - newCic.setType(ast.newSimpleType(ast.newSimpleName("UnsupportedOperationException"))); //$NON-NLS-1$ - InfixExpression newInfixExpr= ast.newInfixExpression(); - StringLiteral newStringLiteral= ast.newStringLiteral(); - newStringLiteral.setLiteralValue("Unimplemented case: "); //$NON-NLS-1$ - newInfixExpr.setLeftOperand(newStringLiteral); - newInfixExpr.setOperator(InfixExpression.Operator.PLUS); - newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpr)); - newCic.arguments().add(newInfixExpr); - newThrowStatement.setExpression(newCic); - return newThrowStatement; + new LocalCorrectionsSubProcessor().createMissingCaseProposalsBase(context, parent, enumConstNames, proposals); } public static void removeDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - - if (selectedNode instanceof SwitchCase && ((SwitchCase) selectedNode).isDefault()) { - ASTNode parent= selectedNode.getParent(); - List statements; - if (parent instanceof SwitchStatement) { - statements= ((SwitchStatement) parent).statements(); - } else if (parent instanceof SwitchExpression) { - statements= ((SwitchExpression) parent).statements(); - } else { - return; - } - - ASTRewrite astRewrite= ASTRewrite.create(parent.getAST()); - ListRewrite listRewrite; - if (parent instanceof SwitchStatement) { - listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - } else { - listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); - } - - int indexOfDefaultCase= statements.indexOf(selectedNode); - if (indexOfDefaultCase != -1) { - listRewrite.remove(statements.get(indexOfDefaultCase), null); - int indexOfDefaultStatement= indexOfDefaultCase + 1; - if (indexOfDefaultStatement < statements.size()) { - listRewrite.remove(statements.get(indexOfDefaultStatement), null); - } - } else { - return; - } - - String label= CorrectionMessages.LocalCorrectionsSubProcessor_remove_default_case_description; - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); - ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE, image); - proposals.add(proposal); - } + new LocalCorrectionsSubProcessor().removeDefaultCaseProposalBase(context, problem, proposals); } - public static void addMissingDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); - if (selectedNode instanceof Expression) { - StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); - ASTNode parent= selectedNode.getParent(); - List statements; - - if (locationInParent == SwitchStatement.EXPRESSION_PROPERTY) { - statements= ((SwitchStatement) parent).statements(); - } else if (locationInParent == SwitchExpression.EXPRESSION_PROPERTY) { - statements= ((SwitchExpression) parent).statements(); - } else { - return; - } - - for (Statement statement : statements) { - if (statement instanceof SwitchCase && ((SwitchCase) statement).isDefault()) { - return; - } - } - Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); - createMissingDefaultProposal(context, parent, image, proposals); - } + public static void addPermittedTypesProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + new LocalCorrectionsSubProcessor().getPermittedTypesProposal(context, problem, proposals); } - private static void createMissingDefaultProposal(IInvocationContext context, ASTNode parent, Image image, Collection proposals) { - List statements; - Expression expression; - if (parent instanceof SwitchStatement) { - SwitchStatement switchStatement= (SwitchStatement) parent; - statements= switchStatement.statements(); - expression= switchStatement.getExpression(); - } else if (parent instanceof SwitchExpression) { - SwitchExpression switchExpression= (SwitchExpression) parent; - statements= switchExpression.statements(); - expression= switchExpression.getExpression(); - } else { - return; - } - AST ast= parent.getAST(); - ASTRewrite astRewrite= ASTRewrite.create(ast); - ListRewrite listRewrite; - if (parent instanceof SwitchStatement) { - listRewrite= astRewrite.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - } else { - listRewrite= astRewrite.getListRewrite(parent, SwitchExpression.STATEMENTS_PROPERTY); - } - String label= CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_description; - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, context.getCompilationUnit(), astRewrite, IProposalRelevance.ADD_MISSING_DEFAULT_CASE, image); - - SwitchCase newSwitchCase= ast.newSwitchCase(); - listRewrite.insertLast(newSwitchCase, null); - boolean offerSwitchLabel= false; - - if (ASTHelper.isSwitchCaseExpressionsSupportedInAST(ast)) { - boolean isArrow= false; - if (statements.size() > 0) { - Statement firstStatement= statements.get(0); - SwitchCase switchCase= (SwitchCase) firstStatement; - isArrow= switchCase.isSwitchLabeledRule(); - newSwitchCase.setSwitchLabeledRule(isArrow); - } - if (isArrow || parent instanceof SwitchExpression) { - ThrowStatement newThrowStatement= getThrowForUnexpectedDefault(expression, ast, astRewrite); - listRewrite.insertLast(newThrowStatement, null); - proposal.addLinkedPosition(astRewrite.track(newThrowStatement), true, null); - } else { - listRewrite.insertLast(ast.newBreakStatement(), null); - offerSwitchLabel= statements.size() == 0; - } - } else { - listRewrite.insertLast(ast.newBreakStatement(), null); - } - - proposals.add(proposal); - - if (offerSwitchLabel) { - ASTRewrite astRewrite2= ASTRewrite.create(ast); - ListRewrite listRewrite2= astRewrite2.getListRewrite(parent, SwitchStatement.STATEMENTS_PROPERTY); - String label2= CorrectionMessages.LocalCorrectionsSubProcessor_add_default_case_label_description; - LinkedCorrectionProposal proposal2= new LinkedCorrectionProposal(label2, context.getCompilationUnit(), astRewrite2, IProposalRelevance.ADD_MISSING_DEFAULT_CASE, image); - SwitchCase newSwitchCase2= ast.newSwitchCase(); - listRewrite2.insertLast(newSwitchCase2, null); - newSwitchCase2.setSwitchLabeledRule(true); - listRewrite2.insertLast(astRewrite2.createStringPlaceholder("{}", ASTNode.BLOCK), null); //$NON-NLS-1$ - proposals.add(proposal2); - } - } - - private static ThrowStatement getThrowForUnexpectedDefault(Expression switchExpression, AST ast, ASTRewrite astRewrite) { - ThrowStatement newThrowStatement= ast.newThrowStatement(); - ClassInstanceCreation newCic= ast.newClassInstanceCreation(); - newCic.setType(ast.newSimpleType(ast.newSimpleName("IllegalArgumentException"))); //$NON-NLS-1$ - InfixExpression newInfixExpr= ast.newInfixExpression(); - StringLiteral newStringLiteral= ast.newStringLiteral(); - newStringLiteral.setLiteralValue("Unexpected value: "); //$NON-NLS-1$ - newInfixExpr.setLeftOperand(newStringLiteral); - newInfixExpr.setOperator(InfixExpression.Operator.PLUS); - newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpression)); - newCic.arguments().add(newInfixExpr); - newThrowStatement.setExpression(newCic); - return newThrowStatement; + public static void addMissingDefaultCaseProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { + new LocalCorrectionsSubProcessor().getMissingDefaultCaseProposal(context, problem, proposals); } public static void addMissingHashCodeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) { @@ -2539,225 +1283,184 @@ public static void getConvertLambdaToAnonymousClassCreationsProposals(IInvocatio } public static void addOverrideDefaultMethodProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { - CompilationUnit astRoot= context.getASTRoot(); + new LocalCorrectionsSubProcessor().getOverrideDefaultMethodProposal(context, problem, proposals); + } - ASTNode selectedNode= problem.getCoveringNode(astRoot); - if (selectedNode == null) { + public static void addServiceProviderProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + ASTNode node= problem.getCoveredNode(context.getASTRoot()); + if (!(node instanceof Name) || !(node.getParent() instanceof ProvidesDirective)) { return; } - StructuralPropertyDescriptor locationInParent= selectedNode.getLocationInParent(); - if (locationInParent != TypeDeclaration.NAME_PROPERTY && locationInParent != EnumDeclaration.NAME_PROPERTY) { - return; - } + Name name= (Name) node; + ProvidesDirective prov= (ProvidesDirective) name.getParent(); + ITypeBinding targetBinding= name.resolveTypeBinding(); + ITypeBinding serviceBinding= prov.getName().resolveTypeBinding(); + if (targetBinding != null && serviceBinding != null) { + ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); - ASTNode typeNode= selectedNode.getParent(); - if (typeNode == null) { - return; + IJavaProject proj= context.getCompilationUnit().getJavaProject(); + IType type= proj.findType(serviceBinding.getQualifiedName()); + Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); + proposals.add(new NewProviderMethodDeclaration( + Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_add_provider_method_description, type.getElementName()), + targetCU, context.getASTRoot(), targetBinding, + IProposalRelevance.CREATE_METHOD, image, type)); } + } - ITypeBinding typeBinding= ((AbstractTypeDeclaration) typeNode).resolveBinding(); - if (typeBinding == null) { - return; - } + public static void addServiceProviderConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { + new LocalCorrectionsSubProcessor().getServiceProviderConstructorProposals(context, problem, proposals); + } - if (problem.getProblemId() == IProblem.DuplicateInheritedDefaultMethods) { - String[] args= problem.getProblemArguments(); - if (args.length < 5) { - return; - } + private LocalCorrectionsSubProcessor() { + } - String methodName= args[0]; - if (methodName == null) { - return; - } + @Override + protected ICommandAccess refactoringCorrectionProposalToT(RefactoringCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); + return new RefactoringCorrectionProposal(core, image); + } - String[] parameters1= {}; - if (args[1] != null && args[1].length() != 0) { - parameters1= args[1].split(", "); //$NON-NLS-1$ + @Override + protected ICommandAccess linkedCorrectionProposalToT(LinkedCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); + switch (uid) { + case INITIALIZE_VARIABLE, RETURN_ALLOCATED_OBJECT, ADD_MISSING_CASE, + CREATE_DEFAULT, ADD_PERMITTED_TYPES -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); } - String[] parameters2= {}; - if (args[2] != null && args[2].length() != 0) { - parameters2= args[2].split(", "); //$NON-NLS-1$ + case ADD_OVERRIDE -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } + } + return new LinkedCorrectionProposal(core, image); + } - addOverrideProposal(typeNode, typeBinding, methodName, parameters1, args[3], context, proposals); - addOverrideProposal(typeNode, typeBinding, methodName, parameters2, args[4], context, proposals); - - } else if (problem.getProblemId() == IProblem.InheritedDefaultMethodConflictsWithOtherInherited) { - String[] args= problem.getProblemArguments(); - if (args.length < 3) { - return; - } + @Override + protected ICommandAccess changeMethodSignatureProposalToT(ChangeMethodSignatureProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); + return new ChangeMethodSignatureProposal(core, image); + } - String arg0= args[0]; - if (arg0 == null) { - return; + @Override + protected ICommandAccess fixCorrectionProposalToT(FixCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + switch (uid) { + case STATIC_INDIRECT_ACCESS, STATIC_NON_STATIC_ACCESS_USING_TYPE, + STATIC_INSTANCE_ACCESS, REMOVE_UNNECESSARY_CAST, UNQUALIFIED_FIELD_ACCESS -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); } - int indexOfLParen= arg0.indexOf('('); - if (indexOfLParen == -1) { - return; + case UNUSED_CODE -> { + image= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); } - int indexOfRParen= arg0.indexOf(')'); - if (indexOfRParen == -1) { - return; + case RENAME_CODE -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LINKED_RENAME); } + } + return new FixCorrectionProposal(core, image); + } - String methodName= arg0.substring(0, indexOfLParen); + @Override + protected ICommandAccess constructorFromSuperClassProposalToT(ConstructorFromSuperclassProposalCore constructorFromSuperclassProposalCore, int uid) { + return new ConstructorFromSuperclassProposal(constructorFromSuperclassProposalCore); + } - String paramString= arg0.substring(indexOfLParen + 1, indexOfRParen); - String[] parameters= {}; - if (paramString != null && paramString.length() != 0) { - parameters= paramString.split(", "); //$NON-NLS-1$ - } + @Override + protected ICommandAccess createNewObjectProposalToT(CreateNewObjectProposalCore core, int uid) { + return new CreateNewObjectProposal(core); + } - addOverrideProposal(typeNode, typeBinding, methodName, parameters, args[1], context, proposals); - addOverrideProposal(typeNode, typeBinding, methodName, parameters, args[2], context, proposals); + @Override + protected ICommandAccess createObjectReferenceProposalToT(CreateObjectReferenceProposalCore core, int uid) { + return new CreateObjectReferenceProposal(core); + } - } + @Override + protected ICommandAccess createVariableReferenceProposalToT(CreateVariableReferenceProposalCore core, int uid) { + return new CreateVariableReferenceProposal(core); } - private static void addOverrideProposal(ASTNode typeNode, ITypeBinding typeBinding, String methodName, String[] parameters, String superType, - IInvocationContext context, Collection proposals) { - ITypeBinding superTypeBinding= null; - if (superType != null) { - int i= superType.indexOf('<'); - if (i > 0) { - superType= superType.substring(0, i); + @Override + protected ICommandAccess astRewriteCorrectionProposalToT(ASTRewriteCorrectionProposalCore core, int uid) { + Image image= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); + switch (uid) { + case REMOVE_REDUNDANT_SUPERINTERFACE, REMOVE_PROPOSAL -> { + image= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); + } + case REMOVE_UNNECESSARY_INSTANCEOF, UNQUALIFY_ENUM_CONSTANT, + MOVE_ELSE_CLAUSE, CHANGE_EXTENDS_TO_IMPLEMENTS, CHANGE_TO_INTERFACE, + CHANGE_CODE, INSERT_BREAK_STATEMENT, INSERT_FALL_THROUGH, INSERT_CASES_OMITTED, + REPLACE_FIELD_ACCESS -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + } + case REMOVE_DEFAULT -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); } - superTypeBinding= Bindings.findTypeInHierarchy(typeBinding, superType); - } - if (superTypeBinding == null) { - return; - } - - IMethodBinding methodToOverride= Bindings.findMethodWithDeclaredParameterTypesInType(superTypeBinding, methodName, parameters); - if (methodToOverride == null) { - return; } + return new ASTRewriteCorrectionProposal(core, image); + } - String label; - int modifiers= methodToOverride.getModifiers(); - if (Modifier.isDefault(modifiers)) { - label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_override_default_method_description, superTypeBinding.getName()); - } else if (Modifier.isAbstract(modifiers)) { - label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_implement_method_description, superTypeBinding.getName()); - } else { - label= Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_override_method_description, superTypeBinding.getName()); - } - Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); + @Override + protected ICommandAccess replaceCorrectionProposalToT(ReplaceCorrectionProposalCore core, int uid) { + return new ReplaceCorrectionProposal(core); + } - CompilationUnit astRoot= context.getASTRoot(); - ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST()); - ICompilationUnit cu= context.getCompilationUnit(); - LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.OVERRIDE_DEFAULT_METHOD, image); - ImportRewrite importRewrite= proposal.createImportRewrite(astRoot); - ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(astRoot, typeNode.getStartPosition(), importRewrite); - CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(cu); + @Override + protected ICommandAccess cuCorrectionProposalToT(CUCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); + switch (uid) { + case ADD_PERMITTED_TYPE, ADD_SEALED_SUPERTYPE -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); + } + } try { - MethodDeclaration stub= StubUtility2Core.createImplementationStub(cu, rewrite, importRewrite, importRewriteContext, methodToOverride, typeBinding, settings, - typeBinding.isInterface(), new NodeFinder(astRoot, typeNode.getStartPosition(), 0).getCoveringNode()); - BodyDeclarationRewrite.create(rewrite, typeNode).insert(stub, null); - - proposal.setEndPosition(rewrite.track(stub)); + return new CUCorrectionProposal(core, image); } catch (CoreException e) { - JavaPlugin.log(e); + return null; } - - proposals.add(proposal); } - public static void addServiceProviderProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode node= problem.getCoveredNode(context.getASTRoot()); - if (!(node instanceof Name) || !(node.getParent() instanceof ProvidesDirective)) { - return; - } - Name name= (Name) node; - ProvidesDirective prov= (ProvidesDirective) name.getParent(); - ITypeBinding targetBinding= name.resolveTypeBinding(); - ITypeBinding serviceBinding= prov.getName().resolveTypeBinding(); - if (targetBinding != null && serviceBinding != null) { - ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); - - IJavaProject proj= context.getCompilationUnit().getJavaProject(); - IType type= proj.findType(serviceBinding.getQualifiedName()); - Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); - proposals.add(new NewProviderMethodDeclaration( - Messages.format(CorrectionMessages.LocalCorrectionsSubProcessor_add_provider_method_description, type.getElementName()), - targetCU, context.getASTRoot(), targetBinding, - IProposalRelevance.CREATE_METHOD, image, type)); + @Override + protected ICommandAccess newVariableCorrectionProposalToT(NewVariableCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); + switch (uid) { + case CREATE_PARAMETER -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); + } } + return new NewVariableCorrectionProposal(core, image); } - public static void addServiceProviderConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { - ASTNode node= problem.getCoveredNode(context.getASTRoot()); - if (!(node instanceof Name) && !(node.getParent() instanceof ProvidesDirective)) { - return; - } - - Name name= (Name) node; - ITypeBinding targetBinding= name.resolveTypeBinding(); - - if (targetBinding != null && - !targetBinding.isInterface() - && !Modifier.isAbstract(targetBinding.getModifiers())) { - ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(context.getCompilationUnit(), context.getASTRoot(), targetBinding); - IJavaProject proj= targetCU.getJavaProject(); - - // Get the AST Root (CompilationUnit) for target class - ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); - parser.setKind(ASTParser.K_COMPILATION_UNIT); - parser.setSource(targetCU); - parser.setProject(proj); - parser.setUnitName(targetCU.getPath().toString()); - parser.setResolveBindings(true); - ASTNode targetRoot= parser.createAST(null); - - if (!(targetRoot instanceof CompilationUnit)) { - return; - } - - IType targetType= proj.findType(targetBinding.getQualifiedName()); - - // Locate the no-arg constructor binding for the type - List result= Arrays.asList(targetBinding.getDeclaredMethods()).stream() - .filter(m -> m.isConstructor() && m.getParameterTypes().length == 0) - .collect(Collectors.toList()); - // no-arg constructor exists, need to change visibility - if (!result.isEmpty()) { - IMethodBinding targetMethodBinding= result.get(0); - IMethod targetMethod= null; - for (IMethod m : targetType.getMethods()) { - if (m.isConstructor() && m.getParameters().length == 0) { - targetMethod= m; - break; - } - } + @Override + protected ICommandAccess missingAnnotationAttributesProposalToT(MissingAnnotationAttributesProposalCore core, int uid) { + return new MissingAnnotationAttributesProposal(core); + } - String label= CorrectionMessages.LocalCorrectionsSubProcessor_changeconstructor_public_description; - int include= Modifier.PUBLIC; - int exclude= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC; - // Locate the constructor declaration node in the target AST Node - MethodDeclaration targetMethodDecl= ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod, (CompilationUnit) targetRoot); - proposals.add(new ModifierChangeCorrectionProposal(label, targetCU, targetMethodBinding, targetMethodDecl.getName(), - include, exclude, IProposalRelevance.CHANGE_VISIBILITY_TO_NON_PRIVATE, - JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE))); - } else { - // no-arg constructor does not exist, need to create it - String[] args= new String[] { ASTResolving - .getMethodSignature(ASTResolving.getTypeSignature(targetBinding), new ITypeBinding[0], false) }; - String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconstructor_description, args); - Image image= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE); - proposals.add(new NewMethodCorrectionProposal(label, targetCU, targetRoot, new ArrayList<>(), targetBinding, IProposalRelevance.CREATE_CONSTRUCTOR, image)); + @Override + protected ICommandAccess newMethodCorrectionProposalToT(NewMethodCorrectionProposalCore core, int uid) { + Image image= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE); + switch (uid) { + case CREATE_CONSTRUCTOR -> { + image= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE); } } + return new NewMethodCorrectionProposal(core, image); } - private LocalCorrectionsSubProcessor() { - } + @Override + protected ICommandAccess modifierChangeCorrectionProposalToT(ModifierChangeCorrectionProposalCore core, int uid) { + Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + switch (uid) { + case CHANGE_MODIFIER -> { + image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); + } + } + return new ModifierChangeCorrectionProposal(core, image); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java index 0fe8ea159c7..2bfa16111d0 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2019 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -869,21 +869,14 @@ public static void addOverridingDeprecatedMethodProposal(IInvocationContext cont if (!(selectedNode instanceof MethodDeclaration)) { return; } - boolean is50OrHigher= JavaModelUtil.is50OrHigher(cu.getJavaProject()); MethodDeclaration methodDecl= (MethodDeclaration) selectedNode; AST ast= methodDecl.getAST(); ASTRewrite rewrite= ASTRewrite.create(ast); - if (is50OrHigher) { - Annotation annot= ast.newMarkerAnnotation(); - annot.setTypeName(ast.newName("Deprecated")); //$NON-NLS-1$ - rewrite.getListRewrite(methodDecl, methodDecl.getModifiersProperty()).insertFirst(annot, null); - } + Annotation annot= ast.newMarkerAnnotation(); + annot.setTypeName(ast.newName("Deprecated")); //$NON-NLS-1$ + rewrite.getListRewrite(methodDecl, methodDecl.getModifiersProperty()).insertFirst(annot, null); Javadoc javadoc= methodDecl.getJavadoc(); - if (javadoc != null || !is50OrHigher) { - if (!is50OrHigher) { - javadoc= ast.newJavadoc(); - rewrite.set(methodDecl, MethodDeclaration.JAVADOC_PROPERTY, javadoc, null); - } + if (javadoc != null) { TagElement newTag= ast.newTagElement(); newTag.setTagName(TagElement.TAG_DEPRECATED); JavadocTagsSubProcessor.insertTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), newTag, null); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java index a23107d35aa..7ffc571bcf7 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistProcessor.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2024 IBM Corporation and others. + * Copyright (c) 2000, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -1584,9 +1584,6 @@ private static boolean getPickoutTypeFromMulticatchProposals(IInvocationContext } private static boolean getConvertToMultiCatchProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) { - if (!JavaModelUtil.is1d7OrHigher(context.getCompilationUnit().getJavaProject())) - return false; - CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(covering, ASTNode.CATCH_CLAUSE); if (catchClause == null) { return false; @@ -1673,9 +1670,6 @@ private static boolean getConvertToMultiCatchProposals(IInvocationContext contex } private static boolean getUnrollMultiCatchProposals(IInvocationContext context, ASTNode covering, Collection resultingCollections) { - if (!JavaModelUtil.is1d7OrHigher(context.getCompilationUnit().getJavaProject())) - return false; - CatchClause catchClause= (CatchClause) ASTResolving.findAncestor(covering, ASTNode.CATCH_CLAUSE); if (catchClause == null) { return false; @@ -1858,28 +1852,6 @@ private static boolean containsQuickFixableRenameLocal(IProblemLocation[] locati return false; } - public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) { - if (statement.getNodeType() == ASTNode.BLOCK) { - Block block= (Block) statement; - List innerStatements= block.statements(); - int nStatements= innerStatements.size(); - if (nStatements == 1) { - return rewrite.createCopyTarget(innerStatements.get(0)); - } else if (nStatements > 1) { - if (toControlStatementBody) { - return rewrite.createCopyTarget(block); - } - ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY); - ASTNode first= innerStatements.get(0); - ASTNode last= innerStatements.get(nStatements - 1); - return listRewrite.createCopyTarget(first, last); - } - return null; - } else { - return rewrite.createCopyTarget(statement); - } - } - private static boolean getUnWrapProposals(IInvocationContext context, ASTNode node, Collection resultingCollections) { ASTNode outer= node; @@ -1975,7 +1947,7 @@ private static boolean getUnWrapProposals(IInvocationContext context, ASTNode no return false; } ASTRewrite rewrite= ASTRewrite.create(outer.getAST()); - ASTNode inner= getCopyOfInner(rewrite, body, ASTNodes.isControlStatementBody(outer.getLocationInParent())); + ASTNode inner= QuickAssistProcessorUtil.getCopyOfInner(rewrite, body, ASTNodes.isControlStatementBody(outer.getLocationInParent())); if (inner == null) { return false; } @@ -3121,9 +3093,7 @@ public static boolean getGenerateForLoopProposals(IInvocationContext context, AS return false; } - if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) { - resultingCollections.add(new GenerateForLoopAssistProposal(cu, expressionStatement, GenerateForLoopAssistProposal.GENERATE_FOREACH)); - } + resultingCollections.add(new GenerateForLoopAssistProposal(cu, expressionStatement, GenerateForLoopAssistProposal.GENERATE_FOREACH)); return true; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java index 5b49bdb5bc9..b67a80b5141 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickFixProcessor.java @@ -49,7 +49,6 @@ import org.eclipse.jdt.internal.corext.fix.IProposableFix; import org.eclipse.jdt.internal.corext.fix.InlineMethodFixCore; import org.eclipse.jdt.internal.corext.fix.NullAnnotationsRewriteOperations.ChangeKind; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; @@ -828,9 +827,11 @@ private void process(IInvocationContext context, IProblemLocation problem, Colle case IProblem.SwitchExpressionsYieldMissingEnumConstantCase: LocalCorrectionsSubProcessor.getMissingEnumConstantCaseProposals(context, problem, proposals); break; - case IProblem.MissingDefaultCase: - case IProblem.SwitchExpressionsYieldMissingDefaultCase: case IProblem.EnhancedSwitchMissingDefault: + case IProblem.SwitchExpressionsYieldMissingDefaultCase: + LocalCorrectionsSubProcessor.addPermittedTypesProposal(context, problem, proposals); + //$FALL-THROUGH$ + case IProblem.MissingDefaultCase: LocalCorrectionsSubProcessor.addMissingDefaultCaseProposal(context, problem, proposals); break; case IProblem.IllegalTotalPatternWithDefault: @@ -978,9 +979,7 @@ private void process(IInvocationContext context, IProblemLocation problem, Colle break; default: } - if (JavaModelUtil.is50OrHigher(context.getCompilationUnit().getJavaProject())) { - SuppressWarningsSubProcessor.addSuppressWarningsProposals(context, problem, proposals); - } + SuppressWarningsSubProcessor.addSuppressWarningsProposals(context, problem, proposals); ConfigureProblemSeveritySubProcessor.addConfigureProblemSeverityProposal(context, problem, proposals); } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java index c7ed9a2a190..c9d86b45b85 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java @@ -255,7 +255,7 @@ public ChangeToRequiredCompilerCompliance(String name, IJavaProject project, boo private boolean isRequiredOrGreaterVMInstall(IVMInstall install) { if (install instanceof IVMInstall2) { - String compliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, JavaCore.VERSION_1_3); + String compliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) install, JavaCore.VERSION_1_8); return !JavaModelUtil.isVersionLessThan(compliance, fRequiredVersion); } return false; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java index c9167bbfd42..62a772bf79c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ConstructorFromSuperclassProposal.java @@ -39,6 +39,10 @@ public ConstructorFromSuperclassProposal(ICompilationUnit cu, TypeDeclaration ty super("", cu, null, relevance, getProposalImage(), new ConstructorFromSuperclassProposalCore(cu, typeNode, superConstructor, relevance)); //$NON-NLS-1$ } + public ConstructorFromSuperclassProposal(ConstructorFromSuperclassProposalCore core) { + super("", core.getCompilationUnit(), null, core.getRelevance(), getProposalImage(), core); //$NON-NLS-1$ + } + @Override public String getName() { return ((ConstructorFromSuperclassProposalCore) getDelegate()).getName(); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateNewObjectProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateNewObjectProposal.java index df46f23ad92..1830cf3bdd3 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateNewObjectProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateNewObjectProposal.java @@ -47,6 +47,10 @@ public CreateNewObjectProposal(ICompilationUnit cu, VariableDeclarationFragment super("", cu, null, relevance, null, new CreateNewObjectProposalCore(cu, variableDeclarationFragment, variableBinding, relevance)); //$NON-NLS-1$ } + public CreateNewObjectProposal(CreateNewObjectProposalCore core) { + super("", core.getCompilationUnit(), null, core.getRelevance(), null, core); //$NON-NLS-1$ + } + @Override public Image getImage() { return JavaPlugin.getImageDescriptorRegistry().get( diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateObjectReferenceProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateObjectReferenceProposal.java index 43fd359f67d..81cb03d914f 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateObjectReferenceProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateObjectReferenceProposal.java @@ -38,6 +38,10 @@ public CreateObjectReferenceProposal(ICompilationUnit cu, ASTNode selectedNode, super("", cu, null, relevance, null, new CreateObjectReferenceProposalCore(cu, selectedNode, typeNode, relevance)); //$NON-NLS-1$ } + public CreateObjectReferenceProposal(CreateObjectReferenceProposalCore core) { + super("", core.getCompilationUnit(), null, core.getRelevance(), null, core); //$NON-NLS-1$ + } + @Override public Image getImage() { return JavaPlugin.getImageDescriptorRegistry().get( diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateVariableReferenceProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateVariableReferenceProposal.java index 5a341afafc2..05c176b0a52 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateVariableReferenceProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/CreateVariableReferenceProposal.java @@ -38,6 +38,10 @@ public CreateVariableReferenceProposal(ICompilationUnit cu, VariableDeclarationF super("", cu, null, relevance, null, new CreateVariableReferenceProposalCore(cu, selectedNode, typeNode, relevance)); //$NON-NLS-1$ } + public CreateVariableReferenceProposal(CreateVariableReferenceProposalCore core) { + super("", core.getCompilationUnit(), null, core.getRelevance(), null, core); //$NON-NLS-1$ + } + @Override public Image getImage() { return JavaPlugin.getImageDescriptorRegistry().get( diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/FixCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/FixCorrectionProposal.java index 51a614034b3..b5256dd5251 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/FixCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/FixCorrectionProposal.java @@ -79,6 +79,11 @@ public FixCorrectionProposal(IProposableFix fix, ICleanUp cleanUp, int relevance this.fCleanUp= cleanUp; } + public FixCorrectionProposal(FixCorrectionProposalCore core, Image image) { + super(core, image); + this.fCleanUp= core.getCleanUp(); + } + public void resolve(MultiFixTarget[] targets, final IProgressMonitor monitor) throws CoreException { if (targets.length == 0) return; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingAnnotationAttributesProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingAnnotationAttributesProposal.java index b611069ff21..e9f8b280385 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingAnnotationAttributesProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/MissingAnnotationAttributesProposal.java @@ -25,4 +25,9 @@ public MissingAnnotationAttributesProposal(ICompilationUnit cu, Annotation annot super(CorrectionMessages.MissingAnnotationAttributesProposal_add_missing_attributes_label, cu, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE), new MissingAnnotationAttributesProposalCore(cu, annotation, relevance)); } + + public MissingAnnotationAttributesProposal(MissingAnnotationAttributesProposalCore core) { + super(CorrectionMessages.MissingAnnotationAttributesProposal_add_missing_attributes_label, core.getCompilationUnit(), null, core.getRelevance(), + JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE), core); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java index fb375a905a2..eb2bad6c69d 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ModifierChangeCorrectionProposal.java @@ -25,4 +25,8 @@ public class ModifierChangeCorrectionProposal extends LinkedCorrectionProposal { public ModifierChangeCorrectionProposal(String label, ICompilationUnit targetCU, IBinding binding, ASTNode node, int includedModifiers, int excludedModifiers, int relevance, Image image) { super(label, targetCU, null, relevance, image, new ModifierChangeCorrectionProposalCore(label, targetCU, binding, node, includedModifiers, excludedModifiers, relevance)); } + + public ModifierChangeCorrectionProposal(ModifierChangeCorrectionProposalCore core, Image image) { + super(core.getName(), core.getCompilationUnit(), null, core.getRelevance(), image, core); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java index dc85c2d9432..5ac002f7957 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/NewDefiningMethodProposal.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -32,7 +32,6 @@ import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Annotation; @@ -52,7 +51,6 @@ import org.eclipse.jdt.internal.core.manipulation.dom.ASTResolving; import org.eclipse.jdt.internal.corext.dom.ASTNodes; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; @@ -86,10 +84,6 @@ private void addOverrideAnnotation(IDocument document) throws CoreException { MethodDeclaration oldMethodDeclaration= (MethodDeclaration) ASTNodes.findDeclaration(fMethod, getInvocationNode()); CompilationUnit findParentCompilationUnit= ASTResolving.findParentCompilationUnit(oldMethodDeclaration); IJavaProject javaProject= findParentCompilationUnit.getJavaElement().getJavaProject(); - String version= javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true); - if (JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_5)) { - return; - } IType type= javaProject.findType(fMethod.getDeclaringClass().getQualifiedName()); ICompilationUnit compilationUnit= type.getCompilationUnit(); ImportRewrite importRewrite= CodeStyleConfiguration.createImportRewrite(compilationUnit, true); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/RefactoringCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/RefactoringCorrectionProposal.java index 9a9af31d39c..4b48b5d4e9c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/RefactoringCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/RefactoringCorrectionProposal.java @@ -30,4 +30,7 @@ public RefactoringCorrectionProposal(String name, ICompilationUnit cu, int relev super(name, cu, null, relevance, image, delegate); } + public RefactoringCorrectionProposal(RefactoringCorrectionProposalCore core, Image image) { + super(core, image); + } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ReplaceCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ReplaceCorrectionProposal.java index 8b436f28133..f11779316dd 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ReplaceCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/proposals/ReplaceCorrectionProposal.java @@ -28,4 +28,5 @@ public ReplaceCorrectionProposal(ReplaceCorrectionProposalCore core) { public ReplaceCorrectionProposal(String name, ICompilationUnit cu, int offset, int length, String replacementString, int relevance) { super(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE), new ReplaceCorrectionProposalCore(name, cu, offset, length, replacementString, relevance)); } + } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/FillArgumentNamesCompletionProposalCollector.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/FillArgumentNamesCompletionProposalCollector.java index e74c36d941a..9e4e7550fff 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/FillArgumentNamesCompletionProposalCollector.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/FillArgumentNamesCompletionProposalCollector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2020 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -18,12 +18,8 @@ import org.eclipse.jdt.core.CompletionContext; import org.eclipse.jdt.core.CompletionProposal; import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.Signature; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; - import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.java.CompletionProposalCollector; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; @@ -91,10 +87,6 @@ IJavaCompletionProposal createTypeProposal(CompletionProposal typeProposal) { if (cu == null || getContext() != null && getContext().isInJavadoc()) return super.createJavaCompletionProposal(typeProposal); - IJavaProject project= cu.getJavaProject(); - if (!shouldProposeGenerics(project)) - return super.createJavaCompletionProposal(typeProposal); - char[] completion= typeProposal.getCompletion(); // don't add parameters for import-completions nor for proposals with an empty completion (e.g. inside the type argument list) if (completion.length > 0 && completion[completion.length - 1] == '.') @@ -106,23 +98,4 @@ IJavaCompletionProposal createTypeProposal(CompletionProposal typeProposal) { return newProposal; } - /** - * Returns true if generic proposals should be allowed, - * false if not. Note that even though code (in a library) - * may be referenced that uses generics, it is still possible that the - * current source does not allow generics. - * - * @param project the Java project - * @return true if the generic proposals should be allowed, - * false if not - */ - private boolean shouldProposeGenerics(IJavaProject project) { - String sourceVersion; - if (project != null) - sourceVersion= project.getOption(JavaCore.COMPILER_SOURCE, true); - else - sourceVersion= JavaCore.getOption(JavaCore.COMPILER_SOURCE); - - return JavaModelUtil.is50OrHigher(sourceVersion); - } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java index 8b4408a8ad5..44fb95899df 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCodeScanner.java @@ -348,11 +348,11 @@ public void setSourceVersion(String version) { private static final String SOURCE_VERSION= JavaCore.COMPILER_SOURCE; static String[] fgKeywords= { - "abstract", //$NON-NLS-1$ + "abstract", "assert", //$NON-NLS-1$ //$NON-NLS-2$ "break", //$NON-NLS-1$ "case", "catch", "class", "const", "continue", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "default", "do", //$NON-NLS-2$ //$NON-NLS-1$ - "else", "extends", //$NON-NLS-2$ //$NON-NLS-1$ + "else", "enum", "extends", //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-1$ "final", "finally", "for", //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ "goto", //$NON-NLS-1$ "if", "implements", "import", "instanceof", "interface", //$NON-NLS-5$ //$NON-NLS-4$ //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-1$ @@ -366,8 +366,6 @@ public void setSourceVersion(String version) { private static final String INTERFACE= "interface"; //$NON-NLS-1$ private static final String RETURN= "return"; //$NON-NLS-1$ - private static String[] fgJava1d4Keywords= { "assert" }; //$NON-NLS-1$ - private static String[] fgJava1d5Keywords= { "enum" }; //$NON-NLS-1$ private static String[] fgJava14Keywords= { "record" }; //$NON-NLS-1$ private static String[] fgJava16Keywords= { "sealed", "permits" }; //$NON-NLS-1$ //$NON-NLS-2$ private static String[] fgJava9ModuleInfoKeywords= { "module", "requires", "exports", "to", "provides", "with", "uses", "open", "opens", "transitive", "import", "static" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ //$NON-NLS-9$ //$NON-NLS-10$ //$NON-NLS-11$ //$NON-NLS-12$ @@ -452,26 +450,6 @@ protected List createRules() { JavaWordDetector wordDetector= new JavaWordDetector(); CombinedWordRule combinedWordRule= new CombinedWordRule(wordDetector, defaultToken); - VersionedWordMatcher j1d4Matcher= new VersionedWordMatcher(defaultToken, JavaCore.VERSION_1_4, version); - - token= getToken(IJavaColorConstants.JAVA_KEYWORD); - for (String fgJava1d4Keyword : fgJava1d4Keywords) { - j1d4Matcher.addWord(fgJava1d4Keyword, token); - } - - combinedWordRule.addWordMatcher(j1d4Matcher); - fVersionDependentRules.add(j1d4Matcher); - - VersionedWordMatcher j1d5Matcher= new VersionedWordMatcher(defaultToken, JavaCore.VERSION_1_5, version); - - token= getToken(IJavaColorConstants.JAVA_KEYWORD); - for (String fgJava1d5Keyword : fgJava1d5Keywords) { - j1d5Matcher.addWord(fgJava1d5Keyword, token); - } - - combinedWordRule.addWordMatcher(j1d5Matcher); - fVersionDependentRules.add(j1d5Matcher); - VersionedWordMatcher j14Matcher= new VersionedWordMatcher(defaultToken, JavaCore.VERSION_14, version); token= getToken(IJavaColorConstants.JAVA_KEYWORD); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaDoubleClickSelector.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaDoubleClickSelector.java index 084e5c6bb53..5007067a2aa 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaDoubleClickSelector.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaDoubleClickSelector.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2018 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,27 +13,26 @@ *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; +import static java.lang.Character.isJavaIdentifierPart; +import static java.lang.Character.isJavaIdentifierStart; +import static java.lang.Character.isWhitespace; + import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultTextDoubleClickStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; -import org.eclipse.jdt.core.JavaCore; - -import org.eclipse.jdt.internal.ui.text.ISourceVersionDependent; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; - - /** * Double click strategy aware of Java identifier syntax rules. */ -public class JavaDoubleClickSelector extends DefaultTextDoubleClickStrategy implements ISourceVersionDependent { +public class JavaDoubleClickSelector extends DefaultTextDoubleClickStrategy { /** * Detects java words depending on the source level. In 1.4 mode, detects - * [[:ID:]]*. In 1.5 mode, it also detects + * [[:ID:]]* and * @\s*[[:IDS:]][[:ID:]]*. * * Character class definitions: @@ -46,9 +45,7 @@ public class JavaDoubleClickSelector extends DefaultTextDoubleClickStrategy impl * * @since 3.1 */ - private static final class AtJavaIdentifierDetector implements ISourceVersionDependent { - - private boolean fSelectAnnotations; + private static final class AtJavaIdentifierDetector { private static final int UNKNOWN= -1; @@ -91,30 +88,7 @@ private void setAnchor(int anchor) { } private boolean isAt(char c) { - return fSelectAnnotations && c == '@'; - } - - private boolean isIdentifierStart(char c) { - return Character.isJavaIdentifierStart(c); - } - - private boolean isIdentifierPart(char c) { - return Character.isJavaIdentifierPart(c); - } - - private boolean isWhitespace(char c) { - return fSelectAnnotations && Character.isWhitespace(c); - } - - /* - * @see org.eclipse.jdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String) - */ - @Override - public void setSourceVersion(String version) { - if (JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, version) <= 0) - fSelectAnnotations= true; - else - fSelectAnnotations= false; + return c == '@'; } /** @@ -139,24 +113,24 @@ private boolean backward(char c, int offset) { fState= WS; return true; } - if (isIdentifierStart(c)) { + if (isJavaIdentifierStart(c)) { fStart= offset; fState= IDS; return true; } - if (isIdentifierPart(c)) { + if (isJavaIdentifierPart(c)) { fStart= offset; fState= ID; return true; } return false; case ID: - if (isIdentifierStart(c)) { + if (isJavaIdentifierStart(c)) { fStart= offset; fState= IDS; return true; } - if (isIdentifierPart(c)) { + if (isJavaIdentifierPart(c)) { fStart= offset; fState= ID; return true; @@ -203,7 +177,7 @@ private boolean forward(char c, int offset) { fState= WS; return true; } - if (isIdentifierStart(c)) { + if (isJavaIdentifierStart(c)) { fEnd= offset; fState= IDS; return true; @@ -211,25 +185,25 @@ private boolean forward(char c, int offset) { return false; case IDS: case ID: - if (isIdentifierStart(c)) { + if (isJavaIdentifierStart(c)) { fEnd= offset; fState= IDS; return true; } - if (isIdentifierPart(c)) { + if (isJavaIdentifierPart(c)) { fEnd= offset; fState= ID; return true; } return false; case UNKNOWN: - if (isIdentifierStart(c)) { + if (isJavaIdentifierStart(c)) { fEnd= offset; fState= IDS; fAnchorState= fState; return true; } - if (isIdentifierPart(c)) { + if (isJavaIdentifierPart(c)) { fEnd= offset; fState= ID; fAnchorState= fState; @@ -326,15 +300,6 @@ protected IRegion findWord(IDocument document, int anchor) { return fWordDetector.getWordSelection(document, anchor); } - /* - * @see org.eclipse.jdt.internal.ui.text.ISourceVersionDependent#setSourceVersion(java.lang.String) - */ - @Override - public void setSourceVersion(String version) { - fPairMatcher.setSourceVersion(version); - fWordDetector.setSourceVersion(version); - } - @Override protected IRegion findExtendedDoubleClickSelection(IDocument document, int offset) { IRegion match= fPairMatcher.match(document, offset); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java index c00f9bbff3d..1dd0fa56f59 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposalComputer.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2005, 2022 IBM Corporation and others. + * Copyright (c) 2005, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -26,9 +26,7 @@ import org.eclipse.jdt.core.CompletionContext; import org.eclipse.jdt.core.CompletionProposal; import org.eclipse.jdt.core.IJavaElement; -import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; @@ -124,35 +122,9 @@ private IJavaCompletionProposal createTypeProposal(int relevance, String fullyQu proposal.setReplaceRange(context.getInvocationOffset(), context.getInvocationOffset()); proposal.setSignature(Signature.createTypeSignature(fullyQualifiedType, true).toCharArray()); - if (shouldProposeGenerics(context.getProject())) { - LazyGenericTypeProposal p= new LazyGenericTypeProposal(proposal, context); - p.setRelevance(relevance); - return p; - } else { - LazyJavaTypeCompletionProposal p= new LazyJavaTypeCompletionProposal(proposal, context); - p.setRelevance(relevance); - return p; - } - } - - /** - * Returns true if generic proposals should be allowed, - * false if not. Note that even though code (in a library) - * may be referenced that uses generics, it is still possible that the - * current source does not allow generics. - * - * @param project the Java project - * @return true if the generic proposals should be allowed, - * false if not - */ - protected final boolean shouldProposeGenerics(IJavaProject project) { - String sourceVersion; - if (project != null) - sourceVersion= project.getOption(JavaCore.COMPILER_SOURCE, true); - else - sourceVersion= JavaCore.getOption(JavaCore.COMPILER_SOURCE); - - return sourceVersion != null && JavaCore.compareJavaVersions(JavaCore.VERSION_1_5, sourceVersion) <= 0; + LazyGenericTypeProposal p= new LazyGenericTypeProposal(proposal, context); + p.setRelevance(relevance); + return p; } @Override diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuesser.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuesser.java index 94d9e420722..490a6461b5c 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuesser.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuesser.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2011 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -39,8 +39,6 @@ import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.PrimitiveType.Code; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; - import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.internal.ui.JavaPlugin; @@ -240,7 +238,7 @@ private PrimitiveType.Code getPrimitiveTypeCode(String type) { if (code != null) { return code; } - if (fEnclosingElement != null && JavaModelUtil.is50OrHigher(fEnclosingElement.getJavaProject())) { + if (fEnclosingElement != null) { if (code == PrimitiveType.SHORT) { if ("java.lang.Short".equals(type)) { //$NON-NLS-1$ return code; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.java index d31910161b4..04528701c68 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.java @@ -613,7 +613,11 @@ private String getBracketHoverInfo(final ITextViewer textViewer, IRegion region) } return source; } catch (BadLocationException e) { - JavaPlugin.log(e); + /* + * This code runs in a separate thread which can + * lead to text offsets being out of bounds when + * computing the hover info (see bug 32848). + */ return null; } } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java index 734f7aa1618..285e509ea7a 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java @@ -101,6 +101,7 @@ import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; +import org.eclipse.ui.views.WorkbenchViewerSetup; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; @@ -757,6 +758,7 @@ private Control createTypeViewerControl(Composite parent) { fEmptyTypesViewer= new Label(fViewerbook, SWT.TOP | SWT.LEFT | SWT.WRAP); for (TypeHierarchyViewer viewer : fAllViewers) { + WorkbenchViewerSetup.setupViewer(viewer); viewer.setInput(viewer); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/ClasspathVMUtil.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/ClasspathVMUtil.java index 83b1af5a13b..a15b6358d16 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/ClasspathVMUtil.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/ClasspathVMUtil.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2018 IBM Corporation and others. + * Copyright (c) 2018, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -74,8 +74,8 @@ public static IVMInstall findRequiredOrGreaterVMInstall(String requiredVersion, } public static String getVMInstallCompliance(IVMInstall install, boolean allowNullCompliance) { - String defCompliance1= JavaCore.VERSION_1_1; - String defCompliance2= JavaCore.VERSION_1_3; + String defCompliance1= JavaCore.VERSION_1_8; + String defCompliance2= JavaCore.VERSION_1_8; if (allowNullCompliance) { defCompliance1= null; defCompliance2= null; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SelectionUtil.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SelectionUtil.java index 0c82d9ed6a9..25dacce322e 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SelectionUtil.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SelectionUtil.java @@ -20,6 +20,7 @@ import java.util.Objects; import org.eclipse.core.runtime.ILog; +import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.resources.IResource; @@ -130,6 +131,12 @@ private SelectionUtil() { private static String lastErrorMsg; public static void logException(String action, RuntimeException e, String title, IDocument document, int offset) { + if (e instanceof OperationCanceledException ) { + // Be silent if operation is canceled see + // https://github.com/eclipse-jdt/eclipse.jdt.ui/issues/1827 + return; + } + // log error and keep going String errorMsg= e.getClass().getSimpleName() + " " + action; //$NON-NLS-1$ if (title != null) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.java index bf72550352e..b0f3bd4fd60 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.java @@ -115,7 +115,6 @@ private NewWizardMessages() { public static String NewTypeWizardPage_error_PackageNameEmptyForModule; public static String NewTypeWizardPage_warning_DiscouragedPackageName; public static String NewTypeWizardPage_warning_DefaultPackageDiscouraged; - public static String NewTypeWizardPage_warning_NotJDKCompliant; public static String NewTypeWizardPage_warning_NotJDKCompliant2; public static String NewTypeWizardPage_warning_EnumClassNotFound; public static String NewTypeWizardPage_warning_RecordClassNotFound; @@ -158,13 +157,10 @@ private NewWizardMessages() { public static String NewTypeWizardPage_error_QualifiedName; public static String NewTypeWizardPage_info_FileExtensionNotRequired; public static String NewTypeWizardPage_warning_TypeNameDiscouraged; - public static String NewTypeWizardPage_error_TypeParameters; public static String NewTypeWizardPage_error_InvalidSuperClassName; public static String NewTypeWizardPage_error_InvalidSuperClassRecord; public static String NewTypeWizardPage_error_InvalidFinalSuperClass; - public static String NewTypeWizardPage_error_SuperClassNotParameterized; public static String NewTypeWizardPage_error_InvalidSuperInterfaceName; - public static String NewTypeWizardPage_error_SuperInterfaceNotParameterized; public static String NewTypeWizardPage_error_ModifiersFinalAndAbstract; public static String NewTypeWizardPage_error_TypeNameFiltered; public static String NewTypeWizardPage_error_PackageNameFiltered; diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties index 0e6ca4c8dba..4eef8f9e6a8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewWizardMessages.properties @@ -90,7 +90,6 @@ NewTypeWizardPage_error_PackageNameEmptyForModule=A package name must be specifi NewTypeWizardPage_error_uri_location_unkown=Cannot locate resource {0} NewTypeWizardPage_warning_DiscouragedPackageName=This package name is discouraged. {0} NewTypeWizardPage_warning_DefaultPackageDiscouraged=The use of the default package is discouraged. -NewTypeWizardPage_warning_NotJDKCompliant=Project ''{0}'' is not a J2SE 5.0 compliant project. NewTypeWizardPage_warning_NotJDKCompliant2=Project ''{0}'' is not a Java {1} compliant project. NewTypeWizardPage_warning_EnumClassNotFound=Type 'java.lang.Enum' is not on the project's build path. Make sure you use a 1.5 JDK. NewTypeWizardPage_warning_RecordClassNotFound=Type 'java.lang.Record' is not on the project's build path. Make sure you use a 14 JDK. @@ -140,12 +139,9 @@ NewTypeWizardPage_error_InvalidTypeName=Type name is not valid. {0} NewTypeWizardPage_error_QualifiedName=Type name must not be qualified. NewTypeWizardPage_info_FileExtensionNotRequired=The file extension '.java' will not be part of the type name. NewTypeWizardPage_warning_TypeNameDiscouraged=Type name is discouraged. {0} -NewTypeWizardPage_error_TypeParameters=Type name is not valid. Type parameters are only available if source level is 1.5. NewTypeWizardPage_error_InvalidSuperClassName=Superclass type is not valid. -NewTypeWizardPage_error_SuperClassNotParameterized=Superclass cannot be parameterized unless source level is 1.5. NewTypeWizardPage_error_InvalidSuperInterfaceName=Extended interface ''{0}'' is not valid. -NewTypeWizardPage_error_SuperInterfaceNotParameterized=Extended interface ''{0}'' cannot be parameterized unless source level is 1.5. NewTypeWizardPage_error_InvalidSuperClassRecord=Record ''{0}'' cannot be superclass. A record is final. NewTypeWizardPage_error_InvalidFinalSuperClass=Class ''{0}'' cannot be superclass as it is final. diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.java index 5595e7acb8f..1f36bff72ff 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2016 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -39,7 +39,6 @@ import org.eclipse.jdt.core.search.TypeNameMatch; import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.wizards.NewTypeWizardPage; @@ -195,9 +194,6 @@ protected void configureShell(Shell newShell) { public static String getNameWithTypeParameters(IType type) { String superName= type.getFullyQualifiedName('.'); - if (!JavaModelUtil.is50OrHigher(type.getJavaProject())) { - return superName; - } try { ITypeParameter[] typeParameters= type.getTypeParameters(); if (typeParameters.length > 0) { diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetModel.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetModel.java index 8069586d084..2737bcc1965 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetModel.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetModel.java @@ -425,8 +425,14 @@ private void addNewlyCreatedWorkingSets(List result) { * @since 3.7 */ public void setWorkingSets(IWorkingSet[] allWorkingSets, boolean isSortingEnabled, IWorkingSet[] activeWorkingSets) { - Assert.isLegal(Arrays.asList(allWorkingSets).containsAll(Arrays.asList(activeWorkingSets))); - Assert.isLegal(!isOrderDifferentInWorkingSetLists(Arrays.asList(allWorkingSets), Arrays.asList(activeWorkingSets))); + if (!Arrays.asList(allWorkingSets).containsAll(Arrays.asList(activeWorkingSets))) { + throw new IllegalArgumentException( + Arrays.stream(allWorkingSets).map(IWorkingSet::getName).sorted().toList() + " does not contain all " + Arrays.stream(activeWorkingSets).map(IWorkingSet::getName).sorted().toList()); //$NON-NLS-1$ + } + if (isOrderDifferentInWorkingSetLists(Arrays.asList(allWorkingSets), Arrays.asList(activeWorkingSets))) { + throw new IllegalArgumentException( + Arrays.stream(allWorkingSets).map(IWorkingSet::getName).toList() + " has different order then " + Arrays.stream(activeWorkingSets).map(IWorkingSet::getName).toList()); //$NON-NLS-1$ + } if (isSortingEnabled) Arrays.sort(allWorkingSets, new WorkingSetComparator(true)); fAllWorkingSets= new ArrayList<>(Arrays.asList(allWorkingSets)); @@ -443,7 +449,9 @@ public void setWorkingSets(IWorkingSet[] allWorkingSets, boolean isSortingEnable * @param workingSets the active working sets to be set */ public void setActiveWorkingSets(IWorkingSet[] workingSets) { + List backup= fAllWorkingSets; // modified by getAllWorkingSets, see gh#1863: Assert.isLegal(Arrays.asList(getAllWorkingSets()).containsAll(Arrays.asList(workingSets))); + fAllWorkingSets= backup; if (fIsSortingEnabled) { Arrays.sort(workingSets, new WorkingSetComparator(true)); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java index 5b2fd619e15..8c32e3d7bf7 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java @@ -3939,6 +3939,17 @@ private PreferenceConstants() { */ public static final String EDITOR_JAVA_CODEMINING_DEFAULT_FILTER_FOR_PARAMETER_NAMES = "java.codemining.defalt.filter.for.parameterNames"; //$NON-NLS-1$ + /** + * A named preference that stores the value if a method with one parameter should be shown with code minings or if the code minings are + * only shown for 2+ parameters + *

+ * Value is of type Boolean. + *

+ * + * @since 3.34 + */ + public static final String EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG = "java.codemining.show.one.parameter"; //$NON-NLS-1$ + /** * A named preference that stores the value for "Filter matching parameter names" when showing parameter names * in codemining. This will filter out parameter names when the passed parameter name implies the parameter name. @@ -4374,6 +4385,7 @@ public static void initializeDefaultValues(IPreferenceStore store) { store.setDefault(EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAMES, false); store.setDefault(EDITOR_JAVA_CODEMINING_FILTER_IMPLIED_PARAMETER_NAMES, true); store.setDefault(EDITOR_JAVA_CODEMINING_DEFAULT_FILTER_FOR_PARAMETER_NAMES, true); + store.setDefault(EDITOR_JAVA_CODEMINING_SHOW_PARAMETER_NAME_SINGLE_ARG, true); // Javadoc hover & view JavaElementLinks.initDefaultPreferences(store); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateToStringAction.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateToStringAction.java index fd32d0cf871..86b003061d8 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateToStringAction.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateToStringAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2008, 2019 Mateusz Matela and others. + * Copyright (c) 2008, 2024 Mateusz Matela and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -32,7 +32,6 @@ import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; -import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; @@ -44,7 +43,6 @@ import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration.GenerateToStringOperation; import org.eclipse.jdt.internal.corext.codemanipulation.tostringgeneration.ToStringGenerationSettings; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; @@ -187,9 +185,6 @@ CodeGenerationSettings createSettings(IType type, SourceActionDialog dialog) { super.createSettings(type, dialog).setSettings(settings); settings.createComments= dialog.getGenerateComment(); settings.useBlocks= useBlocks(type.getJavaProject()); - String version= fUnit.getJavaElement().getJavaProject().getOption(JavaCore.COMPILER_SOURCE, true); - settings.is50orHigher= !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_5); - settings.is60orHigher= !JavaModelUtil.isVersionLessThan(version, JavaCore.VERSION_1_6); return settings; } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SurroundWithTryMultiCatchAction.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SurroundWithTryMultiCatchAction.java index 30cb3ed975f..44a5cd21790 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SurroundWithTryMultiCatchAction.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SurroundWithTryMultiCatchAction.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2011, 2016 IBM Corporation and others. + * Copyright (c) 2011, 2025 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -13,20 +13,12 @@ *******************************************************************************/ package org.eclipse.jdt.ui.actions; -import org.eclipse.jface.dialogs.MessageDialog; - import org.eclipse.jface.text.ITextSelection; import org.eclipse.jdt.core.ICompilationUnit; -import org.eclipse.jdt.core.IJavaProject; -import org.eclipse.jdt.internal.core.manipulation.util.BasicElementLabels; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; -import org.eclipse.jdt.internal.corext.util.JavaModelUtil; -import org.eclipse.jdt.internal.corext.util.Messages; -import org.eclipse.jdt.internal.ui.JavaPlugin; -import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; @@ -54,18 +46,6 @@ public SurroundWithTryMultiCatchAction(CompilationUnitEditor editor) { setText(RefactoringMessages.SurroundWithTryMultiCatchAction_label); } - @Override - public void run(ITextSelection selection) { - ICompilationUnit compilationUnit= SelectionConverter.getInputAsCompilationUnit(fEditor); - IJavaProject javaProject= compilationUnit.getJavaProject(); - if (!JavaModelUtil.is1d7OrHigher(javaProject)) { - String message= Messages.format(RefactoringMessages.SurroundWithTryMultiCatchAction_not17, BasicElementLabels.getJavaElementName(javaProject.getElementName())); - MessageDialog.openInformation(JavaPlugin.getActiveWorkbenchShell(), getDialogTitle(), message); - return; - } - super.run(selection); - } - @Override SurroundWithTryCatchRefactoring createRefactoring(ITextSelection selection, ICompilationUnit cu) { return SurroundWithTryCatchRefactoring.create(cu, selection.getOffset(), selection.getLength(), true); @@ -75,15 +55,4 @@ SurroundWithTryCatchRefactoring createRefactoring(ITextSelection selection, ICom String getDialogTitle() { return RefactoringMessages.SurroundWithTryMultiCatchAction_dialog_title; } - - @Override - boolean isApplicable() { - if (!super.isApplicable()) - return false; - - ICompilationUnit compilationUnit= SelectionConverter.getInputAsCompilationUnit(fEditor); - IJavaProject javaProject= compilationUnit.getJavaProject(); - return JavaModelUtil.is1d7OrHigher(javaProject); - } - } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java index afa83d91b3e..962fbbc4891 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java @@ -571,7 +571,6 @@ public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewe } if (fJavaDoubleClickSelector == null) { fJavaDoubleClickSelector= new JavaDoubleClickSelector(); - fJavaDoubleClickSelector.setSourceVersion(fPreferenceStore.getString(JavaCore.COMPILER_SOURCE)); } return fJavaDoubleClickSelector; } @@ -967,9 +966,6 @@ public void handlePropertyChangeEvent(PropertyChangeEvent event) { if (fJavaDocScanner.affectsBehavior(event)) fJavaDocScanner.adaptToPreferenceChange(event); if (JavaCore.COMPILER_SOURCE.equals(event.getProperty()) && event.getNewValue() instanceof String) { - if (fJavaDoubleClickSelector != null) { - fJavaDoubleClickSelector.setSourceVersion((String) event.getNewValue()); - } if (fJavaStringDoubleClickStrategy != null) { fJavaStringDoubleClickStrategy.setSourceVersion((String) event.getNewValue()); } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/ISemanticTokensProvider.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/ISemanticTokensProvider.java new file mode 100644 index 00000000000..426868ee97d --- /dev/null +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/ISemanticTokensProvider.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * Copyright (c) 2024 Broadcom Inc. and others. + * This program and the accompanying materials are made + * available under the terms of the Eclipse Public License 2.0 + * which is available at https://www.eclipse.org/legal/epl-2.0/ + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Alex Boyko (Broadcom Inc.) - Initial implementation + *******************************************************************************/ +package org.eclipse.jdt.ui.text.java; + +import java.util.Collection; + +import org.eclipse.jdt.core.dom.CompilationUnit; + +/** + * Computes semantic tokens contributed to the Java source editor via extension point semanticTokens + * + * @since 3.34 + */ +public interface ISemanticTokensProvider { + + record SemanticToken(int ofset, int length, TokenType tokenType) {} + + enum TokenType { + DEFAULT, + OPERATOR, + SINGLE_LINE_COMMENT, + MULTI_LINE_COMMENT, + BRACKET, + STRING, + RESTRICTED_IDENTIFIER, + STATIC_FINAL_FIELD, + STATIC_FIELD, + FIELD, + METHOD_DECLARATION, + STATIC_METHOD_INVOCATION, + INHERITED_METHOD_INVOCATION, + ANNOTATION_ELEMENT_REFERENCE, + ABSTRACT_METHOD_INVOCATION, + LOCAL_VARIABLE_DECLARATION, + LOCAL_VARIABLE, + PARAMETER_VARIABLE, + DEPRECATED_MEMBER, + TYPE_VARIABLE, + METHOD, + AUTOBOXING, + CLASS, + ENUM, + INTERFACE, + ANNOTATION, + TYPE_ARGUMENT, + NUMBER, + ABSTRACT_CLASS, + INHERITED_FIELD, + KEYWORD, + } + + Collection computeSemanticTokens(CompilationUnit ast); + +} + + diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/correction/CUCorrectionProposal.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/correction/CUCorrectionProposal.java index b603620611f..f3a1bc0f289 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/correction/CUCorrectionProposal.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/java/correction/CUCorrectionProposal.java @@ -98,6 +98,18 @@ public CUCorrectionProposal(String name, ICompilationUnit cu, TextChange change, } + /** + * Constructs a correction proposal based on a core proposal and an image + * + * @param core the core proposal + * @param image the image to use + * @throws CoreException if obtaining text change has issue + * @since 3.34 + * + */ + public CUCorrectionProposal(CUCorrectionProposalCore core, Image image) throws CoreException { + this(core.getName(), core.getCompilationUnit(), core.getTextChange(), core.getRelevance(), image); + } /** * Constructs a correction proposal working on a compilation unit. diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPageOne.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPageOne.java index b2956fc8b8c..f5e14d6131a 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPageOne.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPageOne.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2023 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -544,9 +544,9 @@ private void fillInstalledJREs(ComboDialogField comboField) { selectionIndex= i; } if (fInstalledJVMs[i] instanceof IVMInstall2) { - fJRECompliance[i]= JavaModelUtil.getCompilerCompliance((IVMInstall2) fInstalledJVMs[i], JavaCore.VERSION_1_4); + fJRECompliance[i]= JavaModelUtil.getCompilerCompliance((IVMInstall2) fInstalledJVMs[i], JavaCore.VERSION_1_8); } else { - fJRECompliance[i]= JavaCore.VERSION_1_4; + fJRECompliance[i]= JavaCore.VERSION_1_8; } } comboField.setItems(jreLabels); @@ -852,7 +852,7 @@ public ModuleGroup() { public String getCompliance() { String compilerCompliance= fJREGroup.getSelectedCompilerCompliance(); if (compilerCompliance == null) { - compilerCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) JavaRuntime.getDefaultVMInstall(), JavaCore.VERSION_1_4); + compilerCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) JavaRuntime.getDefaultVMInstall(), JavaCore.VERSION_1_8); } return compilerCompliance; } @@ -1068,11 +1068,11 @@ public void handlePossibleJVMChange() { if (selectedJVM == null) { selectedJVM= JavaRuntime.getDefaultVMInstall(); } - String jvmCompliance= JavaCore.VERSION_1_4; + String jvmCompliance= JavaCore.VERSION_1_8; if (selectedJVM instanceof IVMInstall2) { - jvmCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) selectedJVM, JavaCore.VERSION_1_4); + jvmCompliance= JavaModelUtil.getCompilerCompliance((IVMInstall2) selectedJVM, JavaCore.VERSION_1_8); } - if (!selectedCompliance.equals(jvmCompliance) && (JavaModelUtil.is50OrHigher(selectedCompliance) || JavaModelUtil.is50OrHigher(jvmCompliance))) { + if (!selectedCompliance.equals(jvmCompliance)) { fHintText.setText(Messages.format(NewWizardMessages.NewJavaProjectWizardPageOne_DetectGroup_jre_message, new String[] {BasicElementLabels.getVersionName(selectedCompliance), BasicElementLabels.getVersionName(jvmCompliance)})); fIcon.setImage(Dialog.getImage(Dialog.DLG_IMG_MESSAGE_WARNING)); setInfoControlVisible(true); diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java index e58769444a2..00acce58d6d 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2000, 2021 IBM Corporation and others. + * Copyright (c) 2000, 2024 IBM Corporation and others. * * This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 @@ -15,10 +15,6 @@ *******************************************************************************/ package org.eclipse.jdt.ui.wizards; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.Reader; -import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.net.URI; @@ -44,12 +40,9 @@ import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; -import org.eclipse.core.runtime.Status; import org.eclipse.core.resources.IFile; -import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; -import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.dialogs.Dialog; @@ -70,20 +63,15 @@ import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.core.manipulation.StubUtility; -import org.eclipse.jdt.internal.corext.javadoc.JavaDocCommentReader; import org.eclipse.jdt.internal.corext.util.InfoFilesUtil; import org.eclipse.jdt.internal.corext.util.JavaConventionsUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Messages; -import org.eclipse.jdt.ui.JavaUI; - import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TextFieldNavigationHandler; -import org.eclipse.jdt.internal.ui.javaeditor.DocumentAdapter; -import org.eclipse.jdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; @@ -329,7 +317,7 @@ protected void handleFieldChanged(String fieldName) { private IStatus validatePackageName(String text) { IJavaProject project= getJavaProject(); if (project == null || !project.exists()) { - return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); } return JavaConventionsUtil.validatePackageName(text, project); } @@ -465,11 +453,7 @@ public IResource getModifiedResource() { IPackageFragment pack= root.getPackageFragment(getPackageText()); IResource packRes= pack.getResource(); if (isCreatePackageDocumentation()) { - if (JavaModelUtil.is50OrHigher(getJavaProject())) { - return pack.getCompilationUnit(PACKAGE_INFO_JAVA_FILENAME).getResource(); - } else if (packRes instanceof IFolder){ - return ((IFolder) packRes).getFile(PACKAGE_HTML_FILENAME); - } + return pack.getCompilationUnit(PACKAGE_INFO_JAVA_FILENAME).getResource(); } return packRes; @@ -531,11 +515,7 @@ public void createPackage(IProgressMonitor monitor) throws CoreException, Interr } if (isCreatePackageDocumentation()) { - if (JavaModelUtil.is50OrHigher(getJavaProject())) { - createPackageInfoJava(monitor); - } else { - createPackageHtml(root, monitor); - } + createPackageInfoJava(monitor); } // save whether package documentation should be created @@ -561,89 +541,4 @@ private void createPackageInfoJava(IProgressMonitor monitor) throws CoreExceptio InfoFilesUtil.createInfoJavaFile(PACKAGE_INFO_JAVA_FILENAME, fileContent.toString(), fCreatedPackageFragment,this.isAddComments(), monitor); } - - private void createPackageHtml(IPackageFragmentRoot root, IProgressMonitor monitor) throws CoreException { - IWorkspace workspace= ResourcesPlugin.getWorkspace(); - IFolder createdPackage= workspace.getRoot().getFolder(fCreatedPackageFragment.getPath()); - IFile packageHtml= createdPackage.getFile(PACKAGE_HTML_FILENAME); - String charset= packageHtml.getCharset(); - String content= buildPackageHtmlContent(root, charset); - try { - packageHtml.create(new ByteArrayInputStream(content.getBytes(charset)), false, monitor); - } catch (UnsupportedEncodingException e) { - String message= "charset " + charset + " not supported by platform"; //$NON-NLS-1$ //$NON-NLS-2$ - throw new CoreException(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, message, e)); - } - } - - private String buildPackageHtmlContent(IPackageFragmentRoot root, String charset) throws CoreException { - String lineDelimiter= StubUtility.getLineDelimiterUsed(root.getJavaProject()); - StringBuilder content = new StringBuilder(); - String fileComment= InfoFilesUtil.getFileComment(PACKAGE_INFO_JAVA_FILENAME, fCreatedPackageFragment, lineDelimiter); - String typeComment= InfoFilesUtil.getTypeComment(PACKAGE_INFO_JAVA_FILENAME, fCreatedPackageFragment, lineDelimiter); - - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - if (fileComment != null) { - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - } - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - content.append(fCreatedPackageFragment.getElementName()); - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - - if (typeComment != null) { - content.append(stripJavaComments(typeComment)); - content.append(lineDelimiter); - } - - content.append(""); //$NON-NLS-1$ - content.append(lineDelimiter); - content.append(""); //$NON-NLS-1$ - - return content.toString(); - } - - private String stripJavaComments(String comment) { - DocumentAdapter documentAdapter= new DocumentAdapter(null, fCreatedPackageFragment.getPath()); - documentAdapter.setContents(comment); - try (JavaDoc2HTMLTextReader reader= new JavaDoc2HTMLTextReader(new JavaDocCommentReader(documentAdapter, 0, comment.length()))) { - return getString(reader); - } catch (IOException e) { - throw new RuntimeException(e); - } finally { - documentAdapter.close(); - } - } - - private static String getString(Reader reader) { - StringBuilder buf= new StringBuilder(); - char[] buffer= new char[1024]; - int count; - try { - while ((count= reader.read(buffer)) != -1) - buf.append(buffer, 0, count); - } catch (IOException e) { - return null; - } - return buf.toString(); - } - } diff --git a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java index ff190fb2a43..9a761891dc2 100644 --- a/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java +++ b/org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java @@ -108,7 +108,6 @@ import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.ImportDeclaration; -import org.eclipse.jdt.core.dom.ParameterizedType; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.rewrite.ASTRewrite; @@ -859,14 +858,14 @@ private IPackageFragment getPackage(IJavaProject javaProject) { private static IStatus validateJavaTypeName(String text, IJavaProject project) { if (project == null || !project.exists()) { - return JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null); + return JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8, null); } return JavaConventionsUtil.validateJavaTypeName(text, project); } private static IStatus validatePackageName(String text, IJavaProject project) { if (project == null || !project.exists()) { - return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3); + return JavaConventions.validatePackageName(text, JavaCore.VERSION_1_8, JavaCore.VERSION_1_8); } return JavaConventionsUtil.validatePackageName(text, project); } @@ -1834,10 +1833,6 @@ protected IStatus containerChanged() { IStatus status= super.containerChanged(); IPackageFragmentRoot root= getPackageFragmentRoot(); if ((fTypeKind == ANNOTATION_TYPE || fTypeKind == ENUM_TYPE) && !status.matches(IStatus.ERROR)) { - if (root != null && !JavaModelUtil.is50OrHigher(root.getJavaProject())) { - // error as createType will fail otherwise (bug 96928) - return new StatusInfo(IStatus.ERROR, Messages.format(NewWizardMessages.NewTypeWizardPage_warning_NotJDKCompliant, BasicElementLabels.getJavaElementName(root.getJavaProject().getElementName()))); - } if (root != null && fTypeKind == ENUM_TYPE) { try { // if findType(...) == null then Enum is unavailable @@ -2150,10 +2145,6 @@ protected IStatus typeNameChanged() { } if (!typeNameWithParameters.equals(typeName) && project != null) { - if (!JavaModelUtil.is50OrHigher(project)) { - status.setError(NewWizardMessages.NewTypeWizardPage_error_TypeParameters); - return status; - } String typeDeclaration= "class " + typeNameWithParameters + " {}"; //$NON-NLS-1$//$NON-NLS-2$ ASTParser parser= ASTParser.newParser(IASTSharedValues.SHARED_AST_LEVEL); parser.setSource(typeDeclaration.toCharArray()); @@ -2212,10 +2203,6 @@ protected IStatus superClassChanged() { status.setError(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperClassName); return status; } - if (type instanceof ParameterizedType && ! JavaModelUtil.is50OrHigher(root.getJavaProject())) { - status.setError(NewWizardMessages.NewTypeWizardPage_error_SuperClassNotParameterized); - return status; - } } else { status.setError(""); //$NON-NLS-1$ } @@ -2480,10 +2467,6 @@ protected IStatus superInterfacesChanged() { status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperInterfaceName, BasicElementLabels.getJavaElementName(intfname))); return status; } - if (type instanceof ParameterizedType && ! JavaModelUtil.is50OrHigher(root.getJavaProject())) { - status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_SuperInterfaceNotParameterized, BasicElementLabels.getJavaElementName(intfname))); - return status; - } } } fSealedSuperInterfacesStatus= validateSealedSuperInterfacesStatus();