From f6714434cb3a7614bdd0a532d0c7ef99adee2008 Mon Sep 17 00:00:00 2001 From: UNV Date: Thu, 8 May 2025 03:17:32 +0300 Subject: [PATCH] Replacing CommonClassNames with JavaClassNames (part 3). Refactoring. --- .../com/siyeh/ig/callMatcher/CallMatcher.java | 9 +- .../siyeh/ig/psiutils/CollectionUtils.java | 65 ++- .../siyeh/ig/psiutils/ConstructionUtils.java | 68 ++-- .../ig/psiutils/JavaDeprecationUtils.java | 20 +- .../language/psi/util/PropertyUtilBase.java | 219 +++++------ .../language/psi/util/PsiPrecedenceUtil.java | 141 ++++--- .../psi/controlFlow/ControlFlowAnalyzer.java | 371 ++++++++++-------- .../impl/psi/impl/PsiSubstitutorImpl.java | 92 ++--- .../impl/psi/scope/util/PsiScopesUtil.java | 201 +++++----- 9 files changed, 603 insertions(+), 583 deletions(-) diff --git a/java-analysis-impl/src/main/java/com/siyeh/ig/callMatcher/CallMatcher.java b/java-analysis-impl/src/main/java/com/siyeh/ig/callMatcher/CallMatcher.java index 489c84786..d581acc05 100644 --- a/java-analysis-impl/src/main/java/com/siyeh/ig/callMatcher/CallMatcher.java +++ b/java-analysis-impl/src/main/java/com/siyeh/ig/callMatcher/CallMatcher.java @@ -6,6 +6,8 @@ import com.intellij.java.language.psi.util.InheritanceUtil; import com.intellij.java.language.psi.util.PsiUtil; import com.siyeh.ig.psiutils.MethodCallUtils; +import consulo.annotation.access.RequiredReadAction; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.util.collection.ArrayUtil; import consulo.util.lang.ObjectUtil; @@ -220,7 +222,7 @@ class Simple implements CallMatcher { static final Simple ENUM_VALUES = new Simple("", Collections.singleton("values"), ArrayUtil.EMPTY_STRING_ARRAY, CallType.ENUM_STATIC); static final Simple ENUM_VALUE_OF = - new Simple("", Collections.singleton("valueOf"), new String[]{CommonClassNames.JAVA_LANG_STRING}, CallType.ENUM_STATIC); + new Simple("", Collections.singleton("valueOf"), new String[]{JavaClassNames.JAVA_LANG_STRING}, CallType.ENUM_STATIC); @Nonnull private final String myClassName; @Nonnull @@ -283,6 +285,7 @@ private static boolean parameterTypeMatches(String type, PsiParameter parameter) @Contract(pure = true) @Override + @RequiredReadAction public boolean methodReferenceMatches(PsiMethodReferenceExpression methodRef) { if (methodRef == null) { return false; @@ -351,8 +354,8 @@ public boolean methodMatches(PsiMethod method) { if (aClass == null) { return false; } - return myCallType.matches(aClass, myClassName, method.hasModifierProperty(PsiModifier.STATIC)) && - parametersMatch(method.getParameterList()); + return myCallType.matches(aClass, myClassName, method.isStatic()) + && parametersMatch(method.getParameterList()); } @Override diff --git a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/CollectionUtils.java b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/CollectionUtils.java index acf1118ba..c13375d84 100644 --- a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/CollectionUtils.java +++ b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/CollectionUtils.java @@ -19,29 +19,24 @@ import com.intellij.java.language.psi.util.InheritanceUtil; import com.siyeh.ig.callMatcher.CallMatcher; import consulo.java.language.module.util.JavaClassNames; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NonNls; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; +import org.jetbrains.annotations.Contract; import java.util.*; public class CollectionUtils { - /** * @noinspection StaticCollection */ - @NonNls private static final Set s_allCollectionClassesAndInterfaces; /** * @noinspection StaticCollection */ - @NonNls private static final Map s_interfaceForCollection = new HashMap<>(); static { - final Set allCollectionClassesAndInterfaces = new HashSet<>(); + Set allCollectionClassesAndInterfaces = new HashSet<>(); allCollectionClassesAndInterfaces.add("java.util.AbstractCollection"); allCollectionClassesAndInterfaces.add("java.util.AbstractList"); allCollectionClassesAndInterfaces.add("java.util.AbstractMap"); @@ -123,7 +118,7 @@ public class CollectionUtils { s_interfaceForCollection.put("WeakHashMap", "Map"); s_interfaceForCollection.put(JavaClassNames.JAVA_UTIL_ARRAY_LIST, JavaClassNames.JAVA_UTIL_LIST); s_interfaceForCollection.put("java.util.EnumMap", JavaClassNames.JAVA_UTIL_MAP); - s_interfaceForCollection.put("java.util.EnumSet", JavaClassNames.JAVA_UTIL_SET); + s_interfaceForCollection.put(JavaClassNames.JAVA_UTIL_ENUM_SET, JavaClassNames.JAVA_UTIL_SET); s_interfaceForCollection.put(JavaClassNames.JAVA_UTIL_HASH_MAP, JavaClassNames.JAVA_UTIL_MAP); s_interfaceForCollection.put(JavaClassNames.JAVA_UTIL_HASH_SET, JavaClassNames.JAVA_UTIL_SET); s_interfaceForCollection.put("java.util.Hashtable", JavaClassNames.JAVA_UTIL_MAP); @@ -150,7 +145,7 @@ public class CollectionUtils { * Matches a call which creates collection of the same size as the qualifier collection */ public static final CallMatcher DERIVED_COLLECTION = CallMatcher.anyOf( - CallMatcher.instanceCall(CommonClassNames.JAVA_UTIL_MAP, "keySet", "values", "entrySet").parameterCount(0), + CallMatcher.instanceCall(JavaClassNames.JAVA_UTIL_MAP, "keySet", "values", "entrySet").parameterCount(0), CallMatcher.instanceCall("java.util.NavigableMap", "descendingKeySet", "descendingMap", "navigableKeySet") .parameterCount(0), CallMatcher.instanceCall("java.util.NavigableSet", "descendingSet").parameterCount(0) @@ -167,11 +162,10 @@ public static Set getAllCollectionNames() { @Contract("null -> false") public static boolean isConcreteCollectionClass(@Nullable PsiType type) { - if (!(type instanceof PsiClassType)) { + if (!(type instanceof PsiClassType classType)) { return false; } - final PsiClassType classType = (PsiClassType)type; - final PsiClass resolved = classType.resolve(); + PsiClass resolved = classType.resolve(); if (resolved == null) { return false; } @@ -180,30 +174,29 @@ public static boolean isConcreteCollectionClass(@Nullable PsiType type) { @Contract("null -> false") public static boolean isConcreteCollectionClass(PsiClass aClass) { - if (aClass == null || aClass.isEnum() || aClass.isInterface() || aClass.isAnnotationType() || aClass.hasModifierProperty(PsiModifier.ABSTRACT)) { + if (aClass == null || aClass.isEnum() || aClass.isInterface() || aClass.isAnnotationType() || aClass.isAbstract()) { return false; } if (!InheritanceUtil.isInheritor(aClass, JavaClassNames.JAVA_UTIL_COLLECTION) && !InheritanceUtil.isInheritor(aClass, JavaClassNames.JAVA_UTIL_MAP)) { return false; } - @NonNls final String name = aClass.getQualifiedName(); + String name = aClass.getQualifiedName(); return name != null && name.startsWith("java.util."); } public static boolean isCollectionClassOrInterface(@Nullable PsiType type) { - if (!(type instanceof PsiClassType)) { + if (!(type instanceof PsiClassType classType)) { return false; } - final PsiClassType classType = (PsiClassType)type; - final PsiClass resolved = classType.resolve(); + PsiClass resolved = classType.resolve(); if (resolved == null) { return false; } - return InheritanceUtil.isInheritor(resolved, JavaClassNames.JAVA_UTIL_COLLECTION) || - InheritanceUtil.isInheritor(resolved, JavaClassNames.JAVA_UTIL_MAP) || - InheritanceUtil.isInheritor(resolved, "com.google.common.collect.Multimap") || - InheritanceUtil.isInheritor(resolved, "com.google.common.collect.Table"); + return InheritanceUtil.isInheritor(resolved, JavaClassNames.JAVA_UTIL_COLLECTION) + || InheritanceUtil.isInheritor(resolved, JavaClassNames.JAVA_UTIL_MAP) + || InheritanceUtil.isInheritor(resolved, "com.google.common.collect.Multimap") + || InheritanceUtil.isInheritor(resolved, "com.google.common.collect.Table"); } public static boolean isCollectionClassOrInterface(PsiClass aClass) { @@ -218,11 +211,11 @@ private static boolean isCollectionClassOrInterface(PsiClass aClass, Set= 0) { - baseName = name.substring(0, parameterStart).trim(); - } - else { - baseName = name; - } + int parameterStart = name.indexOf((int)'<'); + String baseName = parameterStart >= 0 ? name.substring(0, parameterStart).trim() : name; return s_interfaceForCollection.get(baseName); } } \ No newline at end of file diff --git a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/ConstructionUtils.java b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/ConstructionUtils.java index d9ba8b6cc..1ea36be89 100644 --- a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/ConstructionUtils.java +++ b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/ConstructionUtils.java @@ -19,6 +19,7 @@ import com.intellij.java.language.psi.util.InheritanceUtil; import com.intellij.java.language.psi.util.PsiUtil; import com.siyeh.ig.callMatcher.CallMatcher; +import consulo.annotation.access.RequiredReadAction; import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import jakarta.annotation.Nullable; @@ -34,7 +35,8 @@ public class ConstructionUtils { private static final Set GUAVA_UTILITY_CLASSES = Set.of("com.google.common.collect.Maps", "com.google.common.collect.Lists", "com.google.common.collect.Sets"); - private static final CallMatcher ENUM_SET_NONE_OF = CallMatcher.staticCall("java.util.EnumSet", "noneOf").parameterCount(1); + private static final CallMatcher ENUM_SET_NONE_OF = + CallMatcher.staticCall(JavaClassNames.JAVA_UTIL_ENUM_SET, "noneOf").parameterCount(1); /** * Checks that given expression initializes empty StringBuilder or StringBuffer (either with explicit default capacity or not) @@ -43,6 +45,7 @@ public class ConstructionUtils { * @return true if the initializer is empty StringBuilder or StringBuffer initializer */ @Contract("null -> false") + @RequiredReadAction public static boolean isEmptyStringBuilderInitializer(PsiExpression initializer) { return "\"\"".equals(getStringBuilderInitializerText(initializer)); } @@ -55,38 +58,37 @@ public static boolean isEmptyStringBuilderInitializer(PsiExpression initializer) * construction expression */ @Contract("null -> null") + @RequiredReadAction public static String getStringBuilderInitializerText(PsiExpression construction) { construction = PsiUtil.skipParenthesizedExprDown(construction); - if (!(construction instanceof PsiNewExpression)) { + if (!(construction instanceof PsiNewExpression newExpr)) { return null; } - final PsiNewExpression newExpression = (PsiNewExpression)construction; - final PsiJavaCodeReferenceElement classReference = newExpression.getClassReference(); + PsiJavaCodeReferenceElement classReference = newExpr.getClassReference(); if (classReference == null) { return null; } - final PsiElement target = classReference.resolve(); - if (!(target instanceof PsiClass)) { + PsiElement target = classReference.resolve(); + if (!(target instanceof PsiClass aClass)) { return null; } - final PsiClass aClass = (PsiClass)target; - final String qualifiedName = aClass.getQualifiedName(); + String qualifiedName = aClass.getQualifiedName(); if (!JavaClassNames.JAVA_LANG_STRING_BUILDER.equals(qualifiedName) && !JavaClassNames.JAVA_LANG_STRING_BUFFER.equals(qualifiedName)) { return null; } - final PsiExpressionList argumentList = newExpression.getArgumentList(); + PsiExpressionList argumentList = newExpr.getArgumentList(); if (argumentList == null) { return null; } - final PsiExpression[] arguments = argumentList.getExpressions(); + PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length == 0) { return "\"\""; } if (arguments.length != 1) { return null; } - final PsiExpression argument = arguments[0]; - final PsiType argumentType = argument.getType(); + PsiExpression argument = arguments[0]; + PsiType argumentType = argument.getType(); if (PsiType.INT.equals(argumentType)) { return "\"\""; } @@ -102,8 +104,8 @@ public static String getStringBuilderInitializerText(PsiExpression construction) @Contract("null -> false") public static boolean isEmptyCollectionInitializer(PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); - if (expression instanceof PsiNewExpression) { - PsiExpressionList argumentList = ((PsiNewExpression)expression).getArgumentList(); + if (expression instanceof PsiNewExpression newExpr) { + PsiExpressionList argumentList = newExpr.getArgumentList(); if (argumentList != null && argumentList.getExpressions().length == 0) { PsiType type = expression.getType(); return InheritanceUtil.isInheritor(type, JavaClassNames.JAVA_UTIL_COLLECTION) @@ -139,12 +141,12 @@ public static boolean isEmptyCollectionInitializer(PsiExpression expression) { @Contract("null -> false") public static boolean isCustomizedEmptyCollectionInitializer(PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); - if (expression instanceof PsiNewExpression) { - PsiExpressionList argumentList = ((PsiNewExpression)expression).getArgumentList(); + if (expression instanceof PsiNewExpression newExpr) { + PsiExpressionList argumentList = newExpr.getArgumentList(); if (argumentList == null || argumentList.getExpressions().length == 0) { return false; } - PsiMethod constructor = ((PsiNewExpression)expression).resolveConstructor(); + PsiMethod constructor = newExpr.resolveConstructor(); if (constructor == null) { return false; } @@ -160,8 +162,7 @@ public static boolean isCustomizedEmptyCollectionInitializer(PsiExpression expre t -> t instanceof PsiPrimitiveType || InheritanceUtil.isInheritor(t, JavaClassNames.JAVA_LANG_CLASS); return Stream.of(constructor.getParameterList().getParameters()).map(PsiParameter::getType).allMatch(allowedParameterType); } - if (expression instanceof PsiMethodCallExpression) { - PsiMethodCallExpression call = (PsiMethodCallExpression)expression; + if (expression instanceof PsiMethodCallExpression call) { if (ENUM_SET_NONE_OF.test(call)) { return true; } @@ -186,12 +187,12 @@ public static boolean isCustomizedEmptyCollectionInitializer(PsiExpression expre public static boolean isPrepopulatedCollectionInitializer(PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); - if (expression instanceof PsiNewExpression) { - PsiExpressionList args = ((PsiNewExpression)expression).getArgumentList(); + if (expression instanceof PsiNewExpression newExpr) { + PsiExpressionList args = newExpr.getArgumentList(); if (args == null || args.isEmpty()) { return false; } - PsiMethod ctor = ((PsiNewExpression)expression).resolveMethod(); + PsiMethod ctor = newExpr.resolveMethod(); if (ctor == null) { return false; } @@ -207,15 +208,14 @@ public static boolean isPrepopulatedCollectionInitializer(PsiExpression expressi PsiType type = parameter.getType(); if (type instanceof PsiClassType) { PsiClassType rawType = ((PsiClassType)type).rawType(); - if (rawType.equalsToText(CommonClassNames.JAVA_UTIL_COLLECTION) || - rawType.equalsToText(CommonClassNames.JAVA_UTIL_MAP)) { + if (rawType.equalsToText(JavaClassNames.JAVA_UTIL_COLLECTION) + || rawType.equalsToText(JavaClassNames.JAVA_UTIL_MAP)) { return true; } } } } - if (expression instanceof PsiMethodCallExpression) { - PsiMethodCallExpression call = (PsiMethodCallExpression)expression; + if (expression instanceof PsiMethodCallExpression call) { String name = call.getMethodExpression().getReferenceName(); PsiExpressionList argumentList = call.getArgumentList(); if (name != null && name.startsWith("new") && !argumentList.isEmpty()) { @@ -238,8 +238,8 @@ public static boolean isPrepopulatedCollectionInitializer(PsiExpression expressi } if (type instanceof PsiClassType) { PsiClassType rawType = ((PsiClassType)type).rawType(); - if (rawType.equalsToText(CommonClassNames.JAVA_LANG_ITERABLE) || - rawType.equalsToText(CommonClassNames.JAVA_UTIL_ITERATOR)) { + if (rawType.equalsToText(JavaClassNames.JAVA_LANG_ITERABLE) + || rawType.equalsToText(JavaClassNames.JAVA_UTIL_ITERATOR)) { return true; } } @@ -255,23 +255,23 @@ public static boolean isPrepopulatedCollectionInitializer(PsiExpression expressi * @param expression expression to test * @return true if supplied expression is an empty array initializer */ + @RequiredReadAction public static boolean isEmptyArrayInitializer(@Nullable PsiExpression expression) { expression = PsiUtil.skipParenthesizedExprDown(expression); - if (!(expression instanceof PsiNewExpression)) { + if (!(expression instanceof PsiNewExpression newExpr)) { return false; } - final PsiNewExpression newExpression = (PsiNewExpression)expression; - final PsiExpression[] dimensions = newExpression.getArrayDimensions(); + PsiExpression[] dimensions = newExpr.getArrayDimensions(); if (dimensions.length == 0) { - final PsiArrayInitializerExpression arrayInitializer = newExpression.getArrayInitializer(); + PsiArrayInitializerExpression arrayInitializer = newExpr.getArrayInitializer(); if (arrayInitializer == null) { return false; } - final PsiExpression[] initializers = arrayInitializer.getInitializers(); + PsiExpression[] initializers = arrayInitializer.getInitializers(); return initializers.length == 0; } for (PsiExpression dimension : dimensions) { - final String dimensionText = dimension.getText(); + String dimensionText = dimension.getText(); if (!"0".equals(dimensionText)) { return false; } diff --git a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/JavaDeprecationUtils.java b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/JavaDeprecationUtils.java index f58218f6b..ac9dc0148 100644 --- a/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/JavaDeprecationUtils.java +++ b/java-analysis-impl/src/main/java/com/siyeh/ig/psiutils/JavaDeprecationUtils.java @@ -8,6 +8,7 @@ import com.intellij.java.language.psi.util.PsiUtil; import consulo.annotation.access.RequiredReadAction; import consulo.java.language.module.extension.JavaModuleExtension; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.language.util.ModuleUtilCore; import consulo.util.lang.ObjectUtil; @@ -19,7 +20,7 @@ public final class JavaDeprecationUtils { @Nonnull @RequiredReadAction private static ThreeState isDeprecatedByAnnotation(@Nonnull PsiModifierListOwner owner, @Nullable PsiElement context) { - PsiAnnotation annotation = AnnotationUtil.findAnnotation(owner, CommonClassNames.JAVA_LANG_DEPRECATED); + PsiAnnotation annotation = AnnotationUtil.findAnnotation(owner, JavaClassNames.JAVA_LANG_DEPRECATED); if (annotation == null) { return ThreeState.UNSURE; } @@ -28,8 +29,8 @@ private static ThreeState isDeprecatedByAnnotation(@Nonnull PsiModifierListOwner } String since = null; PsiAnnotationMemberValue value = annotation.findAttributeValue("since"); - if (value instanceof PsiLiteralExpression) { - since = ObjectUtil.tryCast(((PsiLiteralExpression)value).getValue(), String.class); + if (value instanceof PsiLiteralExpression literal) { + since = ObjectUtil.tryCast(literal.getValue(), String.class); } if (since == null || ModuleUtilCore.getSdk(owner, JavaModuleExtension.class) == null) { return ThreeState.YES; @@ -51,17 +52,18 @@ private static ThreeState isDeprecatedByAnnotation(@Nonnull PsiModifierListOwner */ @RequiredReadAction public static boolean isDeprecated(@Nonnull PsiElement psiElement, @Nullable PsiElement context) { - if (psiElement instanceof PsiModifierListOwner) { - ThreeState byAnnotation = isDeprecatedByAnnotation((PsiModifierListOwner)psiElement, context); + if (psiElement instanceof PsiModifierListOwner modifierListOwner) { + ThreeState byAnnotation = isDeprecatedByAnnotation(modifierListOwner, context); if (byAnnotation != ThreeState.UNSURE) { return byAnnotation.toBoolean(); } } - if (psiElement instanceof PsiDocCommentOwner) { - return ((PsiDocCommentOwner)psiElement).isDeprecated(); + if (psiElement instanceof PsiDocCommentOwner docCommentOwner) { + return docCommentOwner.isDeprecated(); } - if (psiElement instanceof PsiJavaDocumentedElement) { - return PsiImplUtil.isDeprecatedByDocTag((PsiJavaDocumentedElement)psiElement); + //noinspection SimplifiableIfStatement + if (psiElement instanceof PsiJavaDocumentedElement javaDocumentedElement) { + return PsiImplUtil.isDeprecatedByDocTag(javaDocumentedElement); } return false; } diff --git a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PropertyUtilBase.java b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PropertyUtilBase.java index ac3a68ef2..410fe7e58 100644 --- a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PropertyUtilBase.java +++ b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PropertyUtilBase.java @@ -6,6 +6,8 @@ import com.intellij.java.language.psi.codeStyle.JavaCodeStyleManager; import com.intellij.java.language.psi.codeStyle.VariableKind; import com.intellij.java.language.util.PropertyKind; +import consulo.annotation.access.RequiredReadAction; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.codeStyle.CodeStyleManager; import consulo.language.psi.PsiElement; import consulo.project.Project; @@ -14,54 +16,46 @@ import consulo.util.lang.Comparing; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NonNls; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; import kava.beans.Introspector; +import org.jetbrains.annotations.Contract; import java.util.*; public class PropertyUtilBase { - - @NonNls protected static final String GET_PREFIX = PropertyKind.GETTER.prefix; - @NonNls protected static final String IS_PREFIX = PropertyKind.BOOLEAN_GETTER.prefix; @Nonnull protected static final String SET_PREFIX = PropertyKind.SETTER.prefix; @Nullable - public static String getPropertyName(@NonNls @Nonnull String methodName) { + public static String getPropertyName(@Nonnull String methodName) { return StringUtil.getPropertyName(methodName); } @Nonnull public static Map getAllProperties( - @Nonnull final PsiClass psiClass, - final boolean acceptSetters, - final boolean acceptGetters + @Nonnull PsiClass psiClass, + boolean acceptSetters, + boolean acceptGetters ) { return getAllProperties(psiClass, acceptSetters, acceptGetters, true); } @Nonnull public static Map getAllProperties( - @Nonnull final PsiClass psiClass, - final boolean acceptSetters, - final boolean acceptGetters, - final boolean includeSuperClass + @Nonnull PsiClass psiClass, + boolean acceptSetters, + boolean acceptGetters, + boolean includeSuperClass ) { return getAllProperties(acceptSetters, acceptGetters, includeSuperClass ? psiClass.getAllMethods() : psiClass.getMethods()); } @Nonnull - public static Map getAllProperties( - final boolean acceptSetters, - final boolean acceptGetters, PsiMethod[] methods - ) { - final Map map = new HashMap<>(); + public static Map getAllProperties(boolean acceptSetters, boolean acceptGetters, PsiMethod[] methods) { + Map map = new HashMap<>(); for (PsiMethod method : methods) { if (filterMethods(method)) { @@ -76,8 +70,8 @@ acceptGetters && isSimplePropertyGetter(method)) { } - private static boolean filterMethods(final PsiMethod method) { - if (method.hasModifierProperty(PsiModifier.STATIC) || !method.hasModifierProperty(PsiModifier.PUBLIC)) { + private static boolean filterMethods(PsiMethod method) { + if (method.isStatic() || !method.isPublic()) { return true; } @@ -85,15 +79,15 @@ private static boolean filterMethods(final PsiMethod method) { if (psiClass == null) { return false; } - final String className = psiClass.getQualifiedName(); - return CommonClassNames.JAVA_LANG_OBJECT.equals(className); + String className = psiClass.getQualifiedName(); + return JavaClassNames.JAVA_LANG_OBJECT.equals(className); } @Nonnull - public static List getSetters(@Nonnull final PsiClass psiClass, final String propertyName) { - final String setterName = suggestSetterName(propertyName); - final PsiMethod[] psiMethods = psiClass.findMethodsByName(setterName, true); - final ArrayList list = new ArrayList<>(psiMethods.length); + public static List getSetters(@Nonnull PsiClass psiClass, String propertyName) { + String setterName = suggestSetterName(propertyName); + PsiMethod[] psiMethods = psiClass.findMethodsByName(setterName, true); + ArrayList list = new ArrayList<>(psiMethods.length); for (PsiMethod method : psiMethods) { if (filterMethods(method)) { continue; @@ -106,11 +100,10 @@ public static List getSetters(@Nonnull final PsiClass psiClass, final } @Nonnull - public static List getGetters(@Nonnull final PsiClass psiClass, final String propertyName) { - final String[] names = suggestGetterNames(propertyName); - final ArrayList list = new ArrayList<>(); - for (String name : names) { - final PsiMethod[] psiMethods = psiClass.findMethodsByName(name, true); + public static List getGetters(@Nonnull PsiClass psiClass, String propertyName) { + ArrayList list = new ArrayList<>(); + for (String name : suggestGetterNames(propertyName)) { + PsiMethod[] psiMethods = psiClass.findMethodsByName(name, true); for (PsiMethod method : psiMethods) { if (filterMethods(method)) { continue; @@ -124,7 +117,7 @@ public static List getGetters(@Nonnull final PsiClass psiClass, final } @Nonnull - public static List getAccessors(@Nonnull final PsiClass psiClass, final String propertyName) { + public static List getAccessors(@Nonnull PsiClass psiClass, String propertyName) { return ContainerUtil.concat(getGetters(psiClass, propertyName), getSetters(psiClass, propertyName)); } @@ -135,7 +128,7 @@ public static String[] getReadableProperties(@Nonnull PsiClass aClass, boolean i PsiMethod[] methods = includeSuperClass ? aClass.getAllMethods() : aClass.getMethods(); for (PsiMethod method : methods) { - if (CommonClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName())) { + if (JavaClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName())) { continue; } @@ -154,7 +147,7 @@ public static String[] getWritableProperties(@Nonnull PsiClass aClass, boolean i PsiMethod[] methods = includeSuperClass ? aClass.getAllMethods() : aClass.getMethods(); for (PsiMethod method : methods) { - if (CommonClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName())) { + if (JavaClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName())) { continue; } @@ -167,17 +160,16 @@ public static String[] getWritableProperties(@Nonnull PsiClass aClass, boolean i } @Nullable - public static PsiType getPropertyType(final PsiMember member) { - if (member instanceof PsiField) { - return ((PsiField)member).getType(); + public static PsiType getPropertyType(PsiMember member) { + if (member instanceof PsiField field) { + return field.getType(); } - if (member instanceof PsiMethod) { - final PsiMethod psiMethod = (PsiMethod)member; - if (isSimplePropertyGetter(psiMethod)) { - return psiMethod.getReturnType(); + if (member instanceof PsiMethod method) { + if (isSimplePropertyGetter(method)) { + return method.getReturnType(); } - else if (isSimplePropertySetter(psiMethod)) { - return psiMethod.getParameterList().getParameters()[0].getType(); + else if (isSimplePropertySetter(method)) { + return method.getParameterList().getParameters()[0].getType(); } } return null; @@ -198,7 +190,7 @@ public static PsiMethod findPropertySetter( PsiMethod[] methods = aClass.findMethodsByName(setterName, checkSuperClasses); for (PsiMethod method : methods) { - if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) { + if (method.isStatic() != isStatic) { continue; } @@ -217,7 +209,7 @@ public static PsiField findPropertyField(PsiClass aClass, String propertyName, b PsiField[] fields = aClass.getAllFields(); for (PsiField field : fields) { - if (field.hasModifierProperty(PsiModifier.STATIC) != isStatic) { + if (field.isStatic() != isStatic) { continue; } if (propertyName.equals(suggestPropertyName(field))) { @@ -243,7 +235,7 @@ public static PsiMethod findPropertyGetter( for (String getterCandidateName : getterCandidateNames) { PsiMethod[] getterCandidates = aClass.findMethodsByName(getterCandidateName, checkSuperClasses); for (PsiMethod method : getterCandidates) { - if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) { + if (method.isStatic() != isStatic) { continue; } @@ -267,15 +259,13 @@ public static PsiMethod findPropertyGetterWithType( ) { while (methods.hasNext()) { PsiMethod method = methods.next(); - if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) { + if (method.isStatic() != isStatic) { continue; } - if (isSimplePropertyGetter(method)) { - if (getPropertyNameByGetter(method).equals(propertyName)) { - if (type.equals(method.getReturnType())) { - return method; - } - } + if (isSimplePropertyGetter(method) + && getPropertyNameByGetter(method).equals(propertyName) + && type.equals(method.getReturnType())) { + return method; } } return null; @@ -294,7 +284,7 @@ public static PsiMethod findPropertySetterWithType( ) { while (methods.hasNext()) { PsiMethod method = methods.next(); - if (method.hasModifierProperty(PsiModifier.STATIC) != isStatic) { + if (method.isStatic() != isStatic) { continue; } @@ -334,7 +324,7 @@ public static boolean isSimplePropertyGetter(@Nullable PsiMethod method) { } - public static boolean hasGetterName(final PsiMethod method) { + public static boolean hasGetterName(PsiMethod method) { if (method == null) { return false; } @@ -372,7 +362,7 @@ public static String suggestPropertyName(@Nonnull PsiField field, @Nonnull Strin JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(field.getProject()); VariableKind kind = codeStyleManager.getVariableKind(field); String name = codeStyleManager.variableNameToPropertyName(fieldName, kind); - if (!field.hasModifierProperty(PsiModifier.STATIC) && isBoolean(field.getType())) { + if (!field.isStatic() && isBoolean(field.getType())) { if (name.startsWith(IS_PREFIX) && name.length() > IS_PREFIX.length() && Character.isUpperCase(name.charAt(IS_PREFIX.length()))) { name = Introspector.decapitalize(name.substring(IS_PREFIX.length())); } @@ -391,7 +381,7 @@ public static String suggestSetterName(PsiField field) { } @Nullable - public static String getPropertyName(final PsiMember member) { + public static String getPropertyName(PsiMember member) { if (member instanceof PsiMethod) { return getPropertyName((PsiMethod)member); } @@ -421,8 +411,9 @@ public static boolean isSimplePropertySetter(@Nullable PsiMethod method) { return false; } - final PsiType returnType = method.getReturnType(); + PsiType returnType = method.getReturnType(); + //noinspection SimplifiableIfStatement if (returnType == null || PsiType.VOID.equals(returnType)) { return true; } @@ -447,7 +438,7 @@ public static String getPropertyName(@Nonnull PsiMethod method) { @Nonnull public static String getPropertyNameByGetter(PsiMethod getterMethod) { - @NonNls String methodName = getterMethod.getName(); + String methodName = getterMethod.getName(); if (methodName.startsWith(GET_PREFIX)) { return StringUtil.decapitalize(methodName.substring(3)); } @@ -469,26 +460,25 @@ private static boolean checkPrefix(@Nonnull String methodName, @Nonnull String p (methodName.length() == prefix.length() + 1 || Character.isLowerCase(methodName.charAt(prefix.length() + 1)))); } - @NonNls @Nonnull public static String[] suggestGetterNames(@Nonnull String propertyName) { - final String str = StringUtil.capitalizeWithJavaBeanConvention(StringUtil.sanitizeJavaIdentifier(propertyName)); + String str = StringUtil.capitalizeWithJavaBeanConvention(StringUtil.sanitizeJavaIdentifier(propertyName)); return new String[]{ IS_PREFIX + str, GET_PREFIX + str }; } - public static String suggestGetterName(@NonNls @Nonnull String propertyName, @Nullable PsiType propertyType) { + public static String suggestGetterName(@Nonnull String propertyName, @Nullable PsiType propertyType) { return suggestGetterName(propertyName, propertyType, null); } public static String suggestGetterName( @Nonnull String propertyName, @Nullable PsiType propertyType, - @NonNls String existingGetterName + String existingGetterName ) { - @NonNls StringBuilder name = + StringBuilder name = new StringBuilder(StringUtil.capitalizeWithJavaBeanConvention(StringUtil.sanitizeJavaIdentifier(propertyName))); if (isBoolean(propertyType)) { if (existingGetterName == null || !existingGetterName.startsWith(GET_PREFIX)) { @@ -506,16 +496,16 @@ public static String suggestGetterName( } - public static String suggestSetterName(@NonNls @Nonnull String propertyName) { + public static String suggestSetterName(@Nonnull String propertyName) { return suggestSetterName(propertyName, SET_PREFIX); } - public static String suggestSetterName(@NonNls @Nonnull String propertyName, String setterPrefix) { - final String sanitizeJavaIdentifier = StringUtil.sanitizeJavaIdentifier(propertyName); + public static String suggestSetterName(@Nonnull String propertyName, String setterPrefix) { + String sanitizeJavaIdentifier = StringUtil.sanitizeJavaIdentifier(propertyName); if (StringUtil.isEmpty(setterPrefix)) { return sanitizeJavaIdentifier; } - @NonNls StringBuilder name = new StringBuilder(StringUtil.capitalizeWithJavaBeanConvention(sanitizeJavaIdentifier)); + StringBuilder name = new StringBuilder(StringUtil.capitalizeWithJavaBeanConvention(sanitizeJavaIdentifier)); name.insert(0, setterPrefix); return name.toString(); } @@ -533,7 +523,7 @@ public static PsiMethod generateGetterPrototype(@Nonnull PsiField field) { String getName = suggestGetterName(field); PsiMethod getMethod = factory.createMethod(getName, field.getType()); PsiUtil.setModifierProperty(getMethod, PsiModifier.PUBLIC, true); - if (field.hasModifierProperty(PsiModifier.STATIC)) { + if (field.isStatic()) { PsiUtil.setModifierProperty(getMethod, PsiModifier.STATIC, true); } @@ -571,13 +561,14 @@ public static PsiMethod generateSetterPrototype(@Nonnull PsiField field, @Nonnul * to add @Override annotation */ @Nonnull + @RequiredReadAction public static PsiMethod generateSetterPrototype(@Nonnull PsiField field, @Nonnull PsiClass containingClass, boolean returnSelf) { Project project = field.getProject(); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); PsiElementFactory factory = JavaPsiFacade.getElementFactory(field.getProject()); String name = field.getName(); - boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); + boolean isStatic = field.isStatic(); VariableKind kind = codeStyleManager.getVariableKind(field); String propertyName = codeStyleManager.variableNameToPropertyName(name, kind); String setName = suggestSetterName(field); @@ -594,7 +585,7 @@ public static PsiMethod generateSetterPrototype(@Nonnull PsiField field, @Nonnul PsiUtil.setModifierProperty(setMethod, PsiModifier.PUBLIC, true); PsiUtil.setModifierProperty(setMethod, PsiModifier.STATIC, isStatic); - @NonNls StringBuilder buffer = new StringBuilder(); + StringBuilder buffer = new StringBuilder(); buffer.append("{\n"); if (name.equals(parameterName)) { if (!isStatic) { @@ -623,62 +614,60 @@ public static PsiMethod generateSetterPrototype(@Nonnull PsiField field, @Nonnul } @Nullable - public static PsiTypeElement getPropertyTypeElement(final PsiMember member) { - if (member instanceof PsiField) { - return ((PsiField)member).getTypeElement(); + public static PsiTypeElement getPropertyTypeElement(PsiMember member) { + if (member instanceof PsiField field) { + return field.getTypeElement(); } - if (member instanceof PsiMethod) { - final PsiMethod psiMethod = (PsiMethod)member; - if (isSimplePropertyGetter(psiMethod)) { - return psiMethod.getReturnTypeElement(); + if (member instanceof PsiMethod method) { + if (isSimplePropertyGetter(method)) { + return method.getReturnTypeElement(); } - else if (isSimplePropertySetter(psiMethod)) { - return psiMethod.getParameterList().getParameters()[0].getTypeElement(); + else if (isSimplePropertySetter(method)) { + return method.getParameterList().getParameters()[0].getTypeElement(); } } return null; } @Nullable - public static PsiIdentifier getPropertyNameIdentifier(final PsiMember member) { - if (member instanceof PsiField) { - return ((PsiField)member).getNameIdentifier(); + public static PsiIdentifier getPropertyNameIdentifier(PsiMember member) { + if (member instanceof PsiField field) { + return field.getNameIdentifier(); } - if (member instanceof PsiMethod) { - return ((PsiMethod)member).getNameIdentifier(); + if (member instanceof PsiMethod method) { + return method.getNameIdentifier(); } return null; } @Nullable - public static PsiField findPropertyFieldByMember(final PsiMember psiMember) { - if (psiMember instanceof PsiField) { - return (PsiField)psiMember; + @RequiredReadAction + public static PsiField findPropertyFieldByMember(PsiMember member) { + if (member instanceof PsiField field) { + return field; } - if (psiMember instanceof PsiMethod) { - final PsiMethod psiMethod = (PsiMethod)psiMember; - final PsiType returnType = psiMethod.getReturnType(); + if (member instanceof PsiMethod method) { + PsiType returnType = method.getReturnType(); if (returnType == null) { return null; } - final PsiCodeBlock body = psiMethod.getBody(); - final PsiStatement[] statements = body == null ? null : body.getStatements(); - final PsiStatement statement = statements == null || statements.length != 1 ? null : statements[0]; - final PsiElement target; + PsiCodeBlock body = method.getBody(); + PsiStatement[] statements = body == null ? null : body.getStatements(); + PsiStatement statement = statements == null || statements.length != 1 ? null : statements[0]; + PsiElement target; if (PsiType.VOID.equals(returnType)) { - final PsiExpression expression = - statement instanceof PsiExpressionStatement ? ((PsiExpressionStatement)statement).getExpression() : null; - target = expression instanceof PsiAssignmentExpression ? ((PsiAssignmentExpression)expression).getLExpression() : null; + PsiExpression expression = + statement instanceof PsiExpressionStatement exprStmt ? exprStmt.getExpression() : null; + target = expression instanceof PsiAssignmentExpression assignment ? assignment.getLExpression() : null; } else { - target = statement instanceof PsiReturnStatement ? ((PsiReturnStatement)statement).getReturnValue() : null; + target = statement instanceof PsiReturnStatement returnStmt ? returnStmt.getReturnValue() : null; } - final PsiElement resolved = target instanceof PsiReferenceExpression ? ((PsiReferenceExpression)target).resolve() : null; - if (resolved instanceof PsiField) { - final PsiField field = (PsiField)resolved; - PsiClass memberClass = psiMember.getContainingClass(); + if (target instanceof PsiReferenceExpression refExpr && refExpr.resolve() instanceof PsiField field) { + PsiClass memberClass = member.getContainingClass(); PsiClass fieldClass = field.getContainingClass(); - if (memberClass != null && fieldClass != null && (memberClass == fieldClass || memberClass.isInheritor(fieldClass, true))) { + if (memberClass != null && fieldClass != null + && (memberClass == fieldClass || memberClass.isInheritor(fieldClass, true))) { return field; } } @@ -687,16 +676,16 @@ public static PsiField findPropertyFieldByMember(final PsiMember psiMember) { } public static PsiMethod findSetterForField(PsiField field) { - final PsiClass containingClass = field.getContainingClass(); - final String propertyName = suggestPropertyName(field); - final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); + PsiClass containingClass = field.getContainingClass(); + String propertyName = suggestPropertyName(field); + boolean isStatic = field.isStatic(); return findPropertySetter(containingClass, propertyName, isStatic, true); } public static PsiMethod findGetterForField(PsiField field) { - final PsiClass containingClass = field.getContainingClass(); - final String propertyName = suggestPropertyName(field); - final boolean isStatic = field.hasModifierProperty(PsiModifier.STATIC); + PsiClass containingClass = field.getContainingClass(); + String propertyName = suggestPropertyName(field); + boolean isStatic = field.isStatic(); return findPropertyGetter(containingClass, propertyName, isStatic, true); } @@ -718,13 +707,13 @@ private static boolean hasGetterSignature(@Nonnull PsiMethod method) { @Nullable public static PsiExpression getSingleReturnValue(@Nonnull PsiMethod method) { - final PsiCodeBlock body = method.getBody(); + PsiCodeBlock body = method.getBody(); if (body == null) { return null; } - final PsiStatement[] statements = body.getStatements(); - final PsiStatement statement = statements.length != 1 ? null : statements[0]; - return statement instanceof PsiReturnStatement ? ((PsiReturnStatement)statement).getReturnValue() : null; + PsiStatement[] statements = body.getStatements(); + PsiStatement statement = statements.length != 1 ? null : statements[0]; + return statement instanceof PsiReturnStatement returnStmt? returnStmt.getReturnValue() : null; } @Contract(pure = true) diff --git a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiPrecedenceUtil.java b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiPrecedenceUtil.java index 2b9f4decb..03149008d 100644 --- a/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiPrecedenceUtil.java +++ b/java-language-api/src/main/java/com/intellij/java/language/psi/util/PsiPrecedenceUtil.java @@ -2,8 +2,9 @@ package com.intellij.java.language.psi.util; import com.intellij.java.language.psi.*; -import consulo.language.psi.PsiElement; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.ast.IElementType; +import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; import jakarta.annotation.Nonnull; @@ -32,28 +33,28 @@ public class PsiPrecedenceUtil { public static final int LAMBDA_PRECEDENCE = 17; // jls-15.2 public static final int NUM_PRECEDENCES = 18; - private static final Map s_binaryOperatorPrecedence = new HashMap<>(NUM_PRECEDENCES); + private static final Map S_BINARY_OPERATOR_PRECEDENCE = new HashMap<>(NUM_PRECEDENCES); static { - s_binaryOperatorPrecedence.put(JavaTokenType.PLUS, ADDITIVE_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.MINUS, ADDITIVE_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.ASTERISK, MULTIPLICATIVE_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.DIV, MULTIPLICATIVE_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.PERC, MULTIPLICATIVE_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.ANDAND, AND_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.OROR, OR_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.AND, BINARY_AND_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.OR, BINARY_OR_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.XOR, BINARY_XOR_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.LTLT, SHIFT_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.GTGT, SHIFT_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.GTGTGT, SHIFT_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.GT, RELATIONAL_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.GE, RELATIONAL_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.LT, RELATIONAL_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.LE, RELATIONAL_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.EQEQ, EQUALITY_PRECEDENCE); - s_binaryOperatorPrecedence.put(JavaTokenType.NE, EQUALITY_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.PLUS, ADDITIVE_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.MINUS, ADDITIVE_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.ASTERISK, MULTIPLICATIVE_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.DIV, MULTIPLICATIVE_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.PERC, MULTIPLICATIVE_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.ANDAND, AND_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.OROR, OR_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.AND, BINARY_AND_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.OR, BINARY_OR_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.XOR, BINARY_XOR_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.LTLT, SHIFT_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.GTGT, SHIFT_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.GTGTGT, SHIFT_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.GT, RELATIONAL_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.GE, RELATIONAL_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.LT, RELATIONAL_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.LE, RELATIONAL_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.EQEQ, EQUALITY_PRECEDENCE); + S_BINARY_OPERATOR_PRECEDENCE.put(JavaTokenType.NE, EQUALITY_PRECEDENCE); } public static boolean isCommutativeOperator(@Nonnull IElementType token) { @@ -63,26 +64,26 @@ public static boolean isCommutativeOperator(@Nonnull IElementType token) { } public static boolean isCommutativeOperation(PsiPolyadicExpression expression) { - final IElementType tokenType = expression.getOperationTokenType(); + IElementType tokenType = expression.getOperationTokenType(); if (!isCommutativeOperator(tokenType)) { return false; } - final PsiType type = expression.getType(); - return type != null && !type.equalsToText(CommonClassNames.JAVA_LANG_STRING); + PsiType type = expression.getType(); + return type != null && !type.equalsToText(JavaClassNames.JAVA_LANG_STRING); } public static boolean isAssociativeOperation(PsiPolyadicExpression expression) { - final IElementType tokenType = expression.getOperationTokenType(); - final PsiType type = expression.getType(); - final PsiPrimitiveType primitiveType; + IElementType tokenType = expression.getOperationTokenType(); + PsiType type = expression.getType(); + PsiPrimitiveType primitiveType; if (type instanceof PsiClassType) { primitiveType = PsiPrimitiveType.getUnboxedType(type); if (primitiveType == null) { return false; } } - else if (type instanceof PsiPrimitiveType) { - primitiveType = (PsiPrimitiveType)type; + else if (type instanceof PsiPrimitiveType primitiveType1) { + primitiveType = primitiveType1; } else { return false; @@ -104,17 +105,16 @@ else if (JavaTokenType.OROR == tokenType || JavaTokenType.ANDAND == tokenType) { } public static int getPrecedence(PsiExpression expression) { - if (expression instanceof PsiThisExpression || - expression instanceof PsiLiteralExpression || - expression instanceof PsiSuperExpression || - expression instanceof PsiClassObjectAccessExpression || - expression instanceof PsiArrayAccessExpression || - expression instanceof PsiArrayInitializerExpression) { + if (expression instanceof PsiThisExpression + || expression instanceof PsiLiteralExpression + || expression instanceof PsiSuperExpression + || expression instanceof PsiClassObjectAccessExpression + || expression instanceof PsiArrayAccessExpression + || expression instanceof PsiArrayInitializerExpression) { return LITERAL_PRECEDENCE; } - if (expression instanceof PsiReferenceExpression) { - final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)expression; - if (referenceExpression.getQualifier() != null) { + if (expression instanceof PsiReferenceExpression refExpr) { + if (refExpr.getQualifier() != null) { return METHOD_CALL_PRECEDENCE; } else { @@ -133,8 +133,7 @@ public static int getPrecedence(PsiExpression expression) { if (expression instanceof PsiPostfixExpression || expression instanceof PsiSwitchExpression) { return POSTFIX_PRECEDENCE; } - if (expression instanceof PsiPolyadicExpression) { - final PsiPolyadicExpression polyadicExpression = (PsiPolyadicExpression)expression; + if (expression instanceof PsiPolyadicExpression polyadicExpression) { return getPrecedenceForOperator(polyadicExpression.getOperationTokenType()); } if (expression instanceof PsiInstanceOfExpression) { @@ -156,19 +155,19 @@ public static int getPrecedence(PsiExpression expression) { } public static int getPrecedenceForOperator(@Nonnull IElementType operator) { - final Integer precedence = s_binaryOperatorPrecedence.get(operator); + Integer precedence = S_BINARY_OPERATOR_PRECEDENCE.get(operator); if (precedence == null) { throw new IllegalArgumentException("unknown operator: " + operator); } - return precedence.intValue(); + return precedence; } public static boolean areParenthesesNeeded(PsiParenthesizedExpression expression, boolean ignoreClarifyingParentheses) { - final PsiElement parent = expression.getParent(); + PsiElement parent = expression.getParent(); if (!(parent instanceof PsiExpression)) { return false; } - final PsiExpression child = expression.getExpression(); + PsiExpression child = expression.getExpression(); return child == null || areParenthesesNeeded(child, (PsiExpression)parent, ignoreClarifyingParentheses); } @@ -180,12 +179,11 @@ public static boolean areParenthesesNeeded( if (parentExpression instanceof PsiParenthesizedExpression || parentExpression instanceof PsiArrayInitializerExpression) { return false; } - if (parentExpression instanceof PsiArrayAccessExpression) { - final PsiArrayAccessExpression arrayAccessExpression = (PsiArrayAccessExpression)parentExpression; - return PsiTreeUtil.isAncestor(arrayAccessExpression.getArrayExpression(), expression, false); + if (parentExpression instanceof PsiArrayAccessExpression arrayAccess) { + return PsiTreeUtil.isAncestor(arrayAccess.getArrayExpression(), expression, false); } - final int parentPrecedence = getPrecedence(parentExpression); - final int childPrecedence = getPrecedence(expression); + int parentPrecedence = getPrecedence(parentExpression); + int childPrecedence = getPrecedence(expression); if (parentPrecedence > childPrecedence) { if (ignoreClarifyingParentheses) { if (expression instanceof PsiPolyadicExpression) { @@ -201,20 +199,18 @@ else if (expression instanceof PsiInstanceOfExpression) { } return false; } - if (parentExpression instanceof PsiPolyadicExpression && expression instanceof PsiPolyadicExpression) { - final PsiPolyadicExpression parentPolyadicExpression = (PsiPolyadicExpression)parentExpression; - final PsiType parentType = parentPolyadicExpression.getType(); + if (parentExpression instanceof PsiPolyadicExpression parentPolyadic && expression instanceof PsiPolyadicExpression childPolyadic) { + PsiType parentType = parentPolyadic.getType(); if (parentType == null) { return true; } - final PsiPolyadicExpression childPolyadicExpression = (PsiPolyadicExpression)expression; - final PsiType childType = childPolyadicExpression.getType(); + PsiType childType = childPolyadic.getType(); if (!parentType.equals(childType)) { return true; } - if (childType.equalsToText(CommonClassNames.JAVA_LANG_STRING) && - !PsiTreeUtil.isAncestor(parentPolyadicExpression.getOperands()[0], childPolyadicExpression, true)) { - final PsiExpression[] operands = childPolyadicExpression.getOperands(); + if (childType.equalsToText(JavaClassNames.JAVA_LANG_STRING) + && !PsiTreeUtil.isAncestor(parentPolyadic.getOperands()[0], childPolyadic, true)) { + PsiExpression[] operands = childPolyadic.getOperands(); for (PsiExpression operand : operands) { if (!childType.equals(operand.getType())) { return true; @@ -222,52 +218,49 @@ else if (expression instanceof PsiInstanceOfExpression) { } } else if (childType.equals(PsiType.BOOLEAN)) { - final PsiExpression[] operands = childPolyadicExpression.getOperands(); + PsiExpression[] operands = childPolyadic.getOperands(); for (PsiExpression operand : operands) { if (!PsiType.BOOLEAN.equals(operand.getType())) { return true; } } } - final IElementType parentOperator = parentPolyadicExpression.getOperationTokenType(); - final IElementType childOperator = childPolyadicExpression.getOperationTokenType(); + IElementType parentOperator = parentPolyadic.getOperationTokenType(); + IElementType childOperator = childPolyadic.getOperationTokenType(); if (ignoreClarifyingParentheses) { if (!childOperator.equals(parentOperator)) { return true; } } - final PsiExpression[] parentOperands = parentPolyadicExpression.getOperands(); + PsiExpression[] parentOperands = parentPolyadic.getOperands(); if (!PsiTreeUtil.isAncestor(parentOperands[0], expression, false)) { - if (!isAssociativeOperation(parentPolyadicExpression) || + if (!isAssociativeOperation(parentPolyadic) || JavaTokenType.DIV == childOperator || JavaTokenType.PERC == childOperator) { return true; } } } - else if (parentExpression instanceof PsiConditionalExpression && expression instanceof PsiConditionalExpression) { - final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression; - final PsiExpression condition = conditionalExpression.getCondition(); + else if (parentExpression instanceof PsiConditionalExpression parentConditional && expression instanceof PsiConditionalExpression) { + PsiExpression condition = parentConditional.getCondition(); return PsiTreeUtil.isAncestor(condition, expression, true); } else if (expression instanceof PsiLambdaExpression) { // jls-15.16 if (parentExpression instanceof PsiTypeCastExpression) { return false; } - else if (parentExpression instanceof PsiConditionalExpression) { // jls-15.25 - final PsiConditionalExpression conditionalExpression = (PsiConditionalExpression)parentExpression; - return PsiTreeUtil.isAncestor(conditionalExpression.getCondition(), expression, true); + else if (parentExpression instanceof PsiConditionalExpression conditional) { // jls-15.25 + return PsiTreeUtil.isAncestor(conditional.getCondition(), expression, true); } } return parentPrecedence < childPrecedence; } public static boolean areParenthesesNeeded(PsiJavaToken compoundAssignmentToken, PsiExpression rhs) { - if (rhs instanceof PsiPolyadicExpression) { - final PsiPolyadicExpression binaryExpression = (PsiPolyadicExpression)rhs; - final int precedence1 = getPrecedenceForOperator(binaryExpression.getOperationTokenType()); - final IElementType signTokenType = compoundAssignmentToken.getTokenType(); - final IElementType newOperatorToken = TypeConversionUtil.convertEQtoOperation(signTokenType); - final int precedence2 = getPrecedenceForOperator(newOperatorToken); + if (rhs instanceof PsiPolyadicExpression binaryExpression) { + int precedence1 = getPrecedenceForOperator(binaryExpression.getOperationTokenType()); + IElementType signTokenType = compoundAssignmentToken.getTokenType(); + IElementType newOperatorToken = TypeConversionUtil.convertEQtoOperation(signTokenType); + int precedence2 = getPrecedenceForOperator(newOperatorToken); return precedence1 >= precedence2 || !isCommutativeOperator(newOperatorToken); } else { diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/controlFlow/ControlFlowAnalyzer.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/controlFlow/ControlFlowAnalyzer.java index 1cbc56ad5..9f86650ff 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/controlFlow/ControlFlowAnalyzer.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/controlFlow/ControlFlowAnalyzer.java @@ -6,7 +6,9 @@ import com.intellij.java.language.impl.psi.util.JavaPsiRecordUtil; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.progress.ProgressManager; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.ast.IElementType; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiErrorElement; @@ -19,7 +21,6 @@ import consulo.util.collection.primitive.ints.IntLists; import consulo.util.lang.Comparing; import consulo.util.lang.ObjectUtil; - import jakarta.annotation.Nonnull; import jakarta.annotation.Nullable; @@ -235,11 +236,12 @@ private ControlFlow cleanup() { return result; } + @RequiredReadAction private void startElement(@Nonnull PsiElement element) { for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { ProgressManager.checkCanceled(); - if (child instanceof PsiErrorElement - && !Comparing.strEqual(((PsiErrorElement)child).getErrorDescription(), JavaPsiBundle.message("expected.semicolon"))) { + if (child instanceof PsiErrorElement errorElem + && !Comparing.strEqual(errorElem.getErrorDescription(), JavaPsiBundle.message("expected.semicolon"))) { // do not perform control flow analysis for incomplete code throw new AnalysisCanceledSoftException(element); } @@ -250,18 +252,19 @@ private void startElement(@Nonnull PsiElement element) { generateUncheckedExceptionJumpsIfNeeded(element, true); } + @RequiredReadAction private void generateUncheckedExceptionJumpsIfNeeded(@Nonnull PsiElement element, boolean atStart) { if (!myOptions.isExceptionAfterAssignment() && !atStart) { if (element instanceof PsiExpression) { - PsiElement parent = PsiUtil.skipParenthesizedExprUp(element.getParent()); - if (parent instanceof PsiAssignmentExpression && parent.getParent() instanceof PsiExpressionStatement) { + if (PsiUtil.skipParenthesizedExprUp(element.getParent()) instanceof PsiAssignmentExpression assignment + && assignment.getParent() instanceof PsiExpressionStatement) { generateUncheckedExceptionJumps(element, false); return; } } - if (element instanceof PsiCodeBlock || - element instanceof PsiExpressionStatement && - ((PsiExpressionStatement)element).getExpression() instanceof PsiAssignmentExpression) { + if (element instanceof PsiCodeBlock + || element instanceof PsiExpressionStatement expressionStmt + && expressionStmt.getExpression() instanceof PsiAssignmentExpression) { return; } } @@ -273,6 +276,7 @@ private void generateUncheckedExceptionJumpsIfNeeded(@Nonnull PsiElement element } } + @RequiredReadAction private void finishElement(@Nonnull PsiElement element) { generateUncheckedExceptionJumpsIfNeeded(element, false); @@ -280,7 +284,7 @@ private void finishElement(@Nonnull PsiElement element) { patchInstructionOffsets(element); } - + @RequiredReadAction private void generateUncheckedExceptionJumps(@Nonnull PsiElement element, boolean atStart) { // optimization: if we just generated all necessary jumps, do not generate it once again if (atStart @@ -310,7 +314,7 @@ private void generateUncheckedExceptionJumps(@Nonnull PsiElement element, boolea // generate a jump to the top 'finally' block if (!myFinallyBlocks.isEmpty()) { - final PsiElement finallyBlock = myFinallyBlocks.peek().getElement(); + PsiElement finallyBlock = myFinallyBlocks.peek().getElement(); ConditionalThrowToInstruction throwToInstruction = new ConditionalThrowToInstruction(-2); myCurrentFlow.addInstruction(throwToInstruction); if (!patchUncheckedThrowInstructionIfInsideFinally(throwToInstruction, element, finallyBlock)) { @@ -319,6 +323,7 @@ private void generateUncheckedExceptionJumps(@Nonnull PsiElement element, boolea } } + @RequiredReadAction private void generateCheckedExceptionJumps(@Nonnull PsiElement element) { //generate jumps to all handled exception handlers generateExceptionJumps(element, ExceptionUtil.collectUnhandledExceptions(element, element.getParent())); @@ -332,7 +337,7 @@ private void generateExceptionJumps(@Nonnull PsiElement element, Collection catchBlocks = findThrowToBlocks(unhandledException); + List catchBlocks = findThrowToBlocks(unhandledException); for (PsiElement block : catchBlocks) { ProgressManager.checkCanceled(); ConditionalThrowToInstruction instruction = new ConditionalThrowToInstruction(0); @@ -356,7 +361,7 @@ private boolean patchCheckedThrowInstructionIfInsideFinally( @Nonnull PsiElement throwingElement, PsiElement elementToJumpTo ) { - final PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); + PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); if (finallyBlock == null) { return false; } @@ -380,7 +385,7 @@ private boolean patchUncheckedThrowInstructionIfInsideFinally( @Nonnull PsiElement throwingElement, @Nonnull PsiElement elementToJumpTo ) { - final PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); + PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); if (finallyBlock == null) { return false; } @@ -393,7 +398,8 @@ private boolean patchUncheckedThrowInstructionIfInsideFinally( } @Override - public void visitCodeFragment(JavaCodeFragment codeFragment) { + @RequiredReadAction + public void visitCodeFragment(@Nonnull JavaCodeFragment codeFragment) { startElement(codeFragment); int prevOffset = myCurrentFlow.getSize(); PsiElement[] children = codeFragment.getChildren(); @@ -406,12 +412,13 @@ public void visitCodeFragment(JavaCodeFragment codeFragment) { registerSubRange(codeFragment, prevOffset); } - private void registerSubRange(@Nonnull PsiElement codeFragment, final int startOffset) { + private void registerSubRange(@Nonnull PsiElement codeFragment, int startOffset) { mySubRanges.add(new SubRangeInfo(codeFragment, startOffset, myCurrentFlow.getSize())); } @Override - public void visitCodeBlock(PsiCodeBlock block) { + @RequiredReadAction + public void visitCodeBlock(@Nonnull PsiCodeBlock block) { startElement(block); int prevOffset = myCurrentFlow.getSize(); PsiStatement[] statements = block.getStatements(); @@ -440,28 +447,33 @@ private void emitEmptyInstruction() { } @Override + @RequiredReadAction public void visitFile(@Nonnull PsiFile file) { visitChildren(file); } @Override - public void visitBlockStatement(PsiBlockStatement statement) { + @RequiredReadAction + public void visitBlockStatement(@Nonnull PsiBlockStatement statement) { startElement(statement); - final PsiCodeBlock codeBlock = statement.getCodeBlock(); + PsiCodeBlock codeBlock = statement.getCodeBlock(); codeBlock.accept(this); finishElement(statement); } @Override - public void visitBreakStatement(PsiBreakStatement statement) { + @RequiredReadAction + public void visitBreakStatement(@Nonnull PsiBreakStatement statement) { generateYieldInstructions(statement, null, statement.findExitedStatement()); } @Override - public void visitYieldStatement(PsiYieldStatement statement) { + @RequiredReadAction + public void visitYieldStatement(@Nonnull PsiYieldStatement statement) { generateYieldInstructions(statement, statement.getExpression(), statement.findEnclosingExpression()); } + @RequiredReadAction private void generateYieldInstructions(PsiStatement statement, PsiExpression valueExpression, PsiElement exitedStatement) { startElement(statement); generateExpressionInstructions(valueExpression); @@ -469,9 +481,9 @@ private void generateYieldInstructions(PsiStatement statement, PsiExpression val if (exitedStatement != null) { callFinallyBlocksOnExit(exitedStatement); - final Instruction instruction; - final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, exitedStatement); - final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); + Instruction instruction; + PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, exitedStatement); + int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, use return CallInstruction callInstruction = (CallInstruction)myCurrentFlow.getInstructions().get(finallyStartOffset - 2); @@ -489,10 +501,10 @@ private void generateYieldInstructions(PsiStatement statement, PsiExpression val } private void callFinallyBlocksOnExit(PsiElement exitedStatement) { - for (final ListIterator it = myFinallyBlocks.listIterator(myFinallyBlocks.size()); it.hasPrevious(); ) { - final FinallyBlockSubroutine finallyBlockSubroutine = it.previous(); + for (ListIterator it = myFinallyBlocks.listIterator(myFinallyBlocks.size()); it.hasPrevious(); ) { + FinallyBlockSubroutine finallyBlockSubroutine = it.previous(); PsiElement finallyBlock = finallyBlockSubroutine.getElement(); - final PsiElement enclosingTryStatement = finallyBlock.getParent(); + PsiElement enclosingTryStatement = finallyBlock.getParent(); if (enclosingTryStatement == null || !PsiTreeUtil.isAncestor(exitedStatement, enclosingTryStatement, false)) { break; } @@ -523,7 +535,8 @@ private PsiElement findEnclosingFinallyBlockElement(@Nonnull PsiElement sourceEl } @Override - public void visitContinueStatement(PsiContinueStatement statement) { + @RequiredReadAction + public void visitContinueStatement(@Nonnull PsiContinueStatement statement) { startElement(statement); PsiStatement continuedStatement = statement.findContinuedStatement(); if (continuedStatement != null) { @@ -536,9 +549,9 @@ public void visitContinueStatement(PsiContinueStatement statement) { } callFinallyBlocksOnExit(continuedStatement); - final Instruction instruction; - final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, continuedStatement); - final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); + Instruction instruction; + PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, continuedStatement); + int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, use return CallInstruction callInstruction = (CallInstruction)myCurrentFlow.getInstructions().get(finallyStartOffset - 2); @@ -554,7 +567,8 @@ public void visitContinueStatement(PsiContinueStatement statement) { } @Override - public void visitDeclarationStatement(PsiDeclarationStatement statement) { + @RequiredReadAction + public void visitDeclarationStatement(@Nonnull PsiDeclarationStatement statement) { startElement(statement); int pc = myCurrentFlow.getSize(); PsiElement[] elements = statement.getDeclaredElements(); @@ -574,8 +588,9 @@ else if (element instanceof PsiVariable) { finishElement(statement); } + @RequiredReadAction private void processVariable(@Nonnull PsiVariable element) { - final PsiExpression initializer = element.getInitializer(); + PsiExpression initializer = element.getInitializer(); generateExpressionInstructions(initializer); if (element instanceof PsiLocalVariable && initializer != null || @@ -597,7 +612,8 @@ private void processVariable(@Nonnull PsiVariable element) { } @Override - public void visitDoWhileStatement(PsiDoWhileStatement statement) { + @RequiredReadAction + public void visitDoWhileStatement(@Nonnull PsiDoWhileStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, true); @@ -615,8 +631,8 @@ public void visitDoWhileStatement(PsiDoWhileStatement statement) { int offset = myCurrentFlow.getStartOffset(statement); Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(statement.getCondition()); - if (loopCondition instanceof Boolean) { - if (((Boolean)loopCondition).booleanValue()) { + if (loopCondition instanceof Boolean value) { + if (value) { myCurrentFlow.addInstruction(new GoToInstruction(offset)); } else { @@ -634,7 +650,8 @@ public void visitDoWhileStatement(PsiDoWhileStatement statement) { } @Override - public void visitEmptyStatement(PsiEmptyStatement statement) { + @RequiredReadAction + public void visitEmptyStatement(@Nonnull PsiEmptyStatement statement) { startElement(statement); emitEmptyInstruction(); @@ -642,9 +659,10 @@ public void visitEmptyStatement(PsiEmptyStatement statement) { } @Override - public void visitExpressionStatement(PsiExpressionStatement statement) { + @RequiredReadAction + public void visitExpressionStatement(@Nonnull PsiExpressionStatement statement) { startElement(statement); - final PsiExpression expression = statement.getExpression(); + PsiExpression expression = statement.getExpression(); expression.accept(this); for (PsiParameter catchParameter : myCatchParameters) { @@ -665,7 +683,8 @@ public void visitExpressionStatement(PsiExpressionStatement statement) { } @Override - public void visitExpressionListStatement(PsiExpressionListStatement statement) { + @RequiredReadAction + public void visitExpressionListStatement(@Nonnull PsiExpressionListStatement statement) { startElement(statement); PsiExpression[] expressions = statement.getExpressionList().getExpressions(); for (PsiExpression expr : expressions) { @@ -676,8 +695,9 @@ public void visitExpressionListStatement(PsiExpressionListStatement statement) { } @Override + @RequiredReadAction public void visitField(PsiField field) { - final PsiExpression initializer = field.getInitializer(); + PsiExpression initializer = field.getInitializer(); if (initializer != null) { startElement(field); initializer.accept(this); @@ -686,7 +706,8 @@ public void visitField(PsiField field) { } @Override - public void visitForStatement(PsiForStatement statement) { + @RequiredReadAction + public void visitForStatement(@Nonnull PsiForStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, false); @@ -702,10 +723,9 @@ public void visitForStatement(PsiForStatement statement) { condition.accept(this); } - Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(condition); if (loopCondition instanceof Boolean || condition == null) { - boolean value = condition == null || ((Boolean)loopCondition).booleanValue(); + boolean value = condition == null || (Boolean)loopCondition; if (value) { emitEmptyInstruction(); } @@ -741,22 +761,23 @@ public void visitForStatement(PsiForStatement statement) { } @Override - public void visitForeachStatement(PsiForeachStatement statement) { + @RequiredReadAction + public void visitForeachStatement(@Nonnull PsiForeachStatement statement) { startElement(statement); - final PsiStatement body = statement.getBody(); + PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, false); myEndStatementStack.pushStatement(statement, false); - final PsiExpression iteratedValue = statement.getIteratedValue(); + PsiExpression iteratedValue = statement.getIteratedValue(); if (iteratedValue != null) { iteratedValue.accept(this); } - final int gotoTarget = myCurrentFlow.getSize(); + int gotoTarget = myCurrentFlow.getSize(); Instruction instruction = new ConditionalGoToInstruction(0, statement.getIteratedValue()); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(statement, false); - final PsiParameter iterationParameter = statement.getIterationParameter(); + PsiParameter iterationParameter = statement.getIterationParameter(); if (myPolicy.isParameterAccepted(iterationParameter)) { generateWriteInstruction(iterationParameter); } @@ -764,7 +785,7 @@ public void visitForeachStatement(PsiForeachStatement statement) { body.accept(this); } - final GoToInstruction gotoInstruction = new GoToInstruction(gotoTarget); + GoToInstruction gotoInstruction = new GoToInstruction(gotoTarget); myCurrentFlow.addInstruction(gotoInstruction); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); @@ -772,11 +793,12 @@ public void visitForeachStatement(PsiForeachStatement statement) { } @Override - public void visitIfStatement(PsiIfStatement statement) { + @RequiredReadAction + public void visitIfStatement(@Nonnull PsiIfStatement statement) { startElement(statement); - final PsiStatement elseBranch = statement.getElseBranch(); - final PsiStatement thenBranch = statement.getThenBranch(); + PsiStatement elseBranch = statement.getElseBranch(); + PsiStatement thenBranch = statement.getThenBranch(); PsiExpression conditionExpression = statement.getCondition(); generateConditionalStatementInstructions(statement, conditionExpression, thenBranch, elseBranch); @@ -787,8 +809,8 @@ public void visitIfStatement(PsiIfStatement statement) { private void generateConditionalStatementInstructions( @Nonnull PsiElement statement, @Nullable PsiExpression conditionExpression, - final PsiElement thenBranch, - final PsiElement elseBranch + PsiElement thenBranch, + PsiElement elseBranch ) { if (thenBranch == null) { myStartStatementStack.pushStatement(statement, false); @@ -824,17 +846,17 @@ private void generateConditionalStatementInstructions( * :end */ if (myOptions.shouldEvaluateConstantIfCondition()) { - final Object value = myConstantEvaluationHelper.computeConstantExpression(conditionExpression); - if (value instanceof Boolean) { - thenReachable = ((Boolean)value).booleanValue(); + if (myConstantEvaluationHelper.computeConstantExpression(conditionExpression) instanceof Boolean value) { + thenReachable = value; generateConditionalJump = false; myCurrentFlow.setConstantConditionOccurred(true); } } if (generateConditionalJump || !thenReachable) { BranchingInstruction.Role role = elseBranch == null ? BranchingInstruction.Role.END : BranchingInstruction.Role.ELSE; - Instruction instruction = generateConditionalJump ? new ConditionalGoToInstruction(0, role, conditionExpression) : - new GoToInstruction(0, role); + Instruction instruction = generateConditionalJump + ? new ConditionalGoToInstruction(0, role, conditionExpression) + : new GoToInstruction(0, role); myCurrentFlow.addInstruction(instruction); if (elseBranch == null) { addElementOffsetLater(statement, false); @@ -861,9 +883,10 @@ private void generateConditionalStatementInstructions( } @Override - public void visitLabeledStatement(PsiLabeledStatement statement) { + @RequiredReadAction + public void visitLabeledStatement(@Nonnull PsiLabeledStatement statement) { startElement(statement); - final PsiStatement innerStatement = statement.getStatement(); + PsiStatement innerStatement = statement.getStatement(); if (innerStatement != null) { innerStatement.accept(this); } @@ -871,7 +894,8 @@ public void visitLabeledStatement(PsiLabeledStatement statement) { } @Override - public void visitReturnStatement(PsiReturnStatement statement) { + @RequiredReadAction + public void visitReturnStatement(@Nonnull PsiReturnStatement statement) { startElement(statement); PsiExpression returnValue = statement.getReturnValue(); @@ -891,8 +915,8 @@ public void visitReturnStatement(PsiReturnStatement statement) { private void addReturnInstruction(@Nonnull PsiElement statement) { BranchingInstruction instruction; - final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, null); - final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); + PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, null); + int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, go to 2nd return after finally block // second return is for return statement called completion @@ -914,14 +938,16 @@ private void addReturnInstruction(@Nonnull PsiElement statement) { } @Override - public void visitSwitchLabelStatement(PsiSwitchLabelStatement statement) { + @RequiredReadAction + public void visitSwitchLabelStatement(@Nonnull PsiSwitchLabelStatement statement) { startElement(statement); generateCaseValueInstructions(statement.getCaseValues()); finishElement(statement); } @Override - public void visitSwitchLabeledRuleStatement(PsiSwitchLabeledRuleStatement statement) { + @RequiredReadAction + public void visitSwitchLabeledRuleStatement(@Nonnull PsiSwitchLabeledRuleStatement statement) { startElement(statement); generateCaseValueInstructions(statement.getCaseValues()); @@ -952,15 +978,18 @@ private void generateCaseValueInstructions(@Nullable PsiExpressionList values) { } @Override - public void visitSwitchStatement(PsiSwitchStatement statement) { + @RequiredReadAction + public void visitSwitchStatement(@Nonnull PsiSwitchStatement statement) { generateSwitchBlockInstructions(statement); } @Override - public void visitSwitchExpression(PsiSwitchExpression expression) { + @RequiredReadAction + public void visitSwitchExpression(@Nonnull PsiSwitchExpression expression) { generateSwitchBlockInstructions(expression); } + @RequiredReadAction public void generateSwitchBlockInstructions(PsiSwitchBlock statement) { startElement(statement); @@ -997,7 +1026,8 @@ public void generateSwitchBlockInstructions(PsiSwitchBlock statement) { } @Override - public void visitSynchronizedStatement(PsiSynchronizedStatement statement) { + @RequiredReadAction + public void visitSynchronizedStatement(@Nonnull PsiSynchronizedStatement statement) { startElement(statement); PsiExpression lock = statement.getLockExpression(); @@ -1014,14 +1044,15 @@ public void visitSynchronizedStatement(PsiSynchronizedStatement statement) { } @Override - public void visitThrowStatement(PsiThrowStatement statement) { + @RequiredReadAction + public void visitThrowStatement(@Nonnull PsiThrowStatement statement) { startElement(statement); PsiExpression exception = statement.getException(); if (exception != null) { exception.accept(this); } - final List blocks = findThrowToBlocks(statement); + List blocks = findThrowToBlocks(statement); addThrowInstructions(blocks); finishElement(statement); @@ -1064,15 +1095,14 @@ private void addThrowInstructions(@Nonnull List blocks) { */ @Nonnull private List findThrowToBlocks(@Nonnull PsiThrowStatement statement) { - final PsiExpression exceptionExpr = statement.getException(); + PsiExpression exceptionExpr = statement.getException(); if (exceptionExpr == null) { return Collections.emptyList(); } - final PsiType throwType = exceptionExpr.getType(); - if (!(throwType instanceof PsiClassType)) { + if (!(exceptionExpr.getType() instanceof PsiClassType throwClassType)) { return Collections.emptyList(); } - return findThrowToBlocks((PsiClassType)throwType); + return findThrowToBlocks(throwClassType); } @Nonnull @@ -1094,7 +1124,8 @@ private List findThrowToBlocks(@Nonnull PsiClassType throwType) { } @Override - public void visitAssertStatement(PsiAssertStatement statement) { + @RequiredReadAction + public void visitAssertStatement(@Nonnull PsiAssertStatement statement) { startElement(statement); myStartStatementStack.pushStatement(statement, false); @@ -1103,13 +1134,12 @@ public void visitAssertStatement(PsiAssertStatement statement) { myCurrentFlow.addInstruction(passByWhenAssertionsDisabled); addElementOffsetLater(statement, false); - final PsiExpression condition = statement.getAssertCondition(); + PsiExpression condition = statement.getAssertCondition(); boolean generateCondition = true; boolean throwReachable = true; if (myOptions.shouldEvaluateConstantIfCondition()) { - Object conditionValue = myConstantEvaluationHelper.computeConstantExpression(condition); - if (conditionValue instanceof Boolean) { - throwReachable = !((Boolean)conditionValue); + if (myConstantEvaluationHelper.computeConstantExpression(condition) instanceof Boolean conditionValue) { + throwReachable = !conditionValue; generateCondition = false; emitEmptyInstruction(); } @@ -1145,8 +1175,8 @@ else if (!throwReachable) { } // if description is evaluated, the 'assert' statement cannot complete normally // though non-necessarily AssertionError will be thrown (description may throw something, or AssertionError ctor, etc.) - PsiClassType exceptionClass = JavaPsiFacade.getElementFactory(statement.getProject()).createTypeByFQClassName( - CommonClassNames.JAVA_LANG_THROWABLE, statement.getResolveScope()); + PsiClassType exceptionClass = JavaPsiFacade.getElementFactory(statement.getProject()) + .createTypeByFQClassName(JavaClassNames.JAVA_LANG_THROWABLE, statement.getResolveScope()); addThrowInstructions(findThrowToBlocks(exceptionClass)); myStartStatementStack.popStatement(); @@ -1156,7 +1186,8 @@ else if (!throwReachable) { } @Override - public void visitTryStatement(PsiTryStatement statement) { + @RequiredReadAction + public void visitTryStatement(@Nonnull PsiTryStatement statement) { startElement(statement); PsiCodeBlock[] catchBlocks = statement.getCatchBlocks(); @@ -1168,19 +1199,20 @@ public void visitTryStatement(PsiTryStatement statement) { myCatchParameters.push(catchBlockParameters[i]); myCatchBlocks.push(catchBlocks[i]); - final PsiType type = catchBlockParameters[i].getType(); + PsiType type = catchBlockParameters[i].getType(); // todo cast param - if (type instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)type)) { + if (type instanceof PsiClassType classType && ExceptionUtil.isUncheckedExceptionOrSuperclass(classType)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); } - else if (type instanceof PsiDisjunctionType) { - final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound(); - if (lub instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)lub)) { + else if (type instanceof PsiDisjunctionType disjunctionType) { + PsiType lub = disjunctionType.getLeastUpperBound(); + if (lub instanceof PsiClassType lubClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass(lubClassType)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); } - else if (lub instanceof PsiIntersectionType) { - for (PsiType conjunct : ((PsiIntersectionType)lub).getConjuncts()) { - if (conjunct instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)conjunct)) { + else if (lub instanceof PsiIntersectionType intersectionType) { + for (PsiType conjunct : intersectionType.getConjuncts()) { + if (conjunct instanceof PsiClassType conjunctClassType + && ExceptionUtil.isUncheckedExceptionOrSuperclass(conjunctClassType)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); break; } @@ -1211,7 +1243,6 @@ else if (lub instanceof PsiIntersectionType) { //noinspection StatementWithEmptyBody while (myUnhandledExceptionCatchBlocks.pop() != null) { - ; } myCurrentFlow.addInstruction(new GoToInstruction(finallyBlock == null ? 0 : -6)); @@ -1272,13 +1303,13 @@ else if (lub instanceof PsiIntersectionType) { finallyBlockSubroutine.addCall(throwExceptionCompletion); myCurrentFlow.addInstruction(throwExceptionCompletion); addElementOffsetLater(finallyBlock, true); - final GoToInstruction gotoUncheckedRethrow = new GoToInstruction(0); + GoToInstruction gotoUncheckedRethrow = new GoToInstruction(0); myCurrentFlow.addInstruction(gotoUncheckedRethrow); addElementOffsetLater(finallyBlock, false); finallyBlock.accept(this); - final int procStart = myCurrentFlow.getStartOffset(finallyBlock); - final int procEnd = myCurrentFlow.getEndOffset(finallyBlock); + int procStart = myCurrentFlow.getStartOffset(finallyBlock); + int procEnd = myCurrentFlow.getEndOffset(finallyBlock); for (CallInstruction callInstruction : finallyBlockSubroutine.getCalls()) { callInstruction.procBegin = procStart; callInstruction.procEnd = procEnd; @@ -1297,12 +1328,12 @@ else if (lub instanceof PsiIntersectionType) { myCurrentFlow.addInstruction(new ReturnInstruction(procStart - 1, throwExceptionCompletion)); // checked exception throwing completion; need to dispatch to the correct catch clause - final List unhandledExceptionCatchBlocks = finallyBlockToUnhandledExceptions.remove(finallyBlock); + List unhandledExceptionCatchBlocks = finallyBlockToUnhandledExceptions.remove(finallyBlock); for (int i = 0; unhandledExceptionCatchBlocks != null && i < unhandledExceptionCatchBlocks.size(); i++) { ProgressManager.checkCanceled(); PsiElement catchBlock = unhandledExceptionCatchBlocks.get(i); - final ReturnInstruction returnInstruction = new ReturnInstruction(0, throwExceptionCompletion); + ReturnInstruction returnInstruction = new ReturnInstruction(0, throwExceptionCompletion); returnInstruction.setRethrowFromFinally(); myCurrentFlow.addInstruction(returnInstruction); if (catchBlock == null) { @@ -1328,16 +1359,17 @@ else if (lub instanceof PsiIntersectionType) { } @Override - public void visitResourceList(final PsiResourceList resourceList) { + @RequiredReadAction + public void visitResourceList(@Nonnull PsiResourceList resourceList) { startElement(resourceList); for (PsiResourceListElement resource : resourceList) { ProgressManager.checkCanceled(); - if (resource instanceof PsiResourceVariable) { - processVariable((PsiVariable)resource); + if (resource instanceof PsiResourceVariable resourceVar) { + processVariable(resourceVar); } - else if (resource instanceof PsiResourceExpression) { - ((PsiResourceExpression)resource).getExpression().accept(this); + else if (resource instanceof PsiResourceExpression psiResourceExpr) { + psiResourceExpr.getExpression().accept(this); } } @@ -1345,7 +1377,8 @@ else if (resource instanceof PsiResourceExpression) { } @Override - public void visitWhileStatement(PsiWhileStatement statement) { + @RequiredReadAction + public void visitWhileStatement(@Nonnull PsiWhileStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); if (body == null) { @@ -1363,8 +1396,7 @@ public void visitWhileStatement(PsiWhileStatement statement) { Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(statement.getCondition()); - if (loopCondition instanceof Boolean) { - boolean value = ((Boolean)loopCondition).booleanValue(); + if (loopCondition instanceof Boolean value) { if (value) { emitEmptyInstruction(); } @@ -1394,7 +1426,7 @@ public void visitWhileStatement(PsiWhileStatement statement) { @Override public void visitExpressionList(PsiExpressionList list) { PsiExpression[] expressions = list.getExpressions(); - for (final PsiExpression expression : expressions) { + for (PsiExpression expression : expressions) { ProgressManager.checkCanceled(); generateExpressionInstructions(expression); } @@ -1413,11 +1445,12 @@ private void generateExpressionInstructions(@Nullable PsiExpression expression) } @Override - public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { + @RequiredReadAction + public void visitArrayAccessExpression(@Nonnull PsiArrayAccessExpression expression) { startElement(expression); expression.getArrayExpression().accept(this); - final PsiExpression indexExpression = expression.getIndexExpression(); + PsiExpression indexExpression = expression.getIndexExpression(); if (indexExpression != null) { indexExpression.accept(this); } @@ -1426,7 +1459,8 @@ public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { } @Override - public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { + @RequiredReadAction + public void visitArrayInitializerExpression(@Nonnull PsiArrayInitializerExpression expression) { startElement(expression); PsiExpression[] initializers = expression.getInitializers(); @@ -1439,7 +1473,8 @@ public void visitArrayInitializerExpression(PsiArrayInitializerExpression expres } @Override - public void visitAssignmentExpression(PsiAssignmentExpression expression) { + @RequiredReadAction + public void visitAssignmentExpression(@Nonnull PsiAssignmentExpression expression) { startElement(expression); PsiExpression rExpr = expression.getRExpression(); @@ -1448,12 +1483,9 @@ public void visitAssignmentExpression(PsiAssignmentExpression expression) { boolean generatedWriteInstruction = false; PsiExpression lExpr = PsiUtil.skipParenthesizedExprDown(expression.getLExpression()); - if (lExpr instanceof PsiReferenceExpression) { - if (!myImplicitCompactConstructorAssignments.isEmpty()) { - PsiElement target = ((PsiReferenceExpression)lExpr).resolve(); - if (target instanceof PsiField) { - myImplicitCompactConstructorAssignments.remove(target); - } + if (lExpr instanceof PsiReferenceExpression lRefExpr) { + if (!myImplicitCompactConstructorAssignments.isEmpty() && lRefExpr.resolve() instanceof PsiField field) { + myImplicitCompactConstructorAssignments.remove(field); } PsiVariable variable = getUsedVariable((PsiReferenceExpression)lExpr); if (variable != null) { @@ -1486,12 +1518,12 @@ public void visitAssignmentExpression(PsiAssignmentExpression expression) { lExpr.accept(this); //? } } - else if (lExpr instanceof PsiArrayAccessExpression && - ((PsiArrayAccessExpression)lExpr).getArrayExpression() instanceof PsiReferenceExpression) { - PsiVariable variable = getUsedVariable((PsiReferenceExpression)((PsiArrayAccessExpression)lExpr).getArrayExpression()); + else if (lExpr instanceof PsiArrayAccessExpression lArrayAccessExpr && + lArrayAccessExpr.getArrayExpression() instanceof PsiReferenceExpression lRefExpr) { + PsiVariable variable = getUsedVariable(lRefExpr); if (variable != null) { generateReadInstruction(variable); - final PsiExpression indexExpression = ((PsiArrayAccessExpression)lExpr).getIndexExpression(); + PsiExpression indexExpression = lArrayAccessExpr.getIndexExpression(); if (indexExpression != null) { indexExpression.accept(this); } @@ -1523,11 +1555,12 @@ else if (lExpr != null) { private enum Shortcut { NO_SHORTCUT, // a || b SKIP_CURRENT_OPERAND, // false || a - STOP_EXPRESSION // true || a + STOP_EXPRESSION // true || a } @Override - public void visitPolyadicExpression(PsiPolyadicExpression expression) { + @RequiredReadAction + public void visitPolyadicExpression(@Nonnull PsiPolyadicExpression expression) { startElement(expression); IElementType signTokenType = expression.getOperationTokenType(); @@ -1541,10 +1574,9 @@ public void visitPolyadicExpression(PsiPolyadicExpression expression) { for (int i = 0; i < operands.length; i++) { PsiExpression rOperand = operands[i]; if ((isAndAnd || isOrOr) && myOptions.enableShortCircuit()) { - Object exprValue = myConstantEvaluationHelper.computeConstantExpression(rOperand); - if (exprValue instanceof Boolean) { + if (myConstantEvaluationHelper.computeConstantExpression(rOperand) instanceof Boolean exprValue) { myCurrentFlow.setConstantConditionOccurred(true); - rValue = shouldCalculateConstantExpression(expression) ? (Boolean)exprValue : null; + rValue = shouldCalculateConstantExpression(expression) ? exprValue : null; } else { rValue = null; @@ -1556,9 +1588,9 @@ public void visitPolyadicExpression(PsiPolyadicExpression expression) { Shortcut shortcut; if (lValue != null) { - shortcut = lValue.booleanValue() == isOrOr ? Shortcut.STOP_EXPRESSION : Shortcut.SKIP_CURRENT_OPERAND; + shortcut = lValue == isOrOr ? Shortcut.STOP_EXPRESSION : Shortcut.SKIP_CURRENT_OPERAND; } - else if (rValue != null && rValue.booleanValue() == isOrOr) { + else if (rValue != null && rValue == isOrOr) { shortcut = Shortcut.STOP_EXPRESSION; } else { @@ -1613,11 +1645,10 @@ private void generateLOperand(@Nonnull PsiExpression lOperand, @Nullable PsiExpr private static boolean isInsideIfCondition(@Nonnull PsiExpression expression) { PsiElement element = expression; while (element instanceof PsiExpression) { - final PsiElement parent = element.getParent(); - if (parent instanceof PsiIfStatement && element == ((PsiIfStatement)parent).getCondition()) { + if (element.getParent() instanceof PsiIfStatement ifStmt && element == ifStmt.getCondition()) { return true; } - element = parent; + element = element.getParent(); } return false; } @@ -1627,10 +1658,12 @@ private boolean shouldCalculateConstantExpression(@Nonnull PsiExpression express } @Override - public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) { + @RequiredReadAction + public void visitClassObjectAccessExpression(@Nonnull PsiClassObjectAccessExpression expression) { visitChildren(expression); } + @RequiredReadAction private void visitChildren(@Nonnull PsiElement element) { startElement(element); @@ -1644,27 +1677,29 @@ private void visitChildren(@Nonnull PsiElement element) { } @Override - public void visitConditionalExpression(PsiConditionalExpression expression) { + @RequiredReadAction + public void visitConditionalExpression(@Nonnull PsiConditionalExpression expression) { startElement(expression); - final PsiExpression condition = expression.getCondition(); - final PsiExpression thenExpression = expression.getThenExpression(); - final PsiExpression elseExpression = expression.getElseExpression(); + PsiExpression condition = expression.getCondition(); + PsiExpression thenExpression = expression.getThenExpression(); + PsiExpression elseExpression = expression.getElseExpression(); generateConditionalStatementInstructions(expression, condition, thenExpression, elseExpression); finishElement(expression); } @Override - public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { + @RequiredReadAction + public void visitInstanceOfExpression(@Nonnull PsiInstanceOfExpression expression) { startElement(expression); - final PsiExpression operand = expression.getOperand(); + PsiExpression operand = expression.getOperand(); operand.accept(this); PsiPattern pattern = expression.getPattern(); - if (pattern instanceof PsiTypeTestPattern) { - PsiPatternVariable variable = ((PsiTypeTestPattern)pattern).getPatternVariable(); + if (pattern instanceof PsiTypeTestPattern typeTestPattern) { + PsiPatternVariable variable = typeTestPattern.getPatternVariable(); if (variable != null) { myCurrentFlow.addInstruction(new WriteVariableInstruction(variable)); @@ -1675,15 +1710,17 @@ public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { } @Override - public void visitLiteralExpression(PsiLiteralExpression expression) { + @RequiredReadAction + public void visitLiteralExpression(@Nonnull PsiLiteralExpression expression) { startElement(expression); finishElement(expression); } @Override - public void visitLambdaExpression(PsiLambdaExpression expression) { + @RequiredReadAction + public void visitLambdaExpression(@Nonnull PsiLambdaExpression expression) { startElement(expression); - final PsiElement body = expression.getBody(); + PsiElement body = expression.getBody(); if (body != null) { List array = new ArrayList<>(); addUsedVariables(array, body); @@ -1696,7 +1733,8 @@ public void visitLambdaExpression(PsiLambdaExpression expression) { } @Override - public void visitMethodCallExpression(PsiMethodCallExpression expression) { + @RequiredReadAction + public void visitMethodCallExpression(@Nonnull PsiMethodCallExpression expression) { ArrayDeque calls = new ArrayDeque<>(); while (true) { calls.addFirst(expression); @@ -1713,7 +1751,7 @@ public void visitMethodCallExpression(PsiMethodCallExpression expression) { } for (PsiMethodCallExpression call : calls) { - final PsiExpressionList argumentList = call.getArgumentList(); + PsiExpressionList argumentList = call.getArgumentList(); argumentList.accept(this); // just to increase counter - there is some executable code here emitEmptyInstruction(); @@ -1726,7 +1764,8 @@ public void visitMethodCallExpression(PsiMethodCallExpression expression) { } @Override - public void visitNewExpression(PsiNewExpression expression) { + @RequiredReadAction + public void visitNewExpression(@Nonnull PsiNewExpression expression) { startElement(expression); int pc = myCurrentFlow.getSize(); @@ -1747,12 +1786,14 @@ public void visitNewExpression(PsiNewExpression expression) { } @Override - public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { + @RequiredReadAction + public void visitParenthesizedExpression(@Nonnull PsiParenthesizedExpression expression) { visitChildren(expression); } @Override - public void visitPostfixExpression(PsiPostfixExpression expression) { + @RequiredReadAction + public void visitPostfixExpression(@Nonnull PsiPostfixExpression expression) { startElement(expression); IElementType op = expression.getOperationTokenType(); @@ -1760,8 +1801,8 @@ public void visitPostfixExpression(PsiPostfixExpression expression) { if (operand != null) { operand.accept(this); if (op == JavaTokenType.PLUSPLUS || op == JavaTokenType.MINUSMINUS) { - if (operand instanceof PsiReferenceExpression) { - PsiVariable variable = getUsedVariable((PsiReferenceExpression)operand); + if (operand instanceof PsiReferenceExpression refExpr) { + PsiVariable variable = getUsedVariable(refExpr); if (variable != null) { generateWriteInstruction(variable); } @@ -1773,7 +1814,8 @@ public void visitPostfixExpression(PsiPostfixExpression expression) { } @Override - public void visitPrefixExpression(PsiPrefixExpression expression) { + @RequiredReadAction + public void visitPrefixExpression(@Nonnull PsiPrefixExpression expression) { startElement(expression); PsiExpression operand = PsiUtil.skipParenthesizedExprDown(expression.getOperand()); @@ -1795,9 +1837,9 @@ public void visitPrefixExpression(PsiPrefixExpression expression) { myEndStatementStack.popStatement(); } - if (operand instanceof PsiReferenceExpression && - (operationSign == JavaTokenType.PLUSPLUS || operationSign == JavaTokenType.MINUSMINUS)) { - PsiVariable variable = getUsedVariable((PsiReferenceExpression)operand); + if (operand instanceof PsiReferenceExpression operandRefExpr + && (operationSign == JavaTokenType.PLUSPLUS || operationSign == JavaTokenType.MINUSMINUS)) { + PsiVariable variable = getUsedVariable(operandRefExpr); if (variable != null) { generateWriteInstruction(variable); } @@ -1808,7 +1850,8 @@ public void visitPrefixExpression(PsiPrefixExpression expression) { } @Override - public void visitReferenceExpression(PsiReferenceExpression expression) { + @RequiredReadAction + public void visitReferenceExpression(@Nonnull PsiReferenceExpression expression) { startElement(expression); PsiExpression qualifier = expression.getQualifierExpression(); @@ -1824,21 +1867,23 @@ public void visitReferenceExpression(PsiReferenceExpression expression) { finishElement(expression); } - @Override - public void visitSuperExpression(PsiSuperExpression expression) { + @RequiredReadAction + public void visitSuperExpression(@Nonnull PsiSuperExpression expression) { startElement(expression); finishElement(expression); } @Override - public void visitThisExpression(PsiThisExpression expression) { + @RequiredReadAction + public void visitThisExpression(@Nonnull PsiThisExpression expression) { startElement(expression); finishElement(expression); } @Override - public void visitTypeCastExpression(PsiTypeCastExpression expression) { + @RequiredReadAction + public void visitTypeCastExpression(@Nonnull PsiTypeCastExpression expression) { startElement(expression); PsiExpression operand = expression.getOperand(); if (operand != null) { @@ -1848,11 +1893,12 @@ public void visitTypeCastExpression(PsiTypeCastExpression expression) { } @Override - public void visitClass(PsiClass aClass) { + @RequiredReadAction + public void visitClass(@Nonnull PsiClass aClass) { startElement(aClass); // anonymous or local class if (aClass instanceof PsiAnonymousClass) { - final PsiElement arguments = PsiTreeUtil.getChildOfType(aClass, PsiExpressionList.class); + PsiElement arguments = PsiTreeUtil.getChildOfType(aClass, PsiExpressionList.class); if (arguments != null) { arguments.accept(this); } @@ -1866,9 +1912,10 @@ public void visitClass(PsiClass aClass) { finishElement(aClass); } + @RequiredReadAction private void addUsedVariables(@Nonnull List array, @Nonnull PsiElement scope) { - if (scope instanceof PsiReferenceExpression) { - PsiVariable variable = getUsedVariable((PsiReferenceExpression)scope); + if (scope instanceof PsiReferenceExpression scopeRefExpr) { + PsiVariable variable = getUsedVariable(scopeRefExpr); if (variable != null) { if (!array.contains(variable)) { array.add(variable); diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/PsiSubstitutorImpl.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/PsiSubstitutorImpl.java index 8dfcfd7b1..d4e8961ee 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/PsiSubstitutorImpl.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/impl/PsiSubstitutorImpl.java @@ -6,7 +6,9 @@ import com.intellij.java.language.impl.psi.impl.source.PsiClassReferenceType; import com.intellij.java.language.psi.*; import com.intellij.java.language.psi.util.PsiUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.util.RecursionManager; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiUtilCore; import consulo.logging.Logger; @@ -14,10 +16,8 @@ import consulo.util.collection.HashingStrategy; import consulo.util.collection.UnmodifiableHashMap; import consulo.util.lang.Comparing; -import jakarta.annotation.Nullable; -import org.jetbrains.annotations.NonNls; - import jakarta.annotation.Nonnull; +import jakarta.annotation.Nullable; import java.util.HashMap; import java.util.Map; @@ -31,6 +31,7 @@ public final class PsiSubstitutorImpl implements PsiSubstitutor { private static final HashingStrategy PSI_EQUIVALENCE = new HashingStrategy<>() { @Override + @RequiredReadAction public int hashCode(PsiTypeParameter parameter) { return Comparing.hashcode(parameter.getName()); } @@ -76,8 +77,8 @@ public PsiType substitute(@Nonnull PsiTypeParameter typeParameter) { * @return type mapped to type parameter; null if type parameter is mapped to null; or PsiType.VOID if no mapping exists */ private PsiType getFromMap(@Nonnull PsiTypeParameter typeParameter) { - if (typeParameter instanceof LightTypeParameter && ((LightTypeParameter)typeParameter).useDelegateToSubstitute()) { - typeParameter = ((LightTypeParameter)typeParameter).getDelegate(); + if (typeParameter instanceof LightTypeParameter lightTypeParam && lightTypeParam.useDelegateToSubstitute()) { + typeParameter = lightTypeParam.getDelegate(); } return mySubstitutionMap.getOrDefault(typeParameter, PsiType.VOID); } @@ -94,15 +95,14 @@ public PsiType substitute(PsiType type) { @Override public PsiType substituteWithBoundsPromotion(@Nonnull PsiTypeParameter typeParameter) { - final PsiType substituted = substitute(typeParameter); - if (substituted instanceof PsiWildcardType && !((PsiWildcardType)substituted).isSuper()) { - final PsiWildcardType wildcardType = (PsiWildcardType)substituted; - final PsiType glb = PsiCapturedWildcardType.captureUpperBound(typeParameter, wildcardType, this); + PsiType substituted = substitute(typeParameter); + if (substituted instanceof PsiWildcardType wildcardType && !wildcardType.isSuper()) { + PsiType glb = PsiCapturedWildcardType.captureUpperBound(typeParameter, wildcardType, this); if (glb instanceof PsiWildcardType) { return glb; } - if (glb instanceof PsiCapturedWildcardType) { - PsiWildcardType wildcard = ((PsiCapturedWildcardType)glb).getWildcard(); + if (glb instanceof PsiCapturedWildcardType capturedWildcardType) { + PsiWildcardType wildcard = capturedWildcardType.getWildcard(); if (!wildcard.isSuper()) { return wildcard; } @@ -116,11 +116,10 @@ public PsiType substituteWithBoundsPromotion(@Nonnull PsiTypeParameter typeParam } @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - return o instanceof PsiSubstitutorImpl && mySubstitutionMap.equals(((PsiSubstitutorImpl)o).mySubstitutionMap); + public boolean equals(Object o) { + return this == o + || o instanceof PsiSubstitutorImpl that + && mySubstitutionMap.equals(that.mySubstitutionMap); } @Override @@ -129,7 +128,7 @@ public int hashCode() { } private PsiType rawTypeForTypeParameter(@Nonnull PsiTypeParameter typeParameter) { - final PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes(); + PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes(); if (extendsTypes.length > 0) { // First bound return RecursionManager.doPreventingRecursion(extendsTypes[0], true, () -> substitute(extendsTypes[0])); @@ -158,19 +157,20 @@ public PsiType visitType(@Nonnull PsiType type) { @Override public PsiType visitWildcardType(@Nonnull PsiWildcardType wildcardType) { - final PsiType bound = wildcardType.getBound(); + PsiType bound = wildcardType.getBound(); if (bound == null) { return wildcardType; } else { - final PsiType newBound = bound.accept(this); + PsiType newBound = bound.accept(this); if (newBound == null) { return null; } assert newBound.isValid() : newBound.getClass() + "; " + bound.isValid(); - if (newBound instanceof PsiWildcardType) { - final PsiType newBoundBound = ((PsiWildcardType)newBound).getBound(); - return !((PsiWildcardType)newBound).isBounded() ? PsiWildcardType.createUnbounded(wildcardType.getManager()) + if (newBound instanceof PsiWildcardType newBoundWildcardType) { + PsiType newBoundBound = newBoundWildcardType.getBound(); + return !newBoundWildcardType.isBounded() + ? PsiWildcardType.createUnbounded(wildcardType.getManager()) : rebound(wildcardType, newBoundBound); } @@ -184,7 +184,7 @@ private PsiWildcardType rebound(@Nonnull PsiWildcardType type, @Nonnull PsiType LOG.assertTrue(newBound.isValid()); if (type.isExtends()) { - if (newBound.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { + if (newBound.equalsToText(JavaClassNames.JAVA_LANG_OBJECT)) { return PsiWildcardType.createUnbounded(type.getManager()); } return PsiWildcardType.createExtends(type.getManager(), newBound); @@ -193,17 +193,16 @@ private PsiWildcardType rebound(@Nonnull PsiWildcardType type, @Nonnull PsiType } @Override - public PsiType visitClassType(@Nonnull final PsiClassType classType) { - final PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); - final PsiClass aClass = resolveResult.getElement(); + public PsiType visitClassType(@Nonnull PsiClassType classType) { + PsiClassType.ClassResolveResult resolveResult = classType.resolveGenerics(); + PsiClass aClass = resolveResult.getElement(); if (aClass == null) { return classType; } PsiUtilCore.ensureValid(aClass); - if (aClass instanceof PsiTypeParameter) { - final PsiTypeParameter typeParameter = (PsiTypeParameter)aClass; - final PsiType result = getFromMap(typeParameter); + if (aClass instanceof PsiTypeParameter typeParam) { + PsiType result = getFromMap(typeParam); if (PsiType.VOID.equals(result)) { return classType; } @@ -215,7 +214,7 @@ public PsiType visitClassType(@Nonnull final PsiClassType classType) { } return result; } - final Map hashMap = new HashMap<>(2); + Map hashMap = new HashMap<>(2); if (!processClass(aClass, resolveResult.getSubstitutor(), hashMap)) { return null; } @@ -234,9 +233,9 @@ private boolean processClass( @Nonnull PsiSubstitutor originalSubstitutor, @Nonnull Map substMap ) { - final PsiTypeParameter[] params = resolve.getTypeParameters(); - for (final PsiTypeParameter param : params) { - final PsiType original = originalSubstitutor.substitute(param); + PsiTypeParameter[] params = resolve.getTypeParameters(); + for (PsiTypeParameter param : params) { + PsiType original = originalSubstitutor.substitute(param); if (original == null) { substMap.put(param, null); } @@ -244,11 +243,11 @@ private boolean processClass( substMap.put(param, substituteInternal(original)); } } - if (resolve.hasModifierProperty(PsiModifier.STATIC)) { + if (resolve.isStatic()) { return true; } - final PsiClass containingClass = resolve.getContainingClass(); + PsiClass containingClass = resolve.getContainingClass(); return containingClass == null || processClass(containingClass, originalSubstitutor, substMap); } @@ -308,7 +307,7 @@ private static UnmodifiableHashMap putAllInternal( @Nonnull PsiClass parentClass, PsiType[] mappings ) { - final PsiTypeParameter[] params = parentClass.getTypeParameters(); + PsiTypeParameter[] params = parentClass.getTypeParameters(); if (params.length == 0) { return originalMap; } @@ -343,7 +342,7 @@ public PsiSubstitutor putAll(@Nonnull PsiSubstitutor another) { if (another instanceof EmptySubstitutor) { return this; } - final PsiSubstitutorImpl anotherImpl = (PsiSubstitutorImpl)another; + PsiSubstitutorImpl anotherImpl = (PsiSubstitutorImpl)another; return putAll(anotherImpl.mySubstitutionMap); } @@ -357,22 +356,23 @@ public PsiSubstitutor putAll(@Nonnull Map> set = mySubstitutionMap.entrySet(); + StringBuilder buffer = new StringBuilder(); + Set> set = mySubstitutionMap.entrySet(); for (Map.Entry entry : set) { - final PsiTypeParameter typeParameter = entry.getKey(); + PsiTypeParameter typeParameter = entry.getKey(); buffer.append(typeParameter.getName()); - final PsiElement owner = typeParameter.getOwner(); - if (owner instanceof PsiClass) { + PsiElement owner = typeParameter.getOwner(); + if (owner instanceof PsiClass psiClass) { buffer.append(" of "); - buffer.append(((PsiClass)owner).getQualifiedName()); + buffer.append(psiClass.getQualifiedName()); } - else if (owner instanceof PsiMethod) { + else if (owner instanceof PsiMethod method) { buffer.append(" of "); - buffer.append(((PsiMethod)owner).getName()); + buffer.append(method.getName()); buffer.append(" in "); - PsiClass aClass = ((PsiMethod)owner).getContainingClass(); + PsiClass aClass = method.getContainingClass(); buffer.append(aClass != null ? aClass.getQualifiedName() : ""); } buffer.append(" -> "); diff --git a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/scope/util/PsiScopesUtil.java b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/scope/util/PsiScopesUtil.java index adfb81683..1e338b982 100644 --- a/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/scope/util/PsiScopesUtil.java +++ b/java-language-impl/src/main/java/com/intellij/java/language/impl/psi/scope/util/PsiScopesUtil.java @@ -27,7 +27,9 @@ import com.intellij.java.language.psi.scope.JavaScopeProcessorEvent; import com.intellij.java.language.psi.util.PsiUtil; import com.intellij.java.language.psi.util.TypeConversionUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.application.progress.ProgressIndicatorProvider; +import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiInvalidElementAccessException; import consulo.language.psi.PsiManager; @@ -55,10 +57,10 @@ public static boolean treeWalkUp(@Nonnull PsiScopeProcessor processor, @Nonnull } public static boolean treeWalkUp( - @Nonnull final PsiScopeProcessor processor, - @Nonnull final PsiElement entrance, - @Nullable final PsiElement maxScope, - @Nonnull final ResolveState state + @Nonnull PsiScopeProcessor processor, + @Nonnull PsiElement entrance, + @Nullable PsiElement maxScope, + @Nonnull ResolveState state ) { if (!entrance.isValid()) { LOG.error(new PsiInvalidElementAccessException(entrance)); @@ -75,8 +77,9 @@ public static boolean treeWalkUp( return false; // resolved } - if (scope instanceof PsiModifierListOwner && !(scope instanceof PsiParameter/* important for not loading tree! */)) { - PsiModifierList modifierList = ((PsiModifierListOwner)scope).getModifierList(); + if (scope instanceof PsiModifierListOwner modifierListOwner + && !(scope instanceof PsiParameter/* important for not loading tree! */)) { + PsiModifierList modifierList = modifierListOwner.getModifierList(); if (modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC)) { processor.handleEvent(JavaScopeProcessorEvent.START_STATIC, null); } @@ -92,6 +95,7 @@ public static boolean treeWalkUp( return true; } + @RequiredReadAction public static boolean walkChildrenScopes( @Nonnull PsiElement thisElement, @Nonnull PsiScopeProcessor processor, @@ -121,41 +125,43 @@ public static boolean walkChildrenScopes( return true; } + @RequiredReadAction public static void processTypeDeclarations(PsiType type, PsiElement place, PsiScopeProcessor processor) { - if (type instanceof PsiArrayType) { + if (type instanceof PsiArrayType arrayType) { LanguageLevel languageLevel = PsiUtil.getLanguageLevel(place); - final PsiClass arrayClass = JavaPsiFacade.getElementFactory(place.getProject()).getArrayClass(languageLevel); - final PsiTypeParameter[] arrayTypeParameters = arrayClass.getTypeParameters(); + PsiClass arrayClass = JavaPsiFacade.getElementFactory(place.getProject()).getArrayClass(languageLevel); + PsiTypeParameter[] arrayTypeParameters = arrayClass.getTypeParameters(); PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; if (arrayTypeParameters.length > 0) { - substitutor = substitutor.put(arrayTypeParameters[0], ((PsiArrayType)type).getComponentType()); + substitutor = substitutor.put(arrayTypeParameters[0], arrayType.getComponentType()); } arrayClass.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, substitutor), arrayClass, place); } - else if (type instanceof PsiIntersectionType) { - for (PsiType psiType : ((PsiIntersectionType)type).getConjuncts()) { + else if (type instanceof PsiIntersectionType intersectionType) { + for (PsiType psiType : intersectionType.getConjuncts()) { processTypeDeclarations(psiType, place, processor); } } - else if (type instanceof PsiDisjunctionType) { - final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound(); + else if (type instanceof PsiDisjunctionType disjunctionType) { + PsiType lub = disjunctionType.getLeastUpperBound(); processTypeDeclarations(lub, place, processor); } - else if (type instanceof PsiCapturedWildcardType) { - final PsiType classType = convertToTypeParameter((PsiCapturedWildcardType)type, place); + else if (type instanceof PsiCapturedWildcardType capturedWildcardType) { + PsiType classType = convertToTypeParameter(capturedWildcardType, place); if (classType != null) { processTypeDeclarations(classType, place, processor); } } else { - final JavaResolveResult result = PsiUtil.resolveGenericsClassInType(type); - final PsiClass clazz = (PsiClass)result.getElement(); + JavaResolveResult result = PsiUtil.resolveGenericsClassInType(type); + PsiClass clazz = (PsiClass)result.getElement(); if (clazz != null) { clazz.processDeclarations(processor, ResolveState.initial().put(PsiSubstitutor.KEY, result.getSubstitutor()), clazz, place); } } } + @RequiredReadAction public static boolean resolveAndWalk( @Nonnull PsiScopeProcessor processor, @Nonnull PsiJavaCodeReferenceElement ref, @@ -164,14 +170,15 @@ public static boolean resolveAndWalk( return resolveAndWalk(processor, ref, maxScope, false); } + @RequiredReadAction public static boolean resolveAndWalk( @Nonnull PsiScopeProcessor processor, @Nonnull PsiJavaCodeReferenceElement ref, @Nullable PsiElement maxScope, boolean incompleteCode ) { - final PsiElement qualifier = ref.getQualifier(); - final PsiElement classNameElement = ref.getReferenceNameElement(); + PsiElement qualifier = ref.getQualifier(); + PsiElement classNameElement = ref.getReferenceNameElement(); if (classNameElement == null) { return true; } @@ -181,25 +188,24 @@ public static boolean resolveAndWalk( PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; if (qualifier instanceof PsiExpression || qualifier instanceof PsiJavaCodeReferenceElement) { PsiType type = null; - if (qualifier instanceof PsiExpression) { - type = ((PsiExpression)qualifier).getType(); + if (qualifier instanceof PsiExpression expression) { + type = expression.getType(); if (type != null) { assert type.isValid() : type.getClass() + "; " + qualifier; } processTypeDeclarations(type, ref, processor); } - if (type == null && qualifier instanceof PsiJavaCodeReferenceElement) { + if (type == null && qualifier instanceof PsiJavaCodeReferenceElement referenceElement) { // In case of class qualifier - final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)qualifier; - final JavaResolveResult result = referenceElement.advancedResolve(incompleteCode); + JavaResolveResult result = referenceElement.advancedResolve(incompleteCode); target = result.getElement(); substitutor = result.getSubstitutor(); - if (target instanceof PsiVariable) { - type = substitutor.substitute(((PsiVariable)target).getType()); - if (type instanceof PsiClassType) { - final JavaResolveResult typeResult = ((PsiClassType)type).resolveGenerics(); + if (target instanceof PsiVariable variable) { + type = substitutor.substitute(variable.getType()); + if (type instanceof PsiClassType classType) { + JavaResolveResult typeResult = classType.resolveGenerics(); target = typeResult.getElement(); substitutor = substitutor.putAll(typeResult.getSubstitutor()); } @@ -207,19 +213,18 @@ public static boolean resolveAndWalk( target = null; } } - else if (target instanceof PsiMethod) { - type = substitutor.substitute(((PsiMethod)target).getReturnType()); - if (type instanceof PsiClassType) { - final JavaResolveResult typeResult = ((PsiClassType)type).resolveGenerics(); + else if (target instanceof PsiMethod method) { + if (substitutor.substitute(method.getReturnType()) instanceof PsiClassType classType) { + JavaResolveResult typeResult = classType.resolveGenerics(); target = typeResult.getElement(); substitutor = substitutor.putAll(typeResult.getSubstitutor()); } else { target = null; } - final PsiType[] types = referenceElement.getTypeParameters(); - if (target instanceof PsiClass) { - substitutor = substitutor.putAll((PsiClass)target, types); + PsiType[] types = referenceElement.getTypeParameters(); + if (target instanceof PsiClass psiClass) { + substitutor = substitutor.putAll(psiClass, types); } } else if (target instanceof PsiClass) { @@ -240,29 +245,26 @@ else if (target instanceof PsiClass) { return true; } + @RequiredReadAction public static void setupAndRunProcessor( @Nonnull MethodsProcessor processor, @Nonnull PsiCallExpression call, boolean dummyImplicitConstructor ) throws MethodProcessorSetupFailedException { - if (call instanceof PsiMethodCallExpression) { - final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)call; - final PsiJavaCodeReferenceElement ref = methodCall.getMethodExpression(); - + if (call instanceof PsiMethodCallExpression methodCall) { + PsiJavaCodeReferenceElement ref = methodCall.getMethodExpression(); processor.setArgumentList(methodCall.getArgumentList()); processor.obtainTypeArguments(methodCall); if (!ref.isQualified() || ref.getReferenceNameElement() instanceof PsiKeyword) { - final PsiElement referenceNameElement = ref.getReferenceNameElement(); + PsiElement referenceNameElement = ref.getReferenceNameElement(); if (referenceNameElement == null) { return; } - if (referenceNameElement instanceof PsiKeyword) { - final PsiKeyword keyword = (PsiKeyword)referenceNameElement; - + if (referenceNameElement instanceof PsiKeyword keyword) { if (keyword.getTokenType() == JavaTokenType.THIS_KEYWORD) { - final PsiClass aClass = JavaResolveUtil.getContextClass(methodCall); + PsiClass aClass = JavaResolveUtil.getContextClass(methodCall); if (aClass == null) { throw new MethodProcessorSetupFailedException("Can't resolve class for this expression"); } @@ -281,7 +283,7 @@ else if (keyword.getTokenType() == JavaTokenType.SUPER_KEYWORD) { throw new MethodProcessorSetupFailedException("Can't resolve class for super expression"); } - final PsiClass superClass = aClass.getSuperClass(); + PsiClass superClass = aClass.getSuperClass(); if (superClass != null) { PsiSubstitutor substitutor = PsiSubstitutor.EMPTY; PsiClass runSuper = superClass; @@ -292,7 +294,7 @@ else if (keyword.getTokenType() == JavaTokenType.SUPER_KEYWORD) { TypeConversionUtil.getSuperClassSubstitutor(runSuper, aClass, PsiSubstitutor.EMPTY); contextSubstitutors.add(superSubstitutor); } - if (aClass.hasModifierProperty(PsiModifier.STATIC)) { + if (aClass.isStatic()) { break; } aClass = JavaResolveUtil.getContextClass(aClass); @@ -309,7 +311,7 @@ else if (keyword.getTokenType() == JavaTokenType.SUPER_KEYWORD) { processor.setIsConstructor(true); processor.setAccessClass(null); - final PsiMethod[] constructors = superClass.getConstructors(); + PsiMethod[] constructors = superClass.getConstructors(); ResolveState state = ResolveState.initial().put(PsiSubstitutor.KEY, substitutor); for (PsiMethod constructor : constructors) { if (!processor.execute(constructor, state)) { @@ -338,19 +340,18 @@ else if (referenceNameElement instanceof PsiIdentifier) { } else { // Complex expression - final PsiElement referenceName = methodCall.getMethodExpression().getReferenceNameElement(); - final PsiManager manager = call.getManager(); - final PsiElement qualifier = ref.getQualifier(); + PsiElement referenceName = methodCall.getMethodExpression().getReferenceNameElement(); + PsiManager manager = call.getManager(); if (referenceName == null) { // e.g. "manager.(beginTransaction)" throw new MethodProcessorSetupFailedException("Can't resolve method name for this expression"); } - if (referenceName instanceof PsiIdentifier && qualifier instanceof PsiExpression) { - PsiType type = ((PsiExpression)qualifier).getType(); - if (type != null && qualifier instanceof PsiReferenceExpression) { - final PsiElement resolve = ((PsiReferenceExpression)qualifier).resolve(); - if (resolve instanceof PsiEnumConstant) { - final PsiEnumConstantInitializer initializingClass = ((PsiEnumConstant)resolve).getInitializingClass(); + if (referenceName instanceof PsiIdentifier && ref.getQualifier() instanceof PsiExpression qualifier) { + PsiType type = qualifier.getType(); + if (type != null && qualifier instanceof PsiReferenceExpression qRfExpr) { + PsiElement resolve = qRfExpr.resolve(); + if (resolve instanceof PsiEnumConstant enumConst) { + PsiEnumConstantInitializer initializingClass = enumConst.getInitializingClass(); if (hasDesiredMethod(methodCall, type, initializingClass)) { processQualifierResult( new ClassCandidateInfo(initializingClass, PsiSubstitutor.EMPTY), @@ -360,21 +361,19 @@ else if (referenceNameElement instanceof PsiIdentifier) { return; } } - else if (resolve instanceof PsiVariable - && ((PsiVariable)resolve).hasModifierProperty(PsiModifier.FINAL) - && ((PsiVariable)resolve).hasInitializer()) { - final PsiExpression initializer = ((PsiVariable)resolve).getInitializer(); - if (initializer instanceof PsiNewExpression) { - final PsiAnonymousClass anonymousClass = ((PsiNewExpression)initializer).getAnonymousClass(); - if (hasDesiredMethod(methodCall, type, anonymousClass)) { - type = initializer.getType(); - } + else if (resolve instanceof PsiVariable variable + && variable.hasModifierProperty(PsiModifier.FINAL) + && variable.hasInitializer()) { + PsiExpression initializer = variable.getInitializer(); + if (initializer instanceof PsiNewExpression newExpr + && hasDesiredMethod(methodCall, type, newExpr.getAnonymousClass())) { + type = initializer.getType(); } } } if (type == null) { - if (qualifier instanceof PsiJavaCodeReferenceElement) { - final JavaResolveResult result = ((PsiJavaCodeReferenceElement)qualifier).advancedResolve(false); + if (qualifier instanceof PsiJavaCodeReferenceElement javaCodeRef) { + JavaResolveResult result = javaCodeRef.advancedResolve(false); if (result.getElement() instanceof PsiClass) { processor.handleEvent(JavaScopeProcessorEvent.START_STATIC, null); processQualifierResult(result, processor, methodCall); @@ -384,11 +383,11 @@ else if (resolve instanceof PsiVariable throw new MethodProcessorSetupFailedException("Cant determine qualifier type!"); } } - else if (type instanceof PsiDisjunctionType) { - processQualifierType(((PsiDisjunctionType)type).getLeastUpperBound(), processor, manager, methodCall); + else if (type instanceof PsiDisjunctionType disjunctionType) { + processQualifierType(disjunctionType.getLeastUpperBound(), processor, manager, methodCall); } - else if (type instanceof PsiCapturedWildcardType) { - final PsiType psiType = convertToTypeParameter((PsiCapturedWildcardType)type, methodCall); + else if (type instanceof PsiCapturedWildcardType capturedWildcardType) { + PsiType psiType = convertToTypeParameter(capturedWildcardType, methodCall); if (psiType != null) { processQualifierType(psiType, processor, manager, methodCall); } @@ -398,11 +397,13 @@ else if (type instanceof PsiCapturedWildcardType) { } } else { - LOG.error("ref: " + ref + " (" + ref.getClass() + ")," + + LOG.error( + "ref: " + ref + " (" + ref.getClass() + ")," + " ref.getReferenceNameElement()=" + ref.getReferenceNameElement() + "; methodCall.getMethodExpression().getReferenceNameElement()=" + methodCall.getMethodExpression().getReferenceNameElement() + - "; qualifier=" + qualifier); + "; qualifier=" + ref.getQualifier() + ); } } } @@ -414,7 +415,7 @@ else if (type instanceof PsiCapturedWildcardType) { throw new MethodProcessorSetupFailedException("Cant get reference to class in new expression"); } - final JavaResolveResult result = classRef.advancedResolve(false); + JavaResolveResult result = classRef.advancedResolve(false); PsiClass aClass = (PsiClass)result.getElement(); if (aClass == null) { throw new MethodProcessorSetupFailedException("Cant resolve class in new expression"); @@ -434,8 +435,8 @@ else if (type instanceof PsiCapturedWildcardType) { private static PsiType convertToTypeParameter(PsiCapturedWildcardType type, PsiElement methodCall) { GlobalSearchScope placeResolveScope = methodCall.getResolveScope(); PsiType upperBound = PsiClassImplUtil.correctType(type.getUpperBound(), placeResolveScope); - while (upperBound instanceof PsiCapturedWildcardType) { - upperBound = PsiClassImplUtil.correctType(((PsiCapturedWildcardType)upperBound).getUpperBound(), placeResolveScope); + while (upperBound instanceof PsiCapturedWildcardType capturedWildcardType) { + upperBound = PsiClassImplUtil.correctType(capturedWildcardType.getUpperBound(), placeResolveScope); } //arrays can't participate in extends list @@ -451,9 +452,9 @@ private static PsiType convertToTypeParameter(PsiCapturedWildcardType type, PsiE private static boolean hasDesiredMethod(PsiMethodCallExpression methodCall, PsiType type, PsiAnonymousClass anonymousClass) { if (anonymousClass != null && type.equals(anonymousClass.getBaseClassType())) { - final PsiMethod[] refMethods = anonymousClass.findMethodsByName(methodCall.getMethodExpression().getReferenceName(), false); + PsiMethod[] refMethods = anonymousClass.findMethodsByName(methodCall.getMethodExpression().getReferenceName(), false); if (refMethods.length > 0) { - final PsiClass baseClass = PsiUtil.resolveClassInType(type); + PsiClass baseClass = PsiUtil.resolveClassInType(type); if (baseClass != null && !hasCovariantOverridingOrNotPublic(baseClass, refMethods)) { for (PsiMethod method : refMethods) { if (method.findSuperMethods(baseClass).length > 0) { @@ -468,13 +469,13 @@ private static boolean hasDesiredMethod(PsiMethodCallExpression methodCall, PsiT private static boolean hasCovariantOverridingOrNotPublic(PsiClass baseClass, PsiMethod[] refMethods) { for (PsiMethod method : refMethods) { - final PsiType methodReturnType = method.getReturnType(); + PsiType methodReturnType = method.getReturnType(); for (PsiMethod superMethod : method.findSuperMethods(baseClass)) { if (!Comparing.equal(methodReturnType, superMethod.getReturnType())) { return true; } - if (!superMethod.hasModifierProperty(PsiModifier.PUBLIC)) { + if (!superMethod.isPublic()) { return true; } } @@ -482,26 +483,27 @@ private static boolean hasCovariantOverridingOrNotPublic(PsiClass baseClass, Psi return false; } + @RequiredReadAction private static boolean processQualifierType( - @Nonnull final PsiType type, - final MethodsProcessor processor, + @Nonnull PsiType type, + MethodsProcessor processor, PsiManager manager, PsiMethodCallExpression call ) throws MethodProcessorSetupFailedException { LOG.assertTrue(type.isValid()); - if (type instanceof PsiClassType) { - JavaResolveResult qualifierResult = ((PsiClassType)type).resolveGenerics(); + if (type instanceof PsiClassType classType) { + JavaResolveResult qualifierResult = classType.resolveGenerics(); return processQualifierResult(qualifierResult, processor, call); } - if (type instanceof PsiArrayType) { + if (type instanceof PsiArrayType arrayType) { LanguageLevel languageLevel = PsiUtil.getLanguageLevel(call); PsiElementFactory factory = JavaPsiFacade.getElementFactory(manager.getProject()); JavaResolveResult qualifierResult = - factory.getArrayClassType(((PsiArrayType)type).getComponentType(), languageLevel).resolveGenerics(); + factory.getArrayClassType(arrayType.getComponentType(), languageLevel).resolveGenerics(); return processQualifierResult(qualifierResult, processor, call); } - if (type instanceof PsiIntersectionType) { - for (PsiType conjunct : ((PsiIntersectionType)type).getConjuncts()) { + if (type instanceof PsiIntersectionType intersectionType) { + for (PsiType conjunct : intersectionType.getConjuncts()) { if (!processQualifierType(conjunct, processor, manager, call)) { return false; } @@ -511,6 +513,7 @@ private static boolean processQualifierType( return true; } + @RequiredReadAction private static boolean processQualifierResult( @Nonnull JavaResolveResult qualifierResult, @Nonnull MethodsProcessor processor, @@ -522,19 +525,19 @@ private static boolean processQualifierResult( throw new MethodProcessorSetupFailedException("Cant determine qualifier class!"); } - if (resolve instanceof PsiTypeParameter) { - processor.setAccessClass((PsiClass)resolve); + if (resolve instanceof PsiTypeParameter typeParam) { + processor.setAccessClass(typeParam); } - else if (resolve instanceof PsiClass) { + else if (resolve instanceof PsiClass psiClass) { PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression(); - if (!(qualifier instanceof PsiSuperExpression)) { + if (!(qualifier instanceof PsiSuperExpression superExpr)) { processor.setAccessClass((PsiClass)PsiUtil.getAccessObjectClass(qualifier).getElement()); } - else if (((PsiSuperExpression)qualifier).getQualifier() != null + else if (superExpr.getQualifier() != null && PsiUtil.isLanguageLevel8OrHigher(qualifier) - && CommonClassNames.JAVA_LANG_CLONEABLE.equals(((PsiClass)resolve).getQualifiedName()) - && ((PsiClass)resolve).isInterface()) { - processor.setAccessClass((PsiClass)resolve); + && JavaClassNames.JAVA_LANG_CLONEABLE.equals(psiClass.getQualifiedName()) + && psiClass.isInterface()) { + processor.setAccessClass(psiClass); } } @@ -553,8 +556,8 @@ private static void processDummyConstructor(MethodsProcessor processor, PsiClass if (constructors.length != 0) { return; } - final PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject()); - final PsiMethod dummyConstructor = factory.createConstructor(); + PsiElementFactory factory = JavaPsiFacade.getElementFactory(aClass.getProject()); + PsiMethod dummyConstructor = factory.createConstructor(); PsiIdentifier nameIdentifier = aClass.getNameIdentifier(); if (nameIdentifier != null) { dummyConstructor.getNameIdentifier().replace(nameIdentifier);