diff --git a/python/python-psi-api/src/com/jetbrains/python/PythonFunctionParameters.java b/python/python-psi-api/src/com/jetbrains/python/PythonFunctionParameters.java index 56b873bf18d8..ca998b91465a 100644 --- a/python/python-psi-api/src/com/jetbrains/python/PythonFunctionParameters.java +++ b/python/python-psi-api/src/com/jetbrains/python/PythonFunctionParameters.java @@ -17,7 +17,7 @@ public enum PythonFunctionParameters implements FunctionParameter { /** * environment.setdevault(key, failobj) # failobj */ - ENV_SET_DEFAULT_FAILOBJ("failobj",1); + ENV_SET_DEFAULT_FAILOBJ("failobj", 1); private final @Nullable String myName; diff --git a/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyCustomMember.java b/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyCustomMember.java index 2842f1f291ae..318694bac4cb 100644 --- a/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyCustomMember.java +++ b/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyCustomMember.java @@ -216,7 +216,8 @@ public class PyCustomMember extends UserDataHolderBase { targetClass = (PyClass)resolveTarget; } - return PyCustomMemberProvider.getInstance().createPyCustomMemberTarget(this, targetClass, context, resolveTarget, myTypeCallback, myCustomTypeInfo, myResolveToInstance); + return PyCustomMemberProvider.getInstance() + .createPyCustomMemberTarget(this, targetClass, context, resolveTarget, myTypeCallback, myCustomTypeInfo, myResolveToInstance); } return null; } @@ -284,5 +285,4 @@ public class PyCustomMember extends UserDataHolderBase { myCustomTypeInfo = customInfo; return this; } - } diff --git a/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyPsiPath.java b/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyPsiPath.java index 7cb2e16dd50c..83dd9c3ae49f 100644 --- a/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyPsiPath.java +++ b/python/python-psi-api/src/com/jetbrains/python/codeInsight/PyPsiPath.java @@ -64,7 +64,7 @@ public abstract class PyPsiPath { return null; } if (parent instanceof PyFile) { - return ((PyFile) parent).findTopLevelClass(myClassName); + return ((PyFile)parent).findTopLevelClass(myClassName); } if (resolveContext.getTypeEvalContext().maySwitchToAST(parent)) { if (parent instanceof PyClass) { @@ -115,10 +115,10 @@ public abstract class PyPsiPath { return null; } if (parent instanceof PyFile) { - return ((PyFile) parent).findTopLevelFunction(myFunctionName); + return ((PyFile)parent).findTopLevelFunction(myFunctionName); } if (parent instanceof PyClass) { - return ((PyClass) parent).findMethodByName(myFunctionName, false, resolveContext.getTypeEvalContext()); + return ((PyClass)parent).findMethodByName(myFunctionName, false, resolveContext.getTypeEvalContext()); } if (resolveContext.getTypeEvalContext().maySwitchToAST(parent)) { for (PsiElement element : parent.getChildren()) { @@ -230,14 +230,14 @@ public abstract class PyPsiPath { final PyExpression callee = node.getCallee(); if (callee instanceof PyReferenceExpression) { - final String calleeName = ((PyReferenceExpression) callee).getReferencedName(); + final String calleeName = ((PyReferenceExpression)callee).getReferencedName(); if (myCallName.equals(calleeName)) { final PyExpression[] args = node.getArguments(); if (myArgs.length <= args.length) { boolean argsMatch = true; for (int i = 0; i < myArgs.length; i++) { if (!(args[i] instanceof PyStringLiteralExpression) || - !myArgs [i].equals(((PyStringLiteralExpression)args[i]).getStringValue())) { + !myArgs[i].equals(((PyStringLiteralExpression)args[i]).getStringValue())) { argsMatch = false; break; } diff --git a/python/python-psi-api/src/com/jetbrains/python/inspections/PyInspectionExtension.java b/python/python-psi-api/src/com/jetbrains/python/inspections/PyInspectionExtension.java index aaab986d5c14..023b28fb4d3c 100644 --- a/python/python-psi-api/src/com/jetbrains/python/inspections/PyInspectionExtension.java +++ b/python/python-psi-api/src/com/jetbrains/python/inspections/PyInspectionExtension.java @@ -58,6 +58,7 @@ public abstract class PyInspectionExtension { /** * Enable "unresolved reference" inspection regardless of IDE type and initialized SDK. + * * @return true -- Enable forcibly, false -- disable forcibly, null -- act as usual. */ public Boolean overrideUnresolvedReferenceInspection(@NotNull PsiFile file) { @@ -124,5 +125,5 @@ public abstract class PyInspectionExtension { /** * @return Do not report "unused import" */ - public boolean ignoreUnusedImports(@NotNull PyImportedNameDefiner importNameDefiner) {return false;} + public boolean ignoreUnusedImports(@NotNull PyImportedNameDefiner importNameDefiner) { return false; } } diff --git a/python/python-psi-api/src/com/jetbrains/python/nameResolver/NameResolverTools.java b/python/python-psi-api/src/com/jetbrains/python/nameResolver/NameResolverTools.java index 38e80a86dd1d..cf0f42b75741 100644 --- a/python/python-psi-api/src/com/jetbrains/python/nameResolver/NameResolverTools.java +++ b/python/python-psi-api/src/com/jetbrains/python/nameResolver/NameResolverTools.java @@ -109,7 +109,8 @@ public final class NameResolverTools { * @param functionName function to find * @return parent call or null if not found */ - public static @Nullable PyCallExpression findCallExpParent(final @NotNull PsiElement anchor, final @NotNull FQNamesProvider functionName) { + public static @Nullable PyCallExpression findCallExpParent(final @NotNull PsiElement anchor, + final @NotNull FQNamesProvider functionName) { final PsiElement parent = PsiTreeUtil.findFirstParent(anchor, new MyFunctionCondition(functionName)); if (parent instanceof PyCallExpression) { return (PyCallExpression)parent; @@ -151,7 +152,7 @@ public final class NameResolverTools { /** * Checks if some string contains last component one of name * - * @param text test to check + * @param text test to check */ public static boolean isContainsName(final @NotNull String text, final @NotNull FQNamesProvider names) { for (final String lastComponent : getLastComponents(names)) { @@ -165,7 +166,7 @@ public final class NameResolverTools { /** * Checks if some file contains last component one of name * - * @param file file to check + * @param file file to check */ public static boolean isContainsName(final @NotNull PsiFile file, final @NotNull FQNamesProvider names) { return isContainsName(file.getText(), names); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PsiReferenceEx.java b/python/python-psi-api/src/com/jetbrains/python/psi/PsiReferenceEx.java index dfa86e2c7c70..c4354decc888 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PsiReferenceEx.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PsiReferenceEx.java @@ -24,5 +24,8 @@ import org.jetbrains.annotations.Nullable; public interface PsiReferenceEx extends PsiReference { @Nullable HighlightSeverity getUnresolvedHighlightSeverity(TypeEvalContext context); - @Nullable @Nls String getUnresolvedDescription(); + + @Nullable + @Nls + String getUnresolvedDescription(); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyAssignmentStatement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyAssignmentStatement.java index 16255bb721b7..63e1eff5de46 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyAssignmentStatement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyAssignmentStatement.java @@ -65,6 +65,7 @@ public interface PyAssignmentStatement extends PyAstAssignmentStatement, PyState *
* If RHS and LHS are mis-balanced, certain target or value expressions may be null. * If source is severely incorrect, the returned mapping is empty. + * * @return a list of [target, value] pairs; either part of a pair may be null, but not both. */ @Override @@ -77,5 +78,4 @@ public interface PyAssignmentStatement extends PyAstAssignmentStatement, PyState default @Nullable PyExpression getLeftHandSideExpression() { return (PyExpression)PyAstAssignmentStatement.super.getLeftHandSideExpression(); } - } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyClass.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyClass.java index 60420b6328f9..016427e14be9 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyClass.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyClass.java @@ -25,9 +25,10 @@ import java.util.Map; /** * Represents a class declaration in source. */ -public interface PyClass extends PyAstClass, PsiNameIdentifierOwner, PyCompoundStatement, PyDocStringOwner, StubBasedPsiElement, - ScopeOwner, PyDecoratable, PyTypedElement, PyQualifiedNameOwner, PyStatementListContainer, PyWithAncestors, - PyTypeParameterListOwner, PyDeprecatable { +public interface PyClass + extends PyAstClass, PsiNameIdentifierOwner, PyCompoundStatement, PyDocStringOwner, StubBasedPsiElement, + ScopeOwner, PyDecoratable, PyTypedElement, PyQualifiedNameOwner, PyStatementListContainer, PyWithAncestors, + PyTypeParameterListOwner, PyDeprecatable { PyClass[] EMPTY_ARRAY = new PyClass[0]; ArrayFactory ARRAY_FACTORY = count -> count == 0 ? EMPTY_ARRAY : new PyClass[count]; diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyClassPattern.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyClassPattern.java index 22d34954c6c0..a16cc4a0fc69 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyClassPattern.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyClassPattern.java @@ -9,7 +9,7 @@ import java.util.Set; public interface PyClassPattern extends PyAstClassPattern, PyPattern { Set SPECIAL_BUILTINS = Set.of( "bool", "bytearray", "bytes", "dict", "float", "frozenset", "int", "list", "set", "str", "tuple"); - + @Override default @NotNull PyReferenceExpression getClassNameReference() { return (PyReferenceExpression)PyAstClassPattern.super.getClassNameReference(); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyElement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyElement.java index 740a6c97d72e..fe6f6f5dae15 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyElement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyElement.java @@ -23,5 +23,4 @@ public interface PyElement extends PyAstElement { * An empty array to return cheaply without allocating it anew. */ PyElement[] EMPTY_ARRAY = new PyElement[0]; - } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyElementGenerator.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyElementGenerator.java index a01e7e368309..bac815558cd7 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyElementGenerator.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyElementGenerator.java @@ -30,15 +30,15 @@ public abstract class PyElementGenerator extends PyAstElementGenerator { /** * Creates a string literal, adding appropriate quotes, properly escaping characters inside. * - * @param destination where the literal is destined to; used to determine the encoding. - * @param unescaped the string - * @param preferUTF8 try to use UTF8 (would use ascii if false) + * @param destination where the literal is destined to; used to determine the encoding. + * @param unescaped the string + * @param preferUTF8 try to use UTF8 (would use ascii if false) * @param preferDoubleQuotes try to use double/single quotes * @return a newly created literal */ protected abstract PyStringLiteralExpression createStringLiteralFromString(@Nullable PsiFile destination, - @NotNull String unescaped, - boolean preferUTF8, boolean preferDoubleQuotes); + @NotNull String unescaped, + boolean preferUTF8, boolean preferDoubleQuotes); public abstract PyStringLiteralExpression createStringLiteralFromString(@NotNull String unescaped, boolean preferDoubleQuotes); @@ -55,11 +55,13 @@ public abstract class PyElementGenerator extends PyAstElementGenerator { @NotNull PyExpression rightOperand); @Override - public @NotNull PyExpression createExpressionFromText(@NotNull LanguageLevel languageLevel, @NotNull String text) throws IncorrectOperationException { + public @NotNull PyExpression createExpressionFromText(@NotNull LanguageLevel languageLevel, @NotNull String text) + throws IncorrectOperationException { return (PyExpression)super.createExpressionFromText(languageLevel, text); } - public abstract @NotNull PyPattern createPatternFromText(@NotNull LanguageLevel languageLevel, @NotNull String text) throws IncorrectOperationException; + public abstract @NotNull PyPattern createPatternFromText(@NotNull LanguageLevel languageLevel, @NotNull String text) + throws IncorrectOperationException; /** * Adds elements to list inserting required commas. @@ -131,9 +133,9 @@ public abstract class PyElementGenerator extends PyAstElementGenerator { * @return created {@link PyFromImportStatement} */ public abstract @NotNull PyFromImportStatement createFromImportStatement(@NotNull LanguageLevel languageLevel, - @NotNull String qualifier, - @NotNull String name, - @Nullable String alias); + @NotNull String qualifier, + @NotNull String name, + @Nullable String alias); /** * Creates import statement of form {@code import name as alias}. @@ -144,8 +146,8 @@ public abstract class PyElementGenerator extends PyAstElementGenerator { * @return created {@link PyImportStatement} */ public abstract @NotNull PyImportStatement createImportStatement(@NotNull LanguageLevel languageLevel, - @NotNull String name, - @Nullable String alias); + @NotNull String name, + @Nullable String alias); public abstract @NotNull PyEllipsisLiteralExpression createEllipsis(); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyExceptPart.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyExceptPart.java index 5fcdb6498a40..dda501d514f2 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyExceptPart.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyExceptPart.java @@ -6,7 +6,8 @@ import com.jetbrains.python.ast.PyAstExceptPart; import com.jetbrains.python.psi.stubs.PyExceptPartStub; import org.jetbrains.annotations.Nullable; -public interface PyExceptPart extends PyAstExceptPart, PyElement, StubBasedPsiElement, PyNamedElementContainer, PyStatementPart { +public interface PyExceptPart + extends PyAstExceptPart, PyElement, StubBasedPsiElement, PyNamedElementContainer, PyStatementPart { PyExceptPart[] EMPTY_ARRAY = new PyExceptPart[0]; @Override diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyForPart.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyForPart.java index 60c159743c74..e2b3ed127dcc 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyForPart.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyForPart.java @@ -23,5 +23,4 @@ public interface PyForPart extends PyAstForPart, PyStatementPart { default @Nullable PyExpression getSource() { return (PyExpression)PyAstForPart.super.getSource(); } - } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyFormattedStringElement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyFormattedStringElement.java index 7ce70a61e08b..239f22801247 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyFormattedStringElement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyFormattedStringElement.java @@ -8,10 +8,10 @@ import java.util.List; /** * Represents an f-string, a special kind of interpolated string literal introduced in Python 3.6. - * + *

* Unlike {@link PyPlainStringElement} these elements are composite and consist of several kinds of tokens * and normal PSI trees for embedded expressions. - * + * * @see com.jetbrains.python.PyTokenTypes#FSTRING_START * @see com.jetbrains.python.PyTokenTypes#FSTRING_TEXT * @see PyFStringFragment diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyFromImportStatement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyFromImportStatement.java index b52799fb44e1..426702b51afc 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyFromImportStatement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyFromImportStatement.java @@ -14,10 +14,12 @@ import java.util.List; /** * Describes "from ... import" statements. */ -public interface PyFromImportStatement extends PyAstFromImportStatement, PyImportStatementBase, StubBasedPsiElement, - PyImplicitImportNameDefiner { +public interface PyFromImportStatement + extends PyAstFromImportStatement, PyImportStatementBase, StubBasedPsiElement, + PyImplicitImportNameDefiner { /** * Returns a reference the module from which import is required. + * * @return reference to module. If the 'from' reference is relative and consists entirely of dots, null is returned. */ @Override diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyFunction.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyFunction.java index 2eec81d318b1..abfb1f4a854d 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyFunction.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyFunction.java @@ -41,9 +41,9 @@ public interface PyFunction extends PyAstFunction, StubBasedPsiElementreturn statements (including implicit returns) and yield expression. - * In contrast with {@link TypeEvalContext#getReturnType(PyCallable)} does not consider + * In contrast with {@link TypeEvalContext#getReturnType(PyCallable)} does not consider * return type annotations or any other {@link PyTypeProvider}. - * + * * @apiNote Does not cache the result. */ @ApiStatus.Internal @@ -55,8 +55,8 @@ public interface PyFunction extends PyAstFunction, StubBasedPsiElementPEP-0232 + * * @return assignment statements for function attributes */ @NotNull diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyImportStatement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyImportStatement.java index ad9b0d1bf325..72e2f35bb763 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyImportStatement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyImportStatement.java @@ -6,5 +6,6 @@ import com.jetbrains.python.ast.PyAstImportStatement; import com.jetbrains.python.psi.stubs.PyImportStatementStub; -public interface PyImportStatement extends PyAstImportStatement, PyImportStatementBase, StubBasedPsiElement, PyImplicitImportNameDefiner { +public interface PyImportStatement + extends PyAstImportStatement, PyImportStatementBase, StubBasedPsiElement, PyImplicitImportNameDefiner { } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyKeyValueExpression.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyKeyValueExpression.java index e8f6b4fb7afd..309213c6a211 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyKeyValueExpression.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyKeyValueExpression.java @@ -7,7 +7,7 @@ import org.jetbrains.annotations.Nullable; public interface PyKeyValueExpression extends PyAstKeyValueExpression, PyExpression { - PyKeyValueExpression[] EMPTY_ARRAY = new PyKeyValueExpression[0]; + PyKeyValueExpression[] EMPTY_ARRAY = new PyKeyValueExpression[0]; @Override default @NotNull PyExpression getKey() { diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyNamedParameter.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyNamedParameter.java index cd0ee242f74b..66e1288a615e 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyNamedParameter.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyNamedParameter.java @@ -15,8 +15,9 @@ import org.jetbrains.annotations.Nullable; /** * Represents a named parameter, as opposed to a tuple parameter. */ -public interface PyNamedParameter extends PyAstNamedParameter, PyParameter, PsiNamedElement, PsiNameIdentifierOwner, PyExpression, PyTypeCommentOwner, - PyAnnotationOwner, StubBasedPsiElement { +public interface PyNamedParameter + extends PyAstNamedParameter, PyParameter, PsiNamedElement, PsiNameIdentifierOwner, PyExpression, PyTypeCommentOwner, + PyAnnotationOwner, StubBasedPsiElement { @Override default @Nullable PyExpression getDefaultValue() { diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyPsiFacade.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyPsiFacade.java index 3170339f98ba..163103d8eab5 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyPsiFacade.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyPsiFacade.java @@ -20,7 +20,8 @@ public abstract class PyPsiFacade { return project.getService(PyPsiFacade.class); } - public abstract @NotNull List resolveQualifiedName(@NotNull QualifiedName name, @NotNull PyQualifiedNameResolveContext context); + public abstract @NotNull List resolveQualifiedName(@NotNull QualifiedName name, + @NotNull PyQualifiedNameResolveContext context); public abstract @NotNull PyQualifiedNameResolveContext createResolveContextFromFoothold(@NotNull PsiElement foothold); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java index f4e61dca1251..dc36e5199e50 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyQualifiedNameOwner.java @@ -16,5 +16,6 @@ public interface PyQualifiedNameOwner extends PyAstQualifiedNameOwner, PyElement * is contained inside an element that doesn't have a qualified name. */ @Nullable - @NlsSafe String getQualifiedName(); + @NlsSafe + String getQualifiedName(); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyReferenceExpression.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyReferenceExpression.java index f7b1c961862e..49d1f18c7740 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyReferenceExpression.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyReferenceExpression.java @@ -43,7 +43,7 @@ public interface PyReferenceExpression extends PyAstReferenceExpression, PyQuali * Note: the returned list does not contain null values. */ default @NotNull List multiFollowAssignmentsChain(@NotNull PyResolveContext resolveContext) { - return multiFollowAssignmentsChain(resolveContext, __->true); + return multiFollowAssignmentsChain(resolveContext, __ -> true); } /** @@ -51,7 +51,7 @@ public interface PyReferenceExpression extends PyAstReferenceExpression, PyQuali * Starts at this, expecting it to resolve to a target of an assignment. * * @param resolveContext resolve context - * @param follow predicate to test if target should be followed + * @param follow predicate to test if target should be followed * @return the values that could be assigned to this element via a chain of assignments, or an empty list. * Note: the returned list does not contain null values. */ diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PySequencePattern.kt b/python/python-psi-api/src/com/jetbrains/python/psi/PySequencePattern.kt index b5b0420dd514..0228670eb2ef 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PySequencePattern.kt +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PySequencePattern.kt @@ -5,6 +5,6 @@ import com.jetbrains.python.ast.PyAstSequencePattern import com.jetbrains.python.ast.findChildrenByClass interface PySequencePattern : PyAstSequencePattern, PyPattern { - val elements: List + val elements: List get() = findChildrenByClass(PyPattern::class.java).toList() } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyStarImportElement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyStarImportElement.java index b807b5864bef..baac4cf8b547 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyStarImportElement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyStarImportElement.java @@ -22,5 +22,6 @@ import com.jetbrains.python.psi.stubs.PyStarImportElementStub; /** * Marks the star in "from foo import *". */ -public interface PyStarImportElement extends PyAstStarImportElement, PyImplicitImportNameDefiner, StubBasedPsiElement { +public interface PyStarImportElement + extends PyAstStarImportElement, PyImplicitImportNameDefiner, StubBasedPsiElement { } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyStatement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyStatement.java index 325b7c82aa04..577005be40f9 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyStatement.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyStatement.java @@ -21,5 +21,5 @@ import com.jetbrains.python.ast.PyAstStatement; * Everything that may be an element of a statement list. */ public interface PyStatement extends PyAstStatement, PyElement { - PyStatement[] EMPTY_ARRAY = new PyStatement[0]; + PyStatement[] EMPTY_ARRAY = new PyStatement[0]; } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java index 41998ca7dbb9..6a231b6e4ce9 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java @@ -10,7 +10,7 @@ import java.util.List; /** * A string literal expression can consist of a number of implicitly concatenated string literals - * each with its own set of quotes and prefixes. For instance, the following string literal expression + * each with its own set of quotes and prefixes. For instance, the following string literal expression * in the right hand side of the assignment: *

*

@@ -27,13 +27,14 @@ import java.util.List;
  * decoded value, etc.
  *
  * @see 
- *   https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation
+ * https://docs.python.org/3/reference/lexical_analysis.html#string-literal-concatenation
  * @see #getStringElements()
  * @see PyStringElement
  * @see PyPlainStringElement
  * @see PyFormattedStringElement
  */
-public interface PyStringLiteralExpression extends PyAstStringLiteralExpression, PyLiteralExpression, StringLiteralExpression, PsiLanguageInjectionHost {
+public interface PyStringLiteralExpression
+  extends PyAstStringLiteralExpression, PyLiteralExpression, StringLiteralExpression, PsiLanguageInjectionHost {
   /**
    * Returns a list of implicitly concatenated string elements composing this literal expression.
    */
diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PySubscriptionExpression.java b/python/python-psi-api/src/com/jetbrains/python/psi/PySubscriptionExpression.java
index 2dcf01f7a2a9..b25149175243 100644
--- a/python/python-psi-api/src/com/jetbrains/python/psi/PySubscriptionExpression.java
+++ b/python/python-psi-api/src/com/jetbrains/python/psi/PySubscriptionExpression.java
@@ -6,7 +6,8 @@ import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 
-public interface PySubscriptionExpression extends PyAstSubscriptionExpression, PyQualifiedExpression, PyCallSiteExpression, PyReferenceOwner {
+public interface PySubscriptionExpression
+  extends PyAstSubscriptionExpression, PyQualifiedExpression, PyCallSiteExpression, PyReferenceOwner {
 
   /**
    * @return For {@code spam[x][y][n]} will return {@code spam} regardless number of its dimensions
diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeAliasStatement.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeAliasStatement.java
index 48a2ff4d2d9c..7c6c987429b7 100644
--- a/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeAliasStatement.java
+++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeAliasStatement.java
@@ -11,8 +11,9 @@ import org.jetbrains.annotations.Nullable;
 /**
  * Represents Type Alias Statement added in PEP 695
  */
-public interface PyTypeAliasStatement extends PyAstTypeAliasStatement, PyStatement, PsiNameIdentifierOwner, PyTypeParameterListOwner, PyTypedElement,
-                                              StubBasedPsiElement, PyQualifiedNameOwner, ScopeOwner {
+public interface PyTypeAliasStatement
+  extends PyAstTypeAliasStatement, PyStatement, PsiNameIdentifierOwner, PyTypeParameterListOwner, PyTypedElement,
+          StubBasedPsiElement, PyQualifiedNameOwner, ScopeOwner {
 
   @Override
   default @Nullable PyExpression getTypeExpression() {
diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeParameter.java b/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeParameter.java
index 011115cf2261..cb6f9fd7cf23 100644
--- a/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeParameter.java
+++ b/python/python-psi-api/src/com/jetbrains/python/psi/PyTypeParameter.java
@@ -11,7 +11,8 @@ import org.jetbrains.annotations.Nullable;
  * Represents a Type Parameter that can be a part of {@link PyTypeParameterList}
* For more information see PEP 695 */ -public interface PyTypeParameter extends PyAstTypeParameter, PyElement, PsiNameIdentifierOwner, PyTypedElement, PyQualifiedNameOwner, StubBasedPsiElement { +public interface PyTypeParameter extends PyAstTypeParameter, PyElement, PsiNameIdentifierOwner, PyTypedElement, PyQualifiedNameOwner, + StubBasedPsiElement { @Override default @Nullable PyExpression getBoundExpression() { diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/impl/PyPsiUtils.java b/python/python-psi-api/src/com/jetbrains/python/psi/impl/PyPsiUtils.java index 0d0c2a3b58bf..b309d10ca73f 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/impl/PyPsiUtils.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/impl/PyPsiUtils.java @@ -59,6 +59,7 @@ public final class PyPsiUtils { /** * Finds first sibling that is neither comment, nor whitespace before given element. + * * @param strict prohibit returning element itself */ public static @Nullable PsiElement getPrevNonCommentSibling(@Nullable PsiElement start, boolean strict) { @@ -109,6 +110,7 @@ public final class PyPsiUtils { /** * Finds first sibling that is neither comment, nor whitespace after given element. + * * @param strict prohibit returning element itself */ public static @Nullable PsiElement getNextNonCommentSibling(@Nullable PsiElement start, boolean strict) { @@ -117,6 +119,7 @@ public final class PyPsiUtils { /** * Finds first token after given element that doesn't consist solely of spaces and is not empty (e.g. error marker). + * * @param ignoreComments ignore commentaries as well */ public static @Nullable PsiElement getNextSignificantLeaf(@Nullable PsiElement element, boolean ignoreComments) { @@ -128,6 +131,7 @@ public final class PyPsiUtils { /** * Finds first token before given element that doesn't consist solely of spaces and is not empty (e.g. error marker). + * * @param ignoreComments ignore commentaries as well */ public static @Nullable PsiElement getPrevSignificantLeaf(@Nullable PsiElement element, boolean ignoreComments) { @@ -261,7 +265,8 @@ public final class PyPsiUtils { public static boolean isMethodContext(final PsiElement element) { final PsiNamedElement parent = PsiTreeUtil.getParentOfType(element, PyFile.class, PyFunction.class, PyClass.class); // In case if element is inside method which is inside class - if (parent instanceof PyFunction && PsiTreeUtil.getParentOfType(parent, PyFile.class, PyFunction.class, PyClass.class) instanceof PyClass) { + if (parent instanceof PyFunction && + PsiTreeUtil.getParentOfType(parent, PyFile.class, PyFunction.class, PyClass.class) instanceof PyClass) { return true; } return false; @@ -302,6 +307,7 @@ public final class PyPsiUtils { /** * Returns comments preceding given elements as pair of the first and the last such comments. Comments should not be * separated by any empty line. + * * @param element element comments should be adjacent to * @return described range or {@code null} if there are no such comments */ @@ -348,7 +354,7 @@ public final class PyPsiUtils { * def func(): * pass * }
- * + *

* Note that in the following case it will additionally return an empty list of comments as the last element * to distinguish between the cases when there is a blank line above the provided element and when there is not. * diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContext.java b/python/python-psi-api/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContext.java index a40b0bbde759..21f20cc547a4 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContext.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContext.java @@ -32,42 +32,62 @@ import org.jetbrains.annotations.Nullable; public interface PyQualifiedNameResolveContext { @Nullable PsiElement getFoothold(); + int getRelativeLevel(); + @Nullable Sdk getSdk(); + @Nullable Module getModule(); + @NotNull Project getProject(); + boolean getWithoutRoots(); + boolean getWithoutForeign(); + boolean getWithoutStubs(); + @NotNull PsiManager getPsiManager(); + boolean getWithMembers(); + boolean getWithPlainDirectories(); + boolean getVisitAllModules(); + @Nullable Sdk getEffectiveSdk(); boolean isValid(); + @Nullable PsiFile getFootholdFile(); + @Nullable PsiDirectory getContainingDirectory(); @NotNull PyQualifiedNameResolveContext copyWithoutForeign(); + @NotNull PyQualifiedNameResolveContext copyWithMembers(); + @NotNull PyQualifiedNameResolveContext copyWithPlainDirectories(); + @NotNull PyQualifiedNameResolveContext copyWithRelative(int relativeLevel); + @NotNull PyQualifiedNameResolveContext copyWithoutRoots(); + @NotNull PyQualifiedNameResolveContext copyWithRoots(); + @NotNull PyQualifiedNameResolveContext copyWithoutStubs(); } \ No newline at end of file diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFileStub.java b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFileStub.java index aadbb82d1990..090797ff4a71 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFileStub.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFileStub.java @@ -10,6 +10,8 @@ import java.util.List; public interface PyFileStub extends PsiFileStub { List getDunderAll(); + BitSet getFutureFeatures(); + String getDeprecationMessage(); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFunctionStub.java b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFunctionStub.java index c98429479c27..87d2c5f1e90f 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFunctionStub.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyFunctionStub.java @@ -6,9 +6,13 @@ import com.jetbrains.python.psi.PyFunction; public interface PyFunctionStub extends NamedStub, PyAnnotationOwnerStub, PyTypeCommentOwnerStub, PyVersionSpecificStub { String getDocString(); + String getDeprecationMessage(); + boolean isAsync(); + boolean isGenerator(); + default boolean onlyRaisesNotImplementedError() { return false; } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyImportElementStub.java b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyImportElementStub.java index aa0f5c578906..1f7c67397896 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyImportElementStub.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyImportElementStub.java @@ -2,14 +2,14 @@ package com.jetbrains.python.psi.stubs; import com.intellij.psi.stubs.StubElement; -import com.jetbrains.python.psi.PyImportElement; import com.intellij.psi.util.QualifiedName; +import com.jetbrains.python.psi.PyImportElement; import org.jetbrains.annotations.Nullable; public interface PyImportElementStub extends StubElement { @Nullable QualifiedName getImportedQName(); - + String getAsName(); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyNamedParameterStub.java b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyNamedParameterStub.java index 631c84a0fd51..d386d42156a4 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyNamedParameterStub.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/stubs/PyNamedParameterStub.java @@ -7,6 +7,7 @@ import org.jetbrains.annotations.Nullable; public interface PyNamedParameterStub extends NamedStub, PyAnnotationOwnerStub, PyTypeCommentOwnerStub { boolean isPositionalContainer(); + boolean isKeywordContainer(); default @Nullable String getDefaultValueText() { diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyCallableParameter.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyCallableParameter.java index 8c15dff9b259..6f802c5be754 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyCallableParameter.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyCallableParameter.java @@ -18,7 +18,8 @@ public interface PyCallableParameter { * Returns null if the parameter is tuple or star, or name is unknown. */ @Nullable - @Nls String getName(); + @Nls + String getName(); /** * @param context type evaluation context diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassLikeType.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassLikeType.java index ce1b026a92f4..242fb6f3e849 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassLikeType.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassLikeType.java @@ -32,6 +32,7 @@ public interface PyClassLikeType extends PyCallableType, PyWithAncestors, PyInst boolean inherited); // TODO: Pull to PyType at next iteration + /** * Visits all class members. This method is better then bare class since it uses type info and supports not only classes but * class-like structures as well. Consider using user-friendly wrapper {@link PyTypeUtil#getMembersOfType(PyClassLikeType, Class, boolean, TypeEvalContext)} diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassMembersProviderBase.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassMembersProviderBase.java index e49fe681550e..724056469c89 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassMembersProviderBase.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyClassMembersProviderBase.java @@ -39,9 +39,9 @@ public class PyClassMembersProviderBase implements PyClassMembersProvider { * @return found member or null */ public static @Nullable PsiElement resolveMemberByName(@NotNull Collection members, - @NotNull String name, - @NotNull PsiElement context, - @NotNull PyResolveContext resolveContext) { + @NotNull String name, + @NotNull PsiElement context, + @NotNull PyResolveContext resolveContext) { for (PyCustomMember member : members) { if (member.getName().equals(name)) { return member.resolve(context, resolveContext); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyInstantiableType.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyInstantiableType.java index 9bb670c7c606..eb329ef7ef18 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyInstantiableType.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyInstantiableType.java @@ -18,8 +18,8 @@ package com.jetbrains.python.psi.types; import org.jetbrains.annotations.NotNull; /** - * A type that can describe either particular instantiated instance of a class or a class itself. - * + * A type that can describe either particular instantiated instance of a class or a class itself. + * * @author Mikhail Golubev */ public interface PyInstantiableType> extends PyType { diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyModuleMembersProvider.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyModuleMembersProvider.java index bf496e036ccf..6794dd5b9e6c 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyModuleMembersProvider.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyModuleMembersProvider.java @@ -27,7 +27,9 @@ public abstract class PyModuleMembersProvider { * @param context type evaluation context * @return provided members */ - public @NotNull Collection getMembers(@NotNull PyFile module, @NotNull PointInImport point, @NotNull TypeEvalContext context) { + public @NotNull Collection getMembers(@NotNull PyFile module, + @NotNull PointInImport point, + @NotNull TypeEvalContext context) { final VirtualFile vFile = module.getVirtualFile(); if (vFile != null) { final String qName = PyPsiFacade.getInstance(module.getProject()).findShortestImportableName(vFile, module); @@ -64,6 +66,6 @@ public abstract class PyModuleMembersProvider { * @return provided members */ protected abstract @NotNull Collection getMembersByQName(@NotNull PyFile module, - @NotNull String qName, - @NotNull TypeEvalContext context); + @NotNull String qName, + @NotNull TypeEvalContext context); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyNeverType.kt b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyNeverType.kt index 13067098759b..fbfb542eb050 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyNeverType.kt +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyNeverType.kt @@ -8,7 +8,7 @@ import com.jetbrains.python.psi.PyExpression import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.RatedResolveResult -class PyNeverType private constructor(private val name: String): PyType { +class PyNeverType private constructor(private val name: String) : PyType { companion object { @JvmField val NEVER: PyNeverType = PyNeverType("Never") @JvmField val NO_RETURN: PyNeverType = PyNeverType("NoReturn") @@ -16,7 +16,7 @@ class PyNeverType private constructor(private val name: String): PyType { @JvmStatic fun PyType?.toNoReturnIfNeeded(): PyType? = if (this === NEVER) NO_RETURN else this } - + override fun getName(): String = name override fun isBuiltin(): Boolean = true override fun assertValid(message: String?) {} @@ -30,7 +30,7 @@ class PyNeverType private constructor(private val name: String): PyType { direction: AccessDirection, resolveContext: PyResolveContext, ): List = emptyList() - + override fun getCompletionVariants( completionPrefix: String?, location: PsiElement?, diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeProviderBase.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeProviderBase.java index bb809c0d4135..0d4c65553627 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeProviderBase.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeProviderBase.java @@ -35,7 +35,9 @@ public class PyTypeProviderBase implements PyTypeProvider { } @Override - public @Nullable Ref getParameterType(@NotNull PyNamedParameter param, @NotNull PyFunction func, @NotNull TypeEvalContext context) { + public @Nullable Ref getParameterType(@NotNull PyNamedParameter param, + @NotNull PyFunction func, + @NotNull TypeEvalContext context) { return null; } @@ -45,7 +47,9 @@ public class PyTypeProviderBase implements PyTypeProvider { } @Override - public @Nullable Ref getCallType(@NotNull PyFunction function, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { + public @Nullable Ref getCallType(@NotNull PyFunction function, + @NotNull PyCallSiteExpression callSite, + @NotNull TypeEvalContext context) { final ReturnTypeDescriptor descriptor; synchronized (myMethodToReturnTypeMap) { descriptor = myMethodToReturnTypeMap.get(function.getName()); @@ -120,7 +124,9 @@ public class PyTypeProviderBase implements PyTypeProvider { myStringToReturnTypeMap.put(classQualifiedName, callback); } - public @Nullable Ref get(@NotNull PyFunction function, @Nullable PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { + public @Nullable Ref get(@NotNull PyFunction function, + @Nullable PyCallSiteExpression callSite, + @NotNull TypeEvalContext context) { return Optional .ofNullable(function.getContainingClass()) .map(pyClass -> myStringToReturnTypeMap.get(pyClass.getQualifiedName())) diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeVisitor.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeVisitor.java index fae195586513..815da212df12 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeVisitor.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/PyTypeVisitor.java @@ -12,7 +12,7 @@ import org.jetbrains.annotations.Nullable; * Because the "unknown" type is historically represented as {@code null} in the type system, {@code PyTypeVisitor.visitPyType(type, visitor)} * should be used instead of direct {@code type.acceptTypeVisitor(visitor)} to properly account for possible {@code null} values. *

- * This class gives access only to the types declared in the intellij.python.psi module. + * This class gives access only to the types declared in the intellij.python.psi module. * Most actual implementations should extend {@link PyTypeVisitorExt}. *

* There are helper {@link PyRecursiveTypeVisitor} and {@link PyCloningTypeVisitor} for recursive type @@ -21,7 +21,7 @@ import org.jetbrains.annotations.Nullable; * @see PyRecursiveTypeVisitor * @see PyCloningTypeVisitor * @see PyType#acceptTypeVisitor(PyTypeVisitor) - * @see #visit(PyType, PyTypeVisitor) + * @see #visit(PyType, PyTypeVisitor) * @see #visitUnknownType() */ @ApiStatus.Experimental @@ -74,7 +74,7 @@ public abstract class PyTypeVisitor { public T visitPyCallableParameterListType(@NotNull PyCallableParameterListType callableParameterListType) { return visitPyType(callableParameterListType); } - + public T visitPyNeverType(@NotNull PyNeverType neverType) { return visitPyType(neverType); } diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalConstraints.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalConstraints.java index aba34515b7f9..c68322f2859a 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalConstraints.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalConstraints.java @@ -39,7 +39,7 @@ public final class TypeEvalConstraints { if (this == o) return true; if (!(o instanceof TypeEvalConstraints that)) return false; - return myAllowDataFlow == that.myAllowDataFlow && + return myAllowDataFlow == that.myAllowDataFlow && myAllowStubToAST == that.myAllowStubToAST && myAllowCallContext == that.myAllowCallContext && Objects.equals(myOrigin, that.myOrigin); diff --git a/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalContext.java b/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalContext.java index 0e08b2f16fb1..936c3625b855 100644 --- a/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalContext.java +++ b/python/python-psi-api/src/com/jetbrains/python/psi/types/TypeEvalContext.java @@ -268,7 +268,9 @@ public sealed class TypeEvalContext { myConstraints.myAllowStubToAST, myConstraints.myAllowCallContext, // code completion will always have a new PsiFile, use original file instead - myConstraints.myOrigin != null ? myConstraints.myOrigin.getOriginalFile() : null); + myConstraints.myOrigin != null + ? myConstraints.myOrigin.getOriginalFile() + : null); return project.getService(TypeEvalContextCache.class).getLibraryContext(new LibraryTypeEvalContext(constraints)); } @@ -430,7 +432,7 @@ public sealed class TypeEvalContext { } private static class PyNullType implements PyType { - private PyNullType() {} + private PyNullType() { } @Override public @Nullable List resolveMember(@NotNull String name, diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyAssertTypeInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyAssertTypeInspection.html index df302f1b78dd..65fd03838c1d 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyAssertTypeInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyAssertTypeInspection.html @@ -1,8 +1,8 @@

- Checks typing.assert_type(val, typ, /) calls and reports cases when val's inferred type is not - typ. + Checks typing.assert_type(val, typ, /) calls and reports cases when val's inferred type is not + typ.

Example:


diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyInvalidCastInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyInvalidCastInspection.html
index af47776426d0..ab14639a29fe 100644
--- a/python/python-psi-impl/resources/inspectionDescriptions/PyInvalidCastInspection.html
+++ b/python/python-psi-impl/resources/inspectionDescriptions/PyInvalidCastInspection.html
@@ -6,7 +6,8 @@
   and typing.cast does not dynamically validate the type.

This check applies even to types that could theoretically have a common descendant. - For example, it will flag a cast between two sibling classes Left and Right that both inherit from Top, + For example, it will flag a cast between two sibling classes Left and Right that both inherit from + Top, because there is no direct inheritance relationship between them.

Example:

diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyMethodFirstArgAssignmentInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyMethodFirstArgAssignmentInspection.html index baab0f218925..89afe470fc0b 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyMethodFirstArgAssignmentInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyMethodFirstArgAssignmentInspection.html @@ -14,4 +14,5 @@ class Account:

As a fix, you might want to check and modify the algorithm to ensure that reassignment is needed. If everything is correct, you can invoke intention actions for this code and opt to ignore the warning.

- + + diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyTypeCheckerInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyTypeCheckerInspection.html index 16677cefe50f..911505347f21 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyTypeCheckerInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyTypeCheckerInspection.html @@ -1,6 +1,7 @@ -

Reports type errors in function call expressions, targets, and return values. In a dynamically typed language, this is possible in a limited number of cases.

+

Reports type errors in function call expressions, targets, and return values. In a dynamically typed language, this is possible in a + limited number of cases.

Types of function parameters can be specified in docstrings or in Python 3 function annotations.

Example:

diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyTypeHintsInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyTypeHintsInspection.html index 7a0b4fbbc160..cf09c38126c7 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyTypeHintsInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyTypeHintsInspection.html @@ -17,6 +17,7 @@ def c(p1, p2): # Type signature has too many arguments # type: (int) -> int pass
-

Available quick-fixes offer various actions. You can rename, remove, or move problematic elements. You can also manually modify type declarations to ensure no warning is shown.

+

Available quick-fixes offer various actions. You can rename, remove, or move problematic elements. You can also manually modify type + declarations to ensure no warning is shown.

\ No newline at end of file diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyUnreachableCodeInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyUnreachableCodeInspection.html index b5047a645ae0..5023a2839159 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyUnreachableCodeInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyUnreachableCodeInspection.html @@ -10,4 +10,5 @@ else:

As a fix, you might want to check and modify the algorithm to ensure it implements the expected logic.

- + + diff --git a/python/python-psi-impl/resources/inspectionDescriptions/PyUnusedLocalInspection.html b/python/python-psi-impl/resources/inspectionDescriptions/PyUnusedLocalInspection.html index a8cf9eeedfb1..6cc9ba8651e0 100644 --- a/python/python-psi-impl/resources/inspectionDescriptions/PyUnusedLocalInspection.html +++ b/python/python-psi-impl/resources/inspectionDescriptions/PyUnusedLocalInspection.html @@ -3,4 +3,5 @@

Reports local variables, parameters, and functions that are locally defined, but not used name in a function.

- + + diff --git a/python/python-psi-impl/resources/intentionDescriptions/PyConvertToFStringIntention/description.html b/python/python-psi-impl/resources/intentionDescriptions/PyConvertToFStringIntention/description.html index 24616ef7baf2..e0304623bb87 100644 --- a/python/python-psi-impl/resources/intentionDescriptions/PyConvertToFStringIntention/description.html +++ b/python/python-psi-impl/resources/intentionDescriptions/PyConvertToFStringIntention/description.html @@ -5,7 +5,8 @@ This intention converts string formatting via format() method and f -F-strings provide a way to embed expressions inside string literals, using a minimal syntax. See more details in PEP-498. +F-strings provide a way to embed expressions inside string literals, using a minimal syntax. See more details in PEP-498. \ No newline at end of file diff --git a/python/python-psi-impl/resources/intentionDescriptions/PyConvertTypeCommentToVariableAnnotationIntention/description.html b/python/python-psi-impl/resources/intentionDescriptions/PyConvertTypeCommentToVariableAnnotationIntention/description.html index 8660a347b511..b3cb94dc02f4 100644 --- a/python/python-psi-impl/resources/intentionDescriptions/PyConvertTypeCommentToVariableAnnotationIntention/description.html +++ b/python/python-psi-impl/resources/intentionDescriptions/PyConvertTypeCommentToVariableAnnotationIntention/description.html @@ -1,7 +1,8 @@ -Converts PEP-484 type comments to Python 3.6 variable annotations. +Converts PEP-484 type comments to Python 3.6 variable annotations. \ No newline at end of file diff --git a/python/python-psi-impl/src/com/jetbrains/python/PyNewStyleStringFormatParser.java b/python/python-psi-impl/src/com/jetbrains/python/PyNewStyleStringFormatParser.java index f4ac86bbd582..387f234c5527 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PyNewStyleStringFormatParser.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PyNewStyleStringFormatParser.java @@ -116,7 +116,7 @@ public final class PyNewStyleStringFormatParser { int autoFieldNumber = myImplicitlyNumberedFieldsCounter; // in the order of appearance inside a field - final IntList attrAndLookupBounds=new IntArrayList(); + final IntList attrAndLookupBounds = new IntArrayList(); int conversionStart = -1; int formatSpecStart = -1; final List nestedFields = new ArrayList<>(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/PyPsiBundle.java b/python/python-psi-impl/src/com/jetbrains/python/PyPsiBundle.java index 255ad83d9594..916fbbf48cb1 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PyPsiBundle.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PyPsiBundle.java @@ -33,7 +33,8 @@ public final class PyPsiBundle extends DynamicBundle { return INSTANCE.getMessage(key, params); } - public static @NotNull Supplier<@Nls String> messagePointer(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, Object @NotNull ... params) { + public static @NotNull Supplier<@Nls String> messagePointer(@NotNull @PropertyKey(resourceBundle = BUNDLE) String key, + Object @NotNull ... params) { return INSTANCE.getLazyMessage(key, params); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/PyPsiPackageUtil.kt b/python/python-psi-impl/src/com/jetbrains/python/PyPsiPackageUtil.kt index 9d4cf424a36d..4ed9fbcfa2d6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PyPsiPackageUtil.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/PyPsiPackageUtil.kt @@ -38,7 +38,7 @@ object PyPsiPackageUtil { return buildMap { try { val resourceAsStream = requireNotNull(PyPsiPackageUtil::class.java.getClassLoader().getResourceAsStream("tools/packages")) - { "tool/packages is missed in distribution "} + { "tool/packages is missed in distribution " } for (line in ResourceUtil.loadText(resourceAsStream).lines()) { val split = line.trim().split(" ") check(split.size == 2) { "Each line should contain exactly two names: $line" } diff --git a/python/python-psi-impl/src/com/jetbrains/python/PyStringFormatParser.java b/python/python-psi-impl/src/com/jetbrains/python/PyStringFormatParser.java index 467460e5fb5d..7c5d3d26fa53 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PyStringFormatParser.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PyStringFormatParser.java @@ -289,8 +289,8 @@ public class PyStringFormatParser { myPos = 0; while (myPos < myLiteral.length()) { int next = myLiteral.indexOf('%', myPos); - while(next >= 0 && next < myLiteral.length()-1 && myLiteral.charAt(next+1) == '%') { - next = myLiteral.indexOf('%', next+2); + while (next >= 0 && next < myLiteral.length() - 1 && myLiteral.charAt(next + 1) == '%') { + next = myLiteral.indexOf('%', next + 2); } if (next < 0) break; if (next > myPos) { @@ -474,7 +474,7 @@ public class PyStringFormatParser { chunk.setMappingKey(myLiteral.substring(myPos + 1, mappingEnd)); myPos = mappingEnd + 1; } - else { + else { chunk.setAutoPosition(mySubstitutionsCount); mySubstitutionsCount++; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/PythonDocumentationHighlightingService.kt b/python/python-psi-impl/src/com/jetbrains/python/PythonDocumentationHighlightingService.kt index b595d9132238..3848871f6fa3 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PythonDocumentationHighlightingService.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/PythonDocumentationHighlightingService.kt @@ -7,7 +7,7 @@ import org.jetbrains.annotations.ApiStatus @ApiStatus.Internal open class PythonDocumentationHighlightingService { - companion object{ + companion object { @JvmStatic fun getInstance(): PythonDocumentationHighlightingService { return service() diff --git a/python/python-psi-impl/src/com/jetbrains/python/PythonParserDefinition.java b/python/python-psi-impl/src/com/jetbrains/python/PythonParserDefinition.java index 4f82533d1afa..aa34be83d7c8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PythonParserDefinition.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PythonParserDefinition.java @@ -75,5 +75,4 @@ public class PythonParserDefinition implements ParserDefinition { // see LanguageTokenSeparatorGenerator instead return SpaceRequirements.MAY; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/PythonTemplateRunner.java b/python/python-psi-impl/src/com/jetbrains/python/PythonTemplateRunner.java index d4805daf3103..1209d9368f11 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PythonTemplateRunner.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PythonTemplateRunner.java @@ -52,7 +52,8 @@ public final class PythonTemplateRunner { if (editor != null) { Template template = builder.buildInlineTemplate(); TemplateManager.getInstance(project).startTemplate(editor, template); - } else { + } + else { builder.runNonInteractively(true); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/PythonUiService.java b/python/python-psi-impl/src/com/jetbrains/python/PythonUiService.java index 9e783f5caa2c..0e30db4bb599 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/PythonUiService.java +++ b/python/python-psi-impl/src/com/jetbrains/python/PythonUiService.java @@ -25,11 +25,11 @@ import java.util.List; @ApiStatus.Experimental public class PythonUiService { - public void showBalloonInfo(Project project, @PopupContent String message) {} + public void showBalloonInfo(Project project, @PopupContent String message) { } - public void showBalloonWarning(Project project, @PopupContent String message) {} + public void showBalloonWarning(Project project, @PopupContent String message) { } - public void showBalloonError(Project project, @PopupContent String message) {} + public void showBalloonError(Project project, @PopupContent String message) { } public FileEditor getSelectedEditor(@NotNull Project project, VirtualFile virtualFile) { return null; @@ -55,7 +55,7 @@ public class PythonUiService { PsiElement element, String newName, boolean searchInComments, - boolean searchTextOccurrences) {} + boolean searchTextOccurrences) { } public LocalQuickFix createPyChangeSignatureQuickFixForMismatchingMethods(PyFunction function, PyFunction method) { return null; @@ -119,6 +119,5 @@ public class PythonUiService { @ListItem String initialValue, @Nullable Icon icon) { return -1; - } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/ConditionUtil.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/ConditionUtil.kt index 68fa09511171..6361d74cfcd4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/ConditionUtil.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/ConditionUtil.kt @@ -126,7 +126,8 @@ private fun getInvertedConditionExpression( level: LanguageLevel, generator: PyElementGenerator, expression: PyExpression, - isTopLevelExpression: Boolean): PyExpression { + isTopLevelExpression: Boolean, +): PyExpression { if (expression is PyParenthesizedExpression) { return getInvertedConditionExpression( project, file, level, generator, expression.containedExpression!!, isTopLevelExpression) @@ -271,7 +272,8 @@ private fun requiresParentheses(element: PsiElement): Boolean { } private fun createOrExpression( - level: LanguageLevel, generator: PyElementGenerator, expressions: Iterable, isTopLevelExpression: Boolean): PyExpression { + level: LanguageLevel, generator: PyElementGenerator, expressions: Iterable, isTopLevelExpression: Boolean, +): PyExpression { val result = StringBuilder() val requiresParentheses = !isTopLevelExpression && expressions.count() > 1 diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclassClassMembersProvider.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclassClassMembersProvider.java index 17e38ab4e76c..172934ef2589 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclassClassMembersProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclassClassMembersProvider.java @@ -57,5 +57,4 @@ public final class PyDataclassClassMembersProvider extends PyClassMembersProvide return CachedValueProvider.Result.create(result, PsiModificationTracker.MODIFICATION_COUNT); }); } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt index 191a91028657..a281c89b7b1a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PyDataclasses.kt @@ -176,7 +176,7 @@ fun resolvesToOmittedDefault(expression: PyExpression, type: Type): Boolean { val qNames = PyResolveUtil.resolveImportedElementQNameLocally(expression) return when (type.asPredefinedType) { - PyDataclassParameters.PredefinedType.STD, PyDataclassParameters.PredefinedType.DATACLASS_TRANSFORM -> + PyDataclassParameters.PredefinedType.STD, PyDataclassParameters.PredefinedType.DATACLASS_TRANSFORM -> qNames.any { it.toString() == PyDataclassNames.Dataclasses.DATACLASSES_MISSING } PyDataclassParameters.PredefinedType.ATTRS -> qNames.any { it.toString() in PyDataclassNames.Attrs.ATTRS_NOTHING } else -> false @@ -245,28 +245,28 @@ private fun parseDataclassParametersFromAST(cls: PyClass, context: TypeEvalConte for (decorator in decorators.decorators) { val callee = (decorator.callee as? PyReferenceExpression) ?: continue - + for (decoratorQualifiedName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) { val types = decoratorAndTypeAndMarkedCallee(cls.project) val decoratorAndTypeAndMarkedCallee = types.firstOrNull { it.first == decoratorQualifiedName } ?: continue - + val mapping = decorator.mapArguments( PyCallableTypeImpl(decoratorAndTypeAndMarkedCallee.third, null), context ?: TypeEvalContext.codeInsightFallback(cls.project) ) - + val builder = PyDataclassParametersBuilder(decoratorAndTypeAndMarkedCallee.second, decoratorAndTypeAndMarkedCallee.first) - + mapping .mappedParameters .entries .forEach { builder.update(it.value.name, it.key) } - + return builder.build() } - + // Process decorators that have dataclass_transform-compatible keyword arguments. if (decorator.qualifiedName == null) continue val decoratorKeywordArguments = decorator.arguments.filterIsInstance() @@ -559,10 +559,10 @@ private fun resolveDataclassParameters( // TODO remove this hack, make it a proper field val extraArguments = mutableMapOf() if (type.asPredefinedType == PyDataclassParameters.PredefinedType.ATTRS && stub.decoratorName() == PyKnownDecorator.ATTR_DATACLASS.qualifiedName) { - extraArguments["auto_attribs"] = + extraArguments["auto_attribs"] = PyElementGenerator.getInstance(pyClass.project).createExpressionFromText(LanguageLevel.forElement(pyClass), PyNames.TRUE) } - + return PyDataclassParameters( init = stub.initValue() ?: true, repr = stub.reprValue() ?: true, @@ -603,8 +603,8 @@ private fun resolveDataclassParameters( .overStub { dtStub -> dtStub } .withStubBuilder(PyDataclassTransformDecoratorStub::create) .compute(context) - - + + if (dataclassTransformStub != null) { val resolvedFieldSpecifiers = dataclassTransformStub.fieldSpecifiers .flatMap { PyResolveUtil.resolveQualifiedNameInScope(it, ScopeUtil.getScopeOwner(dataclassTransformDecorator)!!, context) } @@ -690,7 +690,7 @@ fun resolveDataclassFieldParameters( context: TypeEvalContext, ): PyDataclassFieldParameters? { assert(field.containingClass == dataclass) - + val assignedQName = field.assignedQName if (assignedQName != null) { val resolvesToMissingOrNothing = PyResolveUtil.resolveQualifiedNameInScope(assignedQName, ScopeUtil.getScopeOwner(dataclass)!!, context) @@ -707,7 +707,7 @@ fun resolveDataclassFieldParameters( ) } } - + val fieldStub = if (field.stub != null) { // TODO access the green stub here field.stub.getCustomStub(PyDataclassFieldStub::class.java) @@ -729,16 +729,16 @@ fun resolveDataclassFieldParameters( if (field.calleeName == null) return null val fieldSpecifierDeclaration = PyResolveUtil.resolveQualifiedNameInScope(field.calleeName!!, ScopeUtil.getScopeOwner(dataclass)!!, context) .filterIsInstance() - .firstOrNull { + .firstOrNull { val qualifiedName = it.qualifiedName - qualifiedName != null && QualifiedName.fromDottedString(qualifiedName) in dataclassParams.fieldSpecifiers + qualifiedName != null && QualifiedName.fromDottedString(qualifiedName) in dataclassParams.fieldSpecifiers } if (fieldSpecifierDeclaration == null) return null val fieldSpecifierCallable = when (fieldSpecifierDeclaration) { is PyClass -> fieldSpecifierDeclaration.findInitOrNew(true, context) is PyFunction -> fieldSpecifierDeclaration else -> null - } + } if (fieldSpecifierCallable == null) return null return PyDataclassFieldParameters( hasDefault = fieldStub?.hasDefault() ?: false, diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySoftFileReferenceContributor.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySoftFileReferenceContributor.kt index 97e8b21acf4b..7f288a9b2b20 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySoftFileReferenceContributor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySoftFileReferenceContributor.kt @@ -75,7 +75,7 @@ open class PySoftFileReferenceContributor : PsiReferenceContributor() { parameterNames.any(::matchesPathNamePattern) } .any { - val mapping = callExpr.mapArguments( it, typeEvalContext) + val mapping = callExpr.mapArguments(it, typeEvalContext) val parameterName = mapping.mappedParameters[expr]?.name ?: return@any false matchesPathNamePattern(parameterName) } @@ -110,12 +110,12 @@ open class PySoftFileReferenceContributor : PsiReferenceContributor() { val mapping = callExpr.mapArguments(it, typeEvalContext) mapping.mappedParameters[expr]?.getArgumentType(typeEvalContext) } - + // We can't use PyTypeChecker.match directly because the type `str | PathLike` is considered incompatible // with neither str nor PathLike (strict union semantics). - fun PyType.allowsValuesCompatibleWith(superType: PyType): Boolean = + fun PyType.allowsValuesCompatibleWith(superType: PyType): Boolean = PyTypeUtil.toStream(this).anyMatch { it != null && PyTypeChecker.match(superType, it, typeEvalContext) } - + return argumentTypes.any { it.allowsValuesCompatibleWith(bytesOrUnicodeType) } && argumentTypes.any { it.allowsValuesCompatibleWith(osPathLikeType) } } @@ -207,9 +207,11 @@ open class PySoftFileReferenceContributor : PsiReferenceContributor() { override fun createFileReference(range: TextRange, index: Int, text: String): FileReference? = doCreateFileReference(range, index, expandUserHome(text)) - open fun doCreateFileReference(range: TextRange, - index: Int, - expandedText: String?): FileReference? = + open fun doCreateFileReference( + range: TextRange, + index: Int, + expandedText: String?, + ): FileReference? = super.createFileReference(range, index, expandedText) override fun isAbsolutePathReference(): Boolean = diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java index 1550f16b284b..dd3038688f3d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/PySubstitutionChunkReference.java @@ -104,7 +104,8 @@ public class PySubstitutionChunkReference extends PsiReferenceBase resolveKeywordFormat(@NotNull PyArgumentList argumentList) { final Ref valueExprRef = getKeyValueFromArguments(argumentList); - final String indexElement = myChunk instanceof NewStyleSubstitutionChunk ? ((NewStyleSubstitutionChunk)myChunk).getMappingKeyElementIndex() : null; + final String indexElement = + myChunk instanceof NewStyleSubstitutionChunk ? ((NewStyleSubstitutionChunk)myChunk).getMappingKeyElementIndex() : null; if (valueExprRef != null && !valueExprRef.isNull() && indexElement != null) { final PyExpression valueExpr = PyPsiUtils.flattenParens(valueExprRef.get()); assert valueExpr != null; @@ -130,7 +131,7 @@ public class PySubstitutionChunkReference extends PsiReferenceBase resolvedRef = resolveKeywordStarExpression(arg); if (resolvedRef != null && (valueExprRef == null || valueExprRef.get() == null)) { @@ -256,7 +257,9 @@ public class PySubstitutionChunkReference extends PsiReferenceBase resolvePositionalStarExpression(@NotNull PyStarArgument starArgument, int argumentPosition) { assert myPosition >= 0; - final PyExpression expr = PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfAnyType(starArgument, PyListLiteralExpression.class, PyParenthesizedExpression.class, - PyStringLiteralExpression.class)); + final PyExpression expr = + PyPsiUtils.flattenParens(PsiTreeUtil.getChildOfAnyType(starArgument, PyListLiteralExpression.class, PyParenthesizedExpression.class, + PyStringLiteralExpression.class)); if (expr == null) { return Ref.create(starArgument); } @@ -374,7 +378,10 @@ public class PySubstitutionChunkReference extends PsiReferenceBase resolveDoubleStar(@NotNull PyDictLiteralExpression expression, @NotNull String mappingKey, boolean isNumeric, boolean allKeysForSure) { + private @Nullable Ref resolveDoubleStar(@NotNull PyDictLiteralExpression expression, + @NotNull String mappingKey, + boolean isNumeric, + boolean allKeysForSure) { final LanguageLevel languageLevel = LanguageLevel.forElement(expression); PyDoubleStarExpression[] starExpressions = PsiTreeUtil.getChildrenOfType(expression, PyDoubleStarExpression.class); if (languageLevel.isAtLeast(LanguageLevel.PYTHON35) && starExpressions != null) { @@ -391,7 +398,7 @@ public class PySubstitutionChunkReference extends PsiReferenceBase element = resolveDictCall((PyCallExpression)underStarExpr, mappingKey, true); diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassInsertHandler.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassInsertHandler.java index 3592d1e3ec97..968f2418b576 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassInsertHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassInsertHandler.java @@ -31,11 +31,11 @@ public final class PyClassInsertHandler implements InsertHandler PyClass pyClass = PyUtil.as(item.getPsiElement(), PyClass.class); PyFunction init = pyClass != null ? pyClass.findInitOrNew(true, null) : null; if (init != null && PyFunctionInsertHandler.hasParams(context, init)) { - editor.getCaretModel().moveToOffset(offset+1); + editor.getCaretModel().moveToOffset(offset + 1); AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), init); } else { - editor.getCaretModel().moveToOffset(offset+2); + editor.getCaretModel().moveToOffset(offset + 2); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassNameCompletionContributor.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassNameCompletionContributor.kt index 12168784b8ca..6285b2b71d08 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassNameCompletionContributor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyClassNameCompletionContributor.kt @@ -100,7 +100,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { return } } - + val project = originalFile.getProject() val typeEvalContext = TypeEvalContext.codeCompletion(project, originalFile) val maxVariants = intValue("ide.completion.variant.limit") @@ -109,7 +109,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { val fileBasedIndex = FileBasedIndex.getInstance() TimeoutUtil.run(ThrowableRunnable { val alreadySuggested: MutableSet = HashSet() - + // Suggest importable modules and packages val modulePackageScope = createScope(originalFile, false) forEachModulePackageNameFromIndex(modulePackageScope) { modulePackageName: String -> @@ -209,7 +209,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { private fun getInsertHandler( exported: PyElement, position: PsiElement, - typeEvalContext: TypeEvalContext + typeEvalContext: TypeEvalContext, ): InsertHandler { if (position.getParent() is PyStringLiteralExpression) { if (isInsideAllInInitPy(position)) { @@ -228,7 +228,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { private fun containsOnlyElementUnderTheCaret( remainingResults: MutableSet, - parameters: CompletionParameters + parameters: CompletionParameters, ): Boolean { val position = parameters.originalPosition if (remainingResults.size == 1 && position != null) { @@ -272,9 +272,9 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { private fun isApplicableInInsertionContext( definition: PyElement, - fqn: QualifiedName, + fqn: QualifiedName, position: PsiElement, - context: TypeEvalContext + context: TypeEvalContext, ): Boolean { if (PyTypingTypeProvider.isInsideTypeHint(position, context)) { // Not all names from typing.py are defined as classes @@ -295,15 +295,15 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { } return element is PyTypeAliasStatement } - + private fun isInsideErrorElement(referenceExpression: PyReferenceExpression): Boolean { return referenceExpression.findParentOfType() != null } private fun isInsideImportElement(referenceExpression: PyReferenceExpression): Boolean { return referenceExpression.findParentOfType() != null - } - + } + private fun isDirectlyInsideClassBody(referenceExpression: PyReferenceExpression): Boolean { return referenceExpression.parent is PyExpressionStatement && ScopeUtil.getScopeOwner(referenceExpression.parent) is PyClass @@ -403,7 +403,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { // See PY-73964, IJPL-265 private const val RECURSIVE_INDEX_ACCESS_ALLOWED = false } - + object InsertHandlers { internal val importingInsertHandler: InsertHandler = InsertHandler { context, item -> addImportForLookupElement(context, item, context.tailOffset - 1) @@ -445,7 +445,7 @@ class PyClassNameCompletionContributor : CompletionContributor(), DumbAware { context.document.insertString(context.startOffset, qualifiedNamePrefix) } } - + fun addImportForLookupElement(context: InsertionContext, item: LookupElement, tailOffset: Int) { val manager = PsiDocumentManager.getInstance(context.project) val document = manager.getDocument(context.file) diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyCompletionUtils.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyCompletionUtils.kt index d88cfe0b79b5..0e8478982388 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyCompletionUtils.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyCompletionUtils.kt @@ -60,12 +60,14 @@ fun CompletionParameters.getTypeEvalContext(): TypeEvalContext = TypeEvalContext * @param pyClass if provided will check if method does not exist already * @param builderPostprocessor function to be used to tune lookup builder */ -fun addMethodToResult(result: CompletionResultSet, - pyClass: PyClass?, - typeEvalContext: TypeEvalContext, - methodName: String, - methodParentheses: String = "(self)", - builderPostprocessor: ((LookupElementBuilder) -> LookupElementBuilder)? = null) { +fun addMethodToResult( + result: CompletionResultSet, + pyClass: PyClass?, + typeEvalContext: TypeEvalContext, + methodName: String, + methodParentheses: String = "(self)", + builderPostprocessor: ((LookupElementBuilder) -> LookupElementBuilder)? = null, +) { if (pyClass?.findMethodByName(methodName, false, typeEvalContext) != null) return val item = LookupElementBuilder.create(methodName + methodParentheses).withIcon( @@ -79,11 +81,13 @@ fun addMethodToResult(result: CompletionResultSet, * @param pyFile if provided will check if function does not exist already * @param builderPostprocessor function to be used to tune lookup builder */ -fun addFunctionToResult(result: CompletionResultSet, - pyFile: PyFile?, - functionName: String, - functionParentheses: String = "()", - builderPostprocessor: ((LookupElementBuilder) -> LookupElementBuilder)? = null) { +fun addFunctionToResult( + result: CompletionResultSet, + pyFile: PyFile?, + functionName: String, + functionParentheses: String = "()", + builderPostprocessor: ((LookupElementBuilder) -> LookupElementBuilder)? = null, +) { if (pyFile?.findTopLevelFunction(functionName) != null) return val item = LookupElementBuilder.create(functionName + functionParentheses).withIcon( @@ -126,7 +130,13 @@ const val FALLBACK_WEIGHT = -1_000_000 * @param completionLocation file, in which the completion is taking place * @param nameOnly indicates that we just need to check the name for underscores */ -fun computeCompletionWeight(element: PsiElement, elementName: String?, path: QualifiedName?, completionLocation: PsiFile?, nameOnly: Boolean): Int { +fun computeCompletionWeight( + element: PsiElement, + elementName: String?, + path: QualifiedName?, + completionLocation: PsiFile?, + nameOnly: Boolean, +): Int { var weight = 0 val name = elementName ?: return FALLBACK_WEIGHT @@ -156,18 +166,18 @@ fun computeCompletionWeight(element: PsiElement, elementName: String?, path: Qua weight -= LOCATION_NOT_YET_IMPORTED } - val privatePathComponents = importPath.components.count{ it.startsWith("_") } * PRIVATE_API + val privatePathComponents = importPath.components.count { it.startsWith("_") } * PRIVATE_API weight -= privatePathComponents + importPath.componentCount if (vFile != null) { - weight -= when { + weight -= when { PySkeletonUtil.isStdLib(vFile, sdk) -> LOCATION ModuleUtilCore.findModuleForFile(vFile, element.project) == null -> LOCATION * 2 else -> 0 } } - weight -= when(PyUtil.turnInitIntoDir(element)) { + weight -= when (PyUtil.turnInitIntoDir(element)) { is PsiDirectory -> ELEMENT_TYPE * 2 is PyFile -> ELEMENT_TYPE else -> 0 diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDictLiteralCompletionContributor.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDictLiteralCompletionContributor.kt index 3105ba0a73f3..86b2698c75b0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDictLiteralCompletionContributor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDictLiteralCompletionContributor.kt @@ -45,9 +45,11 @@ private class DictLiteralCompletionProvider : CompletionProvider expression.elements diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java index a11bcc33a188..f7f7b8b767b5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java @@ -116,7 +116,7 @@ public final class PyDocstringCompletionContributor extends CompletionContributo } final String text = file.getText(); StringBuilder prefixBuilder = new StringBuilder(); - while(offset > 0 && Character.isLetterOrDigit(text.charAt(offset))) { + while (offset > 0 && Character.isLetterOrDigit(text.charAt(offset))) { prefixBuilder.insert(0, text.charAt(offset)); offset--; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyKeywordCompletionContributor.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyKeywordCompletionContributor.java index b383e823319d..42f146819031 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyKeywordCompletionContributor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyKeywordCompletionContributor.java @@ -77,7 +77,9 @@ public final class PyKeywordCompletionContributor extends CompletionContributor PsiElement prev = p.getPrevSibling(); while (prev instanceof PsiWhiteSpace) prev = prev.getPrevSibling(); if (prev == null) return true; // there was only whitespace before us - if (prev instanceof PyStatement || prev instanceof PsiComment || prev instanceof OuterLanguageElement) { // a non-stmt would be something strange + if (prev instanceof PyStatement || + prev instanceof PsiComment || + prev instanceof OuterLanguageElement) { // a non-stmt would be something strange if (prev.getLastChild() instanceof PsiErrorElement) { // prev stmt ends with an error. are we on the same line? PsiDocumentManager docMgr = PsiDocumentManager.getInstance(p.getProject()); @@ -240,8 +242,9 @@ public final class PyKeywordCompletionContributor extends CompletionContributor psiElement().inFile(psiFile(PyDocstringFile.class))); private static final ElementPattern IN_FUNCTION_HEADER = - psiElement().inside(PyFunction.class).andNot(or(psiElement().inside(false, psiElement(PyStatementList.class), psiElement(PyFunction.class)), - psiElement().inside(false, psiElement(PyParameterList.class), psiElement(PyFunction.class)))); + psiElement().inside(PyFunction.class) + .andNot(or(psiElement().inside(false, psiElement(PyStatementList.class), psiElement(PyFunction.class)), + psiElement().inside(false, psiElement(PyParameterList.class), psiElement(PyFunction.class)))); public static final PsiElementPattern.Capture AFTER_QUALIFIER = psiElement().afterLeaf(psiElement().withText(".").inside(PyReferenceExpression.class)); @@ -307,7 +310,8 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private static final PsiElementPattern.Capture IN_PARAM_LIST = psiElement().inside(PyParameterList.class); private static final PsiElementPattern.Capture IN_ARG_LIST = psiElement().inside(PyArgumentList.class); - private static final PsiElementPattern.Capture IN_DECORATOR_ARG_LIST = psiElement().inside(PyArgumentList.class).inside(PyDecorator.class); + private static final PsiElementPattern.Capture IN_DECORATOR_ARG_LIST = + psiElement().inside(PyArgumentList.class).inside(PyDecorator.class); private static final PsiElementPattern.Capture IN_DEF_BODY = psiElement().inside(false, psiElement(PyFunction.class), psiElement(PyClass.class)); @@ -338,7 +342,7 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private static final PsiElementPattern.Capture AFTER_COND_STMT_NO_ELSE = afterStatement(psiElement().withChild(psiElement(PyConditionalStatementPart.class)) - .withLastChild(not(psiElement(PyElsePart.class)))); + .withLastChild(not(psiElement(PyElsePart.class)))); private static PsiElementPattern.Capture afterStatement(final PsiElementPattern.Capture statementPattern) { return psiElement().atStartOf(psiElement(PyExpressionStatement.class) @@ -372,7 +376,8 @@ public final class PyKeywordCompletionContributor extends CompletionContributor )); */ - private static final FilterPattern PY3K = new FilterPattern(new PyKeywordCompletionContributor.LanguageLevelAtLeastFilter(LanguageLevel.PYTHON30)); + private static final FilterPattern PY3K = + new FilterPattern(new PyKeywordCompletionContributor.LanguageLevelAtLeastFilter(LanguageLevel.PYTHON30)); private static final FilterPattern PY35 = new FilterPattern(new LanguageLevelAtLeastFilter(LanguageLevel.PYTHON35)); private static final FilterPattern PY310 = new FilterPattern(new LanguageLevelAtLeastFilter(LanguageLevel.PYTHON310)); @@ -458,7 +463,8 @@ public final class PyKeywordCompletionContributor extends CompletionContributor final @NotNull ProcessingContext context, final @NotNull CompletionResultSet result ) { - putKeywords(result, TailTypes.spaceType(), PyNames.ASSERT, PyNames.DEL, PyNames.EXEC, PyNames.FROM, PyNames.IMPORT, PyNames.RAISE); + putKeywords(result, TailTypes.spaceType(), PyNames.ASSERT, PyNames.DEL, PyNames.EXEC, PyNames.FROM, PyNames.IMPORT, + PyNames.RAISE); putKeywords(result, TailTypes.noneType(), PyNames.PASS); } } @@ -470,12 +476,12 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addBreak() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_BEGIN_STMT) - .andNot(AFTER_QUALIFIER) - .andNot(IN_PARAM_LIST) - .andNot(IN_ARG_LIST) - .and(IN_LOOP) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_BEGIN_STMT) + .andNot(AFTER_QUALIFIER) + .andNot(IN_PARAM_LIST) + .andNot(IN_ARG_LIST) + .and(IN_LOOP) , new PyKeywordCompletionProvider(TailTypes.noneType(), PyNames.BREAK) ); @@ -484,13 +490,13 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addContinue() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_BEGIN_STMT) - .andNot(AFTER_QUALIFIER) - .andNot(IN_PARAM_LIST) - .andNot(IN_ARG_LIST) - .andOr(not(IN_FINALLY_NO_LOOP), new FilterPattern(new LanguageLevelAtLeastFilter(LanguageLevel.PYTHON38))) - .and(IN_LOOP) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_BEGIN_STMT) + .andNot(AFTER_QUALIFIER) + .andNot(IN_PARAM_LIST) + .andNot(IN_ARG_LIST) + .andOr(not(IN_FINALLY_NO_LOOP), new FilterPattern(new LanguageLevelAtLeastFilter(LanguageLevel.PYTHON38))) + .and(IN_LOOP) , new PyKeywordCompletionProvider(TailTypes.noneType(), PyNames.CONTINUE) ); @@ -509,21 +515,21 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addWithinFuncs() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_DEF_BODY) - .and(IN_BEGIN_STMT) - .andNot(AFTER_QUALIFIER) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_DEF_BODY) + .and(IN_BEGIN_STMT) + .andNot(AFTER_QUALIFIER) , new PyKeywordCompletionProvider(PyNames.GLOBAL, PyNames.RETURN, PyNames.YIELD) ); extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_DEF_BODY) - .and(IN_BEGIN_STMT) - .and(PY3K) - .andNot(AFTER_QUALIFIER) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_DEF_BODY) + .and(IN_BEGIN_STMT) + .and(PY3K) + .andNot(AFTER_QUALIFIER) , new PyKeywordCompletionProvider(PyNames.NONLOCAL) ); @@ -554,10 +560,10 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addWithinIf() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(FIRST_ON_LINE) - .andOr(IN_IF_BODY, AFTER_IF) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) + .withLanguage(PythonLanguage.getInstance()) + .and(FIRST_ON_LINE) + .andOr(IN_IF_BODY, AFTER_IF) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) , new PyKeywordCompletionProvider(TailTypes.noneType(), PyUnindentingInsertHandler.INSTANCE, PyNames.ELIF)); } @@ -565,12 +571,12 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addWithinTry() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(FIRST_ON_LINE) - .andOr(IN_TRY_BODY, IN_EXCEPT_BODY, AFTER_TRY, IN_ELSE_BODY_OF_TRY) + .withLanguage(PythonLanguage.getInstance()) + .and(FIRST_ON_LINE) + .andOr(IN_TRY_BODY, IN_EXCEPT_BODY, AFTER_TRY, IN_ELSE_BODY_OF_TRY) //.andNot(RIGHT_AFTER_COLON) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) - .andNot(AFTER_FINALLY) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) + .andNot(AFTER_FINALLY) , new CompletionProvider<>() { @Override @@ -585,12 +591,12 @@ public final class PyKeywordCompletionContributor extends CompletionContributor ); extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(FIRST_ON_LINE) - .andOr(IN_TRY_BODY, IN_EXCEPT_BODY, AFTER_TRY, IN_ELSE_BODY_OF_TRY) + .withLanguage(PythonLanguage.getInstance()) + .and(FIRST_ON_LINE) + .andOr(IN_TRY_BODY, IN_EXCEPT_BODY, AFTER_TRY, IN_ELSE_BODY_OF_TRY) //.andNot(RIGHT_AFTER_COLON) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) - .andNot(AFTER_FINALLY).andNot(AFTER_ELSE) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) + .andNot(AFTER_FINALLY).andNot(AFTER_ELSE) , new CompletionProvider<>() { @Override @@ -608,10 +614,10 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addElse() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(FIRST_ON_LINE) - .andOr(IN_COND_STMT, IN_EXCEPT_BODY, AFTER_COND_STMT_NO_ELSE, AFTER_LOOP_NO_ELSE, AFTER_EXCEPT) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) + .withLanguage(PythonLanguage.getInstance()) + .and(FIRST_ON_LINE) + .andOr(IN_COND_STMT, IN_EXCEPT_BODY, AFTER_COND_STMT_NO_ELSE, AFTER_LOOP_NO_ELSE, AFTER_EXCEPT) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) , new PyKeywordCompletionProvider(TailTypes.caseColonType(), PyUnindentingInsertHandler.INSTANCE, PyNames.ELSE)); } @@ -619,12 +625,12 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addInfixOperators() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .andNot(IN_COMMENT) - .andNot(BEFORE_COND) - .andNot(IN_IMPORT_STMT) // expressions there are not logical anyway - .andNot(IN_PARAM_LIST) - .andNot(AFTER_QUALIFIER). + .withLanguage(PythonLanguage.getInstance()) + .andNot(IN_COMMENT) + .andNot(BEFORE_COND) + .andNot(IN_IMPORT_STMT) // expressions there are not logical anyway + .andNot(IN_PARAM_LIST) + .andNot(AFTER_QUALIFIER). andNot(IN_STRING_LITERAL).and(IN_BEGIN_STMT) , new PyKeywordCompletionProvider(PyNames.AND, PyNames.OR, PyNames.IS, PyNames.IN) @@ -634,14 +640,14 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addNot() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .andNot(IN_COMMENT) - .andNot(IN_IMPORT_STMT) - .andNot(IN_PARAM_LIST) - .andNot(IN_FUNCTION_HEADER) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) - .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL).andNot(TARGET_AFTER_QUALIFIER) - .andNot(IN_PATTERN) + .withLanguage(PythonLanguage.getInstance()) + .andNot(IN_COMMENT) + .andNot(IN_IMPORT_STMT) + .andNot(IN_PARAM_LIST) + .andNot(IN_FUNCTION_HEADER) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL) + .andNot(AFTER_QUALIFIER).andNot(IN_STRING_LITERAL).andNot(TARGET_AFTER_QUALIFIER) + .andNot(IN_PATTERN) , new PyKeywordCompletionProvider(PyNames.NOT, PyNames.LAMBDA) ); @@ -651,24 +657,24 @@ public final class PyKeywordCompletionContributor extends CompletionContributor // Add literals in normal contexts extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .andNot(IN_COMMENT) - .andNot(IN_IMPORT_STMT) - .and(NOT_PARAMETER_OR_DEFAULT_VALUE) - .andNot(AFTER_QUALIFIER) - .andNot(IN_FUNCTION_HEADER) - .andNot(IN_STRING_LITERAL) - .andNot(TARGET_AFTER_QUALIFIER) + .withLanguage(PythonLanguage.getInstance()) + .andNot(IN_COMMENT) + .andNot(IN_IMPORT_STMT) + .and(NOT_PARAMETER_OR_DEFAULT_VALUE) + .andNot(AFTER_QUALIFIER) + .andNot(IN_FUNCTION_HEADER) + .andNot(IN_STRING_LITERAL) + .andNot(TARGET_AFTER_QUALIFIER) , new PyKeywordCompletionProvider(TailTypes.noneType(), PyNames.TRUE, PyNames.FALSE, PyNames.NONE)); // Add literals specifically in decorator argument lists extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_DECORATOR_ARG_LIST) - .andNot(IN_COMMENT) - .andNot(IN_STRING_LITERAL) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_DECORATOR_ARG_LIST) + .andNot(IN_COMMENT) + .andNot(IN_STRING_LITERAL) , new PyKeywordCompletionProvider(TailTypes.noneType(), PyNames.TRUE, PyNames.FALSE, PyNames.NONE)); extend(CompletionType.BASIC, @@ -714,10 +720,10 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addAs() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .andOr(IN_IMPORT_AFTER_REF, IN_WITH_AFTER_REF, IN_EXCEPT_AFTER_REF) - .andNot(AFTER_QUALIFIER) - .andNot(IN_COMMENT) + .withLanguage(PythonLanguage.getInstance()) + .andOr(IN_IMPORT_AFTER_REF, IN_WITH_AFTER_REF, IN_EXCEPT_AFTER_REF) + .andNot(AFTER_QUALIFIER) + .andNot(IN_COMMENT) , new PyKeywordCompletionProvider(PyNames.AS) ); @@ -726,9 +732,9 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addImportInFrom() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .and(IN_FROM_IMPORT_AFTER_REF) - .andNot(AFTER_QUALIFIER) + .withLanguage(PythonLanguage.getInstance()) + .and(IN_FROM_IMPORT_AFTER_REF) + .andNot(AFTER_QUALIFIER) , new PyKeywordCompletionProvider(PyNames.IMPORT) ); @@ -763,10 +769,10 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addExprElse() { extend( CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .afterLeafSkipping(psiElement().whitespace(), - psiElement().inside(psiElement(PyConditionalExpression.class)) - .and(psiElement().afterLeaf(PyNames.IF))) + .withLanguage(PythonLanguage.getInstance()) + .afterLeafSkipping(psiElement().whitespace(), + psiElement().inside(psiElement(PyConditionalExpression.class)) + .and(psiElement().afterLeaf(PyNames.IF))) , new PyKeywordCompletionProvider(TailTypes.spaceType(), PyNames.ELSE)); } @@ -792,8 +798,8 @@ public final class PyKeywordCompletionContributor extends CompletionContributor .afterLeaf(psiElement().withElementType(PyTokenTypes.AUG_ASSIGN_OPERATIONS)), psiElement() .inside(true, psiElement(PyParenthesizedExpression.class))) - .andNot(IN_STRING_LITERAL) - .andNot(IN_COMMENT), + .andNot(IN_STRING_LITERAL) + .andNot(IN_COMMENT), new PyKeywordCompletionProvider(PyNames.YIELD)); } @@ -834,11 +840,11 @@ public final class PyKeywordCompletionContributor extends CompletionContributor private void addForToComprehensions() { extend(CompletionType.BASIC, psiElement() - .withLanguage(PythonLanguage.getInstance()) - .inside(psiElement(PySequenceExpression.class)) - .andNot(psiElement() - .afterLeaf(or(psiElement(PyTokenTypes.LBRACE), psiElement(PyTokenTypes.LBRACKET), psiElement(PyTokenTypes.LPAR)))) - .andNot(IN_COMMENT), + .withLanguage(PythonLanguage.getInstance()) + .inside(psiElement(PySequenceExpression.class)) + .andNot(psiElement() + .afterLeaf(or(psiElement(PyTokenTypes.LBRACE), psiElement(PyTokenTypes.LBRACKET), psiElement(PyTokenTypes.LPAR)))) + .andNot(IN_COMMENT), new PyKeywordCompletionProvider(PyNames.FOR)); } @@ -848,7 +854,6 @@ public final class PyKeywordCompletionContributor extends CompletionContributor .withLanguage(PythonLanguage.getInstance()) .and(psiElement()).afterLeaf(psiElement().afterLeaf(PyNames.FOR)), new PyKeywordCompletionProvider(PyNames.IN)); - } private static final class PyKeywordCompletionProvider extends CompletionProvider { diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java index 7e859d65a19b..39010953345f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMetaClassCompletionContributor.java @@ -47,10 +47,10 @@ public final class PyMetaClassCompletionContributor extends CompletionContributo }); extend(CompletionType.BASIC, PlatformPatterns - .psiElement() - .withLanguage(PythonLanguage.getInstance()) - .withParents(PyReferenceExpression.class, PyArgumentList.class, PyClass.class) - .and(hasLanguageLevel(level -> !level.isPython2())), + .psiElement() + .withLanguage(PythonLanguage.getInstance()) + .withParents(PyReferenceExpression.class, PyArgumentList.class, PyClass.class) + .and(hasLanguageLevel(level -> !level.isPython2())), new CompletionProvider<>() { @Override protected void addCompletions(@NotNull CompletionParameters parameters, diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMultipleArgumentsCompletionContributor.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMultipleArgumentsCompletionContributor.kt index c399097b3af3..b7258f7320c8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMultipleArgumentsCompletionContributor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyMultipleArgumentsCompletionContributor.kt @@ -21,7 +21,7 @@ import com.jetbrains.python.psi.impl.PyPsiUtils import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyCallableParameter -class PyMultipleArgumentsCompletionContributor: CompletionContributor(), DumbAware { +class PyMultipleArgumentsCompletionContributor : CompletionContributor(), DumbAware { init { extend(CompletionType.BASIC, PlatformPatterns.psiElement().inArgumentList(), MyCompletionProvider) } @@ -45,8 +45,9 @@ class PyMultipleArgumentsCompletionContributor: CompletionContributor(), DumbAwa val argumentIndex = callableType.implicitOffset + argumentExplicitIndex if (callableParameters == null || argumentIndex >= callableParameters.size || - callableParameters.any { it.isKeywordContainer || it.isPositionalContainer }) { - return@forEach + callableParameters.any { it.isKeywordContainer || it.isPositionalContainer } + ) { + return@forEach } val unfilledParameters = ContainerUtil.subList(callableParameters, argumentIndex) @@ -110,7 +111,7 @@ class PyMultipleArgumentsCompletionContributor: CompletionContributor(), DumbAwa ControlFlowCache.getScope(scope).namedElements .asSequence() .filter { element -> - PsiTreeUtil.getParentOfType(element, PyListCompExpression::class.java) ?.let { listComp -> + PsiTreeUtil.getParentOfType(element, PyListCompExpression::class.java)?.let { listComp -> PsiTreeUtil.isAncestor(listComp.resultExpression, position, false) } ?: PyPsiUtils.isBefore(element, position) } @@ -119,7 +120,7 @@ class PyMultipleArgumentsCompletionContributor: CompletionContributor(), DumbAwa } } -class PyMultipleArgumentsInsertHandler(private val call: PyCallExpression): ParenthesesInsertHandler() { +class PyMultipleArgumentsInsertHandler(private val call: PyCallExpression) : ParenthesesInsertHandler() { override fun placeCaretInsideParentheses(context: InsertionContext?, item: LookupElement?): Boolean = false override fun handleInsert(context: InsertionContext, item: LookupElement) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStringFormatCompletionContributor.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStringFormatCompletionContributor.java index d8824b12906f..68945b02d7bb 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStringFormatCompletionContributor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStringFormatCompletionContributor.java @@ -298,7 +298,7 @@ public final class PyStringFormatCompletionContributor extends CompletionContrib private static @NotNull List getElementsFromDict(final @NotNull PyDictLiteralExpression dict) { return Arrays.stream(dict.getElements()) .map(e -> PyUtil.as(e.getKey(), PyStringLiteralExpression.class)) - .filter(k-> k != null) + .filter(k -> k != null) .map(k -> createLookUpElement(k.getStringValue())) .collect(Collectors.toList()); } @@ -317,7 +317,7 @@ public final class PyStringFormatCompletionContributor extends CompletionContrib private static @Nullable LookupElement getKeywordArgument(final @NotNull PyKeywordArgument arg) { final String keyword = arg.getKeyword(); - return keyword != null ? createLookUpElement(keyword) : null; + return keyword != null ? createLookUpElement(keyword) : null; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStructuralTypeAttributesCompletionContributor.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStructuralTypeAttributesCompletionContributor.java index bba92152116a..b1c8ee6ecce5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStructuralTypeAttributesCompletionContributor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyStructuralTypeAttributesCompletionContributor.java @@ -146,8 +146,8 @@ public final class PyStructuralTypeAttributesCompletionContributor extends Compl * intermediate results in case of a large class hierarchy. */ private static @NotNull Set getAncestorClassesFast(@NotNull PyClass pyClass, - @NotNull TypeEvalContext context, - @NotNull Map> ancestorsCache) { + @NotNull TypeEvalContext context, + @NotNull Map> ancestorsCache) { final Set ancestors = ancestorsCache.get(pyClass); if (ancestors != null) { return ancestors; diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyUnresolvedModuleAttributeCompletionContributor.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyUnresolvedModuleAttributeCompletionContributor.kt index 9a30e0e65e15..f2d82fe43f69 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyUnresolvedModuleAttributeCompletionContributor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyUnresolvedModuleAttributeCompletionContributor.kt @@ -145,7 +145,7 @@ class PyUnresolvedModuleAttributeCompletionContributor : CompletionContributor() .filterIsInstance() .map { PyModuleType(it) } .flatMap { it.getCompletionVariantsAsLookupElements(parameters.position, context, false, false, typeContext) } - .filter { PyNames.isIdentifier(it.lookupString) && !it.lookupString.startsWith('_')} + .filter { PyNames.isIdentifier(it.lookupString) && !it.lookupString.startsWith('_') } .filter { attribute.isEmpty() || resultMatchingCompleteReference.prefixMatcher.prefixMatches("$qualifier.${it.lookupString}") } .mapNotNull { val element = it.psiElement as? PyElement diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PythonLookupElement.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PythonLookupElement.java index 6c89416acfb9..20b42cba78ba 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PythonLookupElement.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PythonLookupElement.java @@ -15,7 +15,7 @@ import javax.swing.*; /** * TODO: Add description */ -public class PythonLookupElement extends LookupElement implements Comparable{ +public class PythonLookupElement extends LookupElement implements Comparable { protected final String myLookupString; protected final String myTypeText; @@ -100,6 +100,5 @@ public class PythonLookupElement extends LookupElement implements Comparable> CONTROL_FLOW_KEY = Key.create("com.jetbrains.python.codeInsight.controlflow.ControlFlow"); + private static final Key> CONTROL_FLOW_KEY = + Key.create("com.jetbrains.python.codeInsight.controlflow.ControlFlow"); private static final Key> SCOPE_KEY = Key.create("com.jetbrains.python.codeInsight.controlflow.Scope"); private ControlFlowCache() { diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyControlFlowBuilder.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyControlFlowBuilder.java index 28efff94b73a..e73fcb96910d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyControlFlowBuilder.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyControlFlowBuilder.java @@ -45,11 +45,12 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { private final ControlFlowBuilder myBuilder = new ControlFlowBuilder(); private @Nullable TrueFalseNodes myTrueFalseNodes; - + // see com.jetbrains.python.PyPatternTypeTest.testMatchClassPatternShadowingCapture private final @NotNull List myPatternBindingNames = new ArrayList<>(); - private record TrueFalseNodes(@NotNull Instruction trueNode, @NotNull Instruction falseNode) {} + private record TrueFalseNodes(@NotNull Instruction trueNode, @NotNull Instruction falseNode) { + } public PyControlFlow buildControlFlow(final @NotNull ScopeOwner owner) { return new PyControlFlow(myBuilder.build(this, owner)); @@ -346,15 +347,15 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { for (PyCaseClause clause : matchStatement.getCaseClauses()) { myBuilder.prevInstruction = nextClause; nextClause = addTransparentInstruction(); - + myPatternBindingNames.clear(); - + PyPattern pattern = clause.getPattern(); if (pattern != null) { pattern.accept(this); addTypeAssertionNodes(clause, true, myPatternBindingNames); } - + PyExpression guard = clause.getGuardCondition(); if (guard != null) { TransparentInstruction trueNode = addTransparentInstruction(); @@ -650,7 +651,7 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { elsePart.accept(this); myBuilder.addPendingEdge(node, myBuilder.prevInstruction); } - + myBuilder.flowAbrupted(); collectInternalPendingEdges(node); @@ -958,7 +959,7 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { myBuilder.addEdge(myBuilder.prevInstruction, i); } } - + collectInternalPendingEdges(node); } @@ -1147,7 +1148,7 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { private TransparentInstruction addTransparentInstruction() { return addTransparentInstruction(null); } - + private TransparentInstruction addTransparentInstruction(@Nullable PsiElement element) { TransparentInstructionImpl instruction = new TransparentInstructionImpl(myBuilder, element, ""); myBuilder.instructions.add(instruction); @@ -1162,11 +1163,11 @@ public class PyControlFlowBuilder extends PyRecursiveElementVisitor { } /** - * Can be used to collect all pending edges + * Can be used to collect all pending edges * that we used to build CFG for `node`, * but are not relevant to other elements. * Is almost equivalent to this: - * + * *
{@code
    * visitPy...(node);
    * myBuilder.startNode(node.nextSibling); // collectInternalPendingEdges does this, without needing nextSibling
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyRaiseInstruction.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyRaiseInstruction.kt
index 3073b54a5c04..634f8eaad35d 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyRaiseInstruction.kt
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyRaiseInstruction.kt
@@ -6,9 +6,10 @@ import com.jetbrains.python.psi.PyAssertStatement
 import com.jetbrains.python.psi.PyRaiseStatement
 import com.jetbrains.python.psi.PyStatement
 
-class PyRaiseInstruction private constructor(builder: ControlFlowBuilder, raiseOrAssert: PyStatement): InstructionImpl(builder, raiseOrAssert) {
-  constructor(builder: ControlFlowBuilder, raise: PyRaiseStatement): this(builder, raise as PyStatement)
-  constructor(builder: ControlFlowBuilder, assert: PyAssertStatement): this(builder, assert as PyStatement)
+class PyRaiseInstruction private constructor(builder: ControlFlowBuilder, raiseOrAssert: PyStatement) : InstructionImpl(builder,
+                                                                                                                        raiseOrAssert) {
+  constructor(builder: ControlFlowBuilder, raise: PyRaiseStatement) : this(builder, raise as PyStatement)
+  constructor(builder: ControlFlowBuilder, assert: PyAssertStatement) : this(builder, assert as PyStatement)
 
   override fun getElementPresentation(): String = "raise: ${element}"
 }
\ No newline at end of file
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyTypeAssertionEvaluator.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyTypeAssertionEvaluator.java
index 7eddb5e937a4..e4803977870f 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyTypeAssertionEvaluator.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/PyTypeAssertionEvaluator.java
@@ -131,7 +131,8 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
         PyExpression[] elements = ((PySequenceExpression)rhs).getElements();
         List types = new ArrayList<>(elements.length);
         for (PyExpression element : elements) {
-          PyType type = PyLiteralType.isNone(element) ? PyBuiltinCache.getInstance(element).getNoneType() : getLiteralType(element, context);
+          PyType type =
+            PyLiteralType.isNone(element) ? PyBuiltinCache.getInstance(element).getNoneType() : getLiteralType(element, context);
           if (type == null) {
             return null;
           }
@@ -201,7 +202,7 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
   public static @Nullable Ref createAssertionType(@Nullable PyType initial,
                                                           @Nullable PyType suggested,
                                                           boolean positive,
-                                                          boolean forceStrictNarrow, 
+                                                          boolean forceStrictNarrow,
                                                           @NotNull TypeEvalContext context) {
     if (suggested == null) return null;
     if (positive) {
@@ -281,7 +282,7 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
     }
     return null;
   }
-  
+
   private static @Nullable PyType intersect(@Nullable PyType initial, @Nullable PyType suggested) {
     // TODO: if we had IntersectionType, here it would be created. Also, final classes can be handled here
     if (initial instanceof PyNeverType) {
@@ -301,7 +302,9 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
   /**
    * @param transformToDefinition if true the result type will be Type[T], not T itself.
    */
-  private static @Nullable PyType transformTypeFromAssertion(@Nullable PyType type, boolean transformToDefinition, @NotNull TypeEvalContext context,
+  private static @Nullable PyType transformTypeFromAssertion(@Nullable PyType type,
+                                                             boolean transformToDefinition,
+                                                             @NotNull TypeEvalContext context,
                                                              @Nullable PyExpression typeElement) {
     /*
      * We need to distinguish:
@@ -348,7 +351,11 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
     pushAssertion(expr, positive, false, isStrictNarrowingAllowed(), suggestedType);
   }
 
-  private void pushAssertion(@Nullable PyExpression expr, boolean positive, boolean allowAnyExpr, boolean forceStrictNarrow, @NotNull Function suggestedType) {
+  private void pushAssertion(@Nullable PyExpression expr,
+                             boolean positive,
+                             boolean allowAnyExpr,
+                             boolean forceStrictNarrow,
+                             @NotNull Function suggestedType) {
     expr = PyPsiUtils.flattenParens(expr);
     if (expr instanceof PySequenceExpression seqExpr) {
       PyExpression[] elements = seqExpr.getElements();
@@ -388,11 +395,11 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
       return null;
     };
   }
-  
+
   private static @Nullable PsiElement skipNotAndParens(@Nullable PsiElement element) {
     if (element == null) return null;
     for (PsiElement e = element.getParent(); e != null; e = e.getParent()) {
-      if (!(e instanceof PyParenthesizedExpression) && 
+      if (!(e instanceof PyParenthesizedExpression) &&
           !(e instanceof PyPrefixExpression prefixExpr && prefixExpr.getOperator() == PyTokenTypes.NOT_KEYWORD)) {
         return e;
       }
@@ -406,8 +413,10 @@ public class PyTypeAssertionEvaluator extends PyRecursiveElementVisitor {
     if (parent instanceof PyConditionalExpression cond && PsiTreeUtil.isAncestor(cond.getCondition(), node, false)) return true;
     if (parent instanceof PyBinaryExpression binExpr && (binExpr.isOperator(PyNames.AND) || binExpr.isOperator(PyNames.OR))) return true;
     if (parent instanceof PyAssertStatement) return true;
-    if (parent instanceof PyGeneratorExpression gen && 
-        ContainerUtil.or(gen.getIfComponents(), it -> PsiTreeUtil.isAncestor(it.getTest(), node, false))) return true;
+    if (parent instanceof PyGeneratorExpression gen &&
+        ContainerUtil.or(gen.getIfComponents(), it -> PsiTreeUtil.isAncestor(it.getTest(), node, false))) {
+      return true;
+    }
     return false;
   }
 
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/ReadWriteInstruction.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/ReadWriteInstruction.java
index 3a7aa19a8707..1262d6d10763 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/ReadWriteInstruction.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/controlflow/ReadWriteInstruction.java
@@ -100,7 +100,7 @@ public final class ReadWriteInstruction extends InstructionImpl {
   public @NotNull ACCESS getAccess() {
     return myAccess;
   }
-  
+
   public static @NotNull ReadWriteInstruction read(final @NotNull ControlFlowBuilder builder,
                                                    final @Nullable PyElement element,
                                                    final @Nullable String name) {
@@ -112,14 +112,14 @@ public final class ReadWriteInstruction extends InstructionImpl {
                                                     final @Nullable String name) {
     return new ReadWriteInstruction(builder, element, name, ACCESS.WRITE);
   }
-  
+
   public static @NotNull ReadWriteInstruction newInstruction(final @NotNull ControlFlowBuilder builder,
                                                              final @Nullable PsiElement element,
                                                              final @Nullable String name,
                                                              final @NotNull ACCESS access) {
     return new ReadWriteInstruction(builder, element, name, access);
   }
-  
+
   public static @NotNull ReadWriteInstruction assertType(final @NotNull ControlFlowBuilder builder,
                                                          final @Nullable PsiElement element,
                                                          final @Nullable String name,
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsDfaInstance.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsDfaInstance.java
index e8df30fd36a1..e652a779b6c1 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsDfaInstance.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsDfaInstance.java
@@ -32,9 +32,9 @@ public class PyReachingDefsDfaInstance implements DfaMapInstance
 
   @Override
   public DFAMap fun(final DFAMap map, final Instruction instruction) {
-    if (map == UNREACHABLE_MARKER)  return map;
+    if (map == UNREACHABLE_MARKER) return map;
     final PsiElement element = instruction.getElement();
-    if (element == null || ((PyFile) element.getContainingFile()).getLanguageLevel().isPython2()){
+    if (element == null || ((PyFile)element.getContainingFile()).getLanguageLevel().isPython2()) {
       return processReducedMap(map, instruction, element);
     }
     if (PyDataFlowKt.isUnreachableForInspection(element, myContext)) {
@@ -50,11 +50,11 @@ public class PyReachingDefsDfaInstance implements DfaMapInstance
     for (Map.Entry entry : map.entrySet()) {
       final ScopeVariable value = entry.getValue();
       // Support PEP-3110. (PY-1408)
-      if (value.isParameter()){
+      if (value.isParameter()) {
         final PsiElement declaration = value.getDeclarations().iterator().next();
         final PyExceptPart exceptPart = PyExceptPartNavigator.getPyExceptPartByTarget(declaration);
-        if (exceptPart != null){
-          if (!PsiTreeUtil.isAncestor(exceptPart, element, false)){
+        if (exceptPart != null) {
+          if (!PsiTreeUtil.isAncestor(exceptPart, element, false)) {
             continue;
           }
         }
@@ -85,10 +85,10 @@ public class PyReachingDefsDfaInstance implements DfaMapInstance
       }
     }
     // Processing PyFunction
-    else if (element instanceof PyFunction){
+    else if (element instanceof PyFunction) {
       name = ((PyFunction)element).getName();
     }
-    if (name == null){
+    if (name == null) {
       return map;
     }
     final ScopeVariable variable = map.get(name);
@@ -106,7 +106,8 @@ public class PyReachingDefsDfaInstance implements DfaMapInstance
       final boolean isParameter = variable != null && variable.isParameter();
       if (variable == null) {
         scopeVariable = new ScopeVariableImpl(name, isParameter, element);
-      } else {
+      }
+      else {
         scopeVariable = new ScopeVariableImpl(name, isParameter, variable.getDeclarations());
       }
       map = map.asWritable();
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsSemilattice.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsSemilattice.java
index 810b7c91f12d..6c22d577a14e 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsSemilattice.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/PyReachingDefsSemilattice.java
@@ -33,7 +33,7 @@ public class PyReachingDefsSemilattice implements MapSemilattice
       return ins.get(0);
     }
 
-    ins = ins.stream().filter( e -> e != PyReachingDefsDfaInstance.UNREACHABLE_MARKER).toList();
+    ins = ins.stream().filter(e -> e != PyReachingDefsDfaInstance.UNREACHABLE_MARKER).toList();
 
     final Set resultNames = getResultNames(ins);
     if (resultNames == null || resultNames.isEmpty()) {
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/Scope.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/Scope.java
index 93857eb78e23..8265559da00c 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/Scope.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/Scope.java
@@ -43,9 +43,11 @@ public interface Scope {
                                     @NotNull TypeEvalContext typeEvalContext) throws DFALimitExceededException;
 
   boolean hasGlobals();
+
   boolean isGlobal(String name);
 
   boolean hasNonLocals();
+
   boolean isNonlocal(String name);
 
   boolean containsDeclaration(String name);
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/ScopeUtil.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/ScopeUtil.java
index 177ea58b4343..4c2d4a27b193 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/ScopeUtil.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/ScopeUtil.java
@@ -35,26 +35,26 @@ public final class ScopeUtil {
   private ScopeUtil() {
   }
 
-  public static @Nullable PsiElement getParameterScope(final PsiElement element){
-    if (element instanceof PyNamedParameter){
+  public static @Nullable PsiElement getParameterScope(final PsiElement element) {
+    if (element instanceof PyNamedParameter) {
       final PyFunction function = getParentOfType(element, PyFunction.class, false);
-      if (function != null){
+      if (function != null) {
         return function;
       }
     }
 
     final PyExceptPart exceptPart = PyExceptPartNavigator.getPyExceptPartByTarget(element);
-    if (exceptPart != null){
+    if (exceptPart != null) {
       return exceptPart;
     }
 
     final PyForStatement forStatement = PyForStatementNavigator.getPyForStatementByIterable(element);
-    if (forStatement != null){
+    if (forStatement != null) {
       return forStatement;
     }
 
     final PyListCompExpression listCompExpression = PyListCompExpressionNavigator.getPyListCompExpressionByVariable(element);
-    if (listCompExpression != null){
+    if (listCompExpression != null) {
       return listCompExpression;
     }
     return null;
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeImpl.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeImpl.java
index e78aacba7cb1..a856c1b8dcdf 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeImpl.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeImpl.java
@@ -232,10 +232,10 @@ public class ScopeImpl implements Scope {
         importStmt.accept(new PyVersionAwareElementVisitor(languageLevel) {
           @Override
           public void visitPyElement(@NotNull PyElement node) {
-           if (node instanceof PyImportedNameDefiner definer) {
-             importedNameDefiners.add(definer);
-           }
-           super.visitPyElement(node);
+            if (node instanceof PyImportedNameDefiner definer) {
+              importedNameDefiners.add(definer);
+            }
+            super.visitPyElement(node);
           }
         });
       }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeVariableImpl.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeVariableImpl.java
index c56f8efe2d90..fc82abef072c 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeVariableImpl.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/dataflow/scope/impl/ScopeVariableImpl.java
@@ -40,7 +40,7 @@ public class ScopeVariableImpl implements ScopeVariable {
 
   @Override
   public String toString() {
-    return (isParameter() ? "par" : "var") + "(" + myName+ ")[" + myDeclarations.size() + "]";
+    return (isParameter() ? "par" : "var") + "(" + myName + ")[" + myDeclarations.size() + "]";
   }
 
   @Override
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/decorator/PyDecoratedFunctionTypeProvider.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/decorator/PyDecoratedFunctionTypeProvider.java
index cefdb5bd7f92..4ca821cfcd9d 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/decorator/PyDecoratedFunctionTypeProvider.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/decorator/PyDecoratedFunctionTypeProvider.java
@@ -28,7 +28,9 @@ import static com.jetbrains.python.psi.types.PyTypeUtil.notNullToRef;
 public final class PyDecoratedFunctionTypeProvider extends PyTypeProviderBase {
 
   @Override
-  public @Nullable Ref getReferenceType(@NotNull PsiElement referenceTarget, @NotNull TypeEvalContext context, @Nullable PsiElement anchor) {
+  public @Nullable Ref getReferenceType(@NotNull PsiElement referenceTarget,
+                                                @NotNull TypeEvalContext context,
+                                                @Nullable PsiElement anchor) {
     if (!(referenceTarget instanceof PyDecoratable pyDecoratable)) {
       return null;
     }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationParser.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationParser.java
index 4759ad04fa88..4f9245e2ce24 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationParser.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/PyFunctionTypeAnnotationParser.java
@@ -85,10 +85,10 @@ public class PyFunctionTypeAnnotationParser extends PyParser {
       assert atToken(PyTokenTypes.LPAR);
       final SyntaxTreeBuilder.Marker listMark = myBuilder.mark();
       myBuilder.advanceLexer();
-      
+
       final ExpressionParsing exprParser = getExpressionParser();
       int paramCount = 0;
-      while (!(atAnyOfTokens(PyTokenTypes.RPAR, PyTokenTypes.RARROW, PyTokenTypes.STATEMENT_BREAK) || myBuilder.eof()) ) {
+      while (!(atAnyOfTokens(PyTokenTypes.RPAR, PyTokenTypes.RARROW, PyTokenTypes.STATEMENT_BREAK) || myBuilder.eof())) {
         if (paramCount > 0) {
           checkMatches(PyTokenTypes.COMMA, PyParsingBundle.message("PARSE.expected.comma"));
         }
@@ -110,7 +110,8 @@ public class PyFunctionTypeAnnotationParser extends PyParser {
         }
         if (!parsed) {
           myBuilder.error(PyParsingBundle.message("PARSE.expected.expression"));
-          recoverUntilMatches(PyParsingBundle.message("PARSE.expected.expression"), PyTokenTypes.COMMA, PyTokenTypes.RPAR, PyTokenTypes.RARROW, PyTokenTypes.STATEMENT_BREAK);
+          recoverUntilMatches(PyParsingBundle.message("PARSE.expected.expression"), PyTokenTypes.COMMA, PyTokenTypes.RPAR,
+                              PyTokenTypes.RARROW, PyTokenTypes.STATEMENT_BREAK);
         }
         paramCount++;
       }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/psi/PyFunctionTypeAnnotation.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/psi/PyFunctionTypeAnnotation.java
index be070496daa0..9e6645677c9c 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/psi/PyFunctionTypeAnnotation.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/functionTypeComments/psi/PyFunctionTypeAnnotation.java
@@ -31,8 +31,8 @@ public class PyFunctionTypeAnnotation extends PyElementImpl {
 
   public @NotNull PyParameterTypeList getParameterTypeList() {
     return findNotNullChildByClass(PyParameterTypeList.class);
-  }  
-  
+  }
+
   public @Nullable PyExpression getReturnType() {
     return findChildByClass(PyExpression.class);
   }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java
index 521ec7480323..b359e9120a0f 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/AddImportHelper.java
@@ -64,7 +64,9 @@ public final class AddImportHelper {
   }
 
   public static @NotNull Comparator getImportTextComparator(@NotNull PsiFile settingsAnchor) {
-    return PythonCodeStyleService.getInstance().isOptimizeImportsCaseSensitiveOrder(settingsAnchor) ? String.CASE_INSENSITIVE_ORDER : Comparator.naturalOrder();
+    return PythonCodeStyleService.getInstance().isOptimizeImportsCaseSensitiveOrder(settingsAnchor)
+           ? String.CASE_INSENSITIVE_ORDER
+           : Comparator.naturalOrder();
   }
 
   private static @NotNull List getSortNames(@NotNull PyImportStatementBase importStatement) {
@@ -161,7 +163,6 @@ public final class AddImportHelper {
     if (parentElement != null) {
       parentElement.addBefore(generator.createFromImportStatement(languageLevel, qualifier, name, asName), anchor);
     }
-
   }
 
   public static @Nullable PsiElement getLocalInsertPosition(@NotNull PsiElement anchor) {
@@ -368,7 +369,8 @@ public final class AddImportHelper {
     return getImportPriorityWithReason(importStatement, resolvedFileOrDir);
   }
 
-  static @NotNull ImportPriorityChoice getImportPriorityWithReason(@NotNull PsiElement importLocation, @NotNull PsiFileSystemItem toImport) {
+  static @NotNull ImportPriorityChoice getImportPriorityWithReason(@NotNull PsiElement importLocation,
+                                                                   @NotNull PsiFileSystemItem toImport) {
     final VirtualFile vFile = toImport.getVirtualFile();
     if (vFile == null) {
       return new ImportPriorityChoice(UNRESOLVED_SYMBOL_PRIORITY, toImport + " doesn't have an associated virtual file");
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java
index 40431b761d5a..d98c78dc2c72 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportCandidateHolder.java
@@ -100,7 +100,9 @@ public class ImportCandidateHolder implements Comparable
    * @param source     known ImportElement to import the name; its 'as' clause is used if present.
    * @return a properly qualified name.
    */
-  public static @NotNull String getQualifiedName(@NotNull String name, @Nullable QualifiedName importPath, @Nullable PyImportElement source) {
+  public static @NotNull String getQualifiedName(@NotNull String name,
+                                                 @Nullable QualifiedName importPath,
+                                                 @Nullable PyImportElement source) {
     final StringBuilder sb = new StringBuilder();
     if (source != null) {
       final PsiElement parent = source.getParent();
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java
index 5fce21a19e34..dae3126edac5 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/ImportFromExistingAction.java
@@ -34,9 +34,9 @@ public class ImportFromExistingAction implements QuestionAction {
   private final boolean myImportLocally;
 
   /**
-   * @param target element to become qualified as imported.
-   * @param sources clauses of import to be used.
-   * @param name relevant name ot the target element (e.g. of identifier in an expression).
+   * @param target       element to become qualified as imported.
+   * @param sources      clauses of import to be used.
+   * @param name         relevant name ot the target element (e.g. of identifier in an expression).
    * @param insertBefore import statement should be inserted right before this element. However, if it aims at an insertion statement in
    *                     a group of inserts, a better insertion point belonging the group may be chosen, and it can be after the specified
    *                     node. If null, the position will be chosen automatically.
@@ -201,5 +201,4 @@ public class ImportFromExistingAction implements QuestionAction {
       myOnDoneCallback.run();
     }
   }
-
 }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/PyRelativeImportData.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/PyRelativeImportData.kt
index f7495abc24ca..62b42725683d 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/PyRelativeImportData.kt
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/imports/PyRelativeImportData.kt
@@ -8,7 +8,7 @@ import com.jetbrains.python.psi.resolve.QualifiedNameFinder
 /**
  * @author Aleksei Kniazev
  */
-class PyRelativeImportData private constructor(val relativeLocation: String, val relativeLevel: Int)  {
+class PyRelativeImportData private constructor(val relativeLocation: String, val relativeLevel: Int) {
 
   val locationWithDots: String
     get() = ".".repeat(relativeLevel) + relativeLocation
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java
index 10d42b798577..a41cd530ca33 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java
@@ -51,7 +51,7 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
     while (scanner.find(index)) {
       if (scanner.start() > 1) {
         // handle escaping sequences PY-977
-        if ("{".equals(scanner.group(0)) && "\\N".equals(source.subSequence(scanner.start()-2, scanner.start()).toString())) {
+        if ("{".equals(scanner.group(0)) && "\\N".equals(source.subSequence(scanner.start() - 2, scanner.start()).toString())) {
           skipClosingBrace = true;
           target.append(source.subSequence(index, scanner.end()));
           index = scanner.end();
@@ -66,8 +66,12 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
       }
 
       target.append(source.subSequence(index, scanner.start()));
-      if ("{".equals(scanner.group(0))) target.append("{{");
-      else target.append("}}");
+      if ("{".equals(scanner.group(0))) {
+        target.append("{{");
+      }
+      else {
+        target.append("}}");
+      }
       index = scanner.end();
     }
     target.append(source.subSequence(index, source.length()));
@@ -75,6 +79,7 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
 
   /**
    * Converts format expressions inside a string
+   *
    * @return a pair of string builder with resulting string expression and a flag which is true if formats inside use mapping by name.
    */
   private static Pair convertFormat(PyStringLiteralExpression stringLiteralExpression, String prefix) {
@@ -97,12 +102,12 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
       sure("\"'".indexOf(quote) >= 0);
       if (text.length() - openPos >= 6) {
         // triple-quoted?
-        if (text.charAt(openPos+1) == quote && text.charAt(openPos+2) == quote) {
+        if (text.charAt(openPos + 1) == quote && text.charAt(openPos + 2) == quote) {
           openPos += 2;
         }
       }
       int index = openPos + 1; // from quote to first in-string char
-      StringBuilder out = new StringBuilder(text.subSequence(0, openPos+1));
+      StringBuilder out = new StringBuilder(text.subSequence(0, openPos + 1));
       if (!hasPrefix) out.insert(0, prefix);
       Matcher scanner = FORMAT_PATTERN.matcher(text);
       while (scanner.find(index)) {
@@ -136,7 +141,9 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
           if (f_width != null) {
             out.append(f_width);
           }
-          if ("i".equals(fConversion) || "u".equals(fConversion)) out.append("d");
+          if ("i".equals(fConversion) || "u".equals(fConversion)) {
+            out.append("d");
+          }
           else if (!"s".equals(fConversion) && !"r".equals(fConversion)) out.append(fConversion);
 
           final int lastIndexOf = out.lastIndexOf(":");
@@ -164,7 +171,7 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
       int left = prev_range.getEndOffset() - full_start;
       int right = next_range.getStartOffset() - full_start;
       if (left < right) {
-        constants.get(fragment_no-1).append(full_text.subSequence(left, right));
+        constants.get(fragment_no - 1).append(full_text.subSequence(left, right));
       }
       fragment_no += 1;
       prev_range = next_range;
@@ -173,7 +180,7 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
     final int right = full_range.getEndOffset() - full_start;
     if (left < right) {
       // the barely possible case of last dangling "\"
-      constants.get(constants.size()-1).append(full_text.subSequence(left, right));
+      constants.get(constants.size() - 1).append(full_text.subSequence(left, right));
     }
 
     // join everything
@@ -219,12 +226,13 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
       return false;
     }
 
-    PyBinaryExpression binaryExpression  =
+    PyBinaryExpression binaryExpression =
       PsiTreeUtil.getParentOfType(psiFile.findElementAt(editor.getCaretModel().getOffset()), PyBinaryExpression.class, false);
     if (binaryExpression == null) {
       return false;
     }
-    if (binaryExpression.getLeftExpression() instanceof PyStringLiteralExpression str && binaryExpression.getOperator() == PyTokenTypes.PERC) {
+    if (binaryExpression.getLeftExpression() instanceof PyStringLiteralExpression str &&
+        binaryExpression.getOperator() == PyTokenTypes.PERC) {
       if ((!str.getText().isEmpty() && Character.toUpperCase(str.getText().charAt(0)) == 'B')) {
         return false;
       }
@@ -290,7 +298,9 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
     else if (PyTypeUtil.isDict(rhsType)) {
       target.append("(**").append(paramText).append(")");
     }
-    else target.append("(").append(paramText).append(")"); // tuple is ok as is
+    else {
+      target.append("(").append(paramText).append(")"); // tuple is ok as is
+    }
     // Correctly handle multiline implicitly concatenated string literals (PY-9176)
     target.insert(0, '(').append(')');
     final PyExpression parenthesized = elementGenerator.createExpressionFromText(LanguageLevel.forElement(element), target.toString());
@@ -313,13 +323,15 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
     String separator = ""; // detect nontrivial whitespace around the "%"
     Pair crop = collectWhitespace(leftExpression);
     String maybeSeparator = crop.getFirst();
-    if (maybeSeparator != null && !maybeSeparator.isEmpty() && !" ".equals(maybeSeparator))
+    if (maybeSeparator != null && !maybeSeparator.isEmpty() && !" ".equals(maybeSeparator)) {
       separator = maybeSeparator;
+    }
     else { // after "%"
       crop = collectWhitespace(crop.getSecond());
       maybeSeparator = crop.getFirst();
-      if (maybeSeparator != null && !maybeSeparator.isEmpty() && !" ".equals(maybeSeparator))
+      if (maybeSeparator != null && !maybeSeparator.isEmpty() && !" ".equals(maybeSeparator)) {
         separator = maybeSeparator;
+      }
     }
     return separator;
   }
@@ -329,8 +341,12 @@ public final class ConvertFormatOperatorToMethodIntention extends PyBaseIntentio
     PsiElement seeker = start;
     while (seeker != null) {
       seeker = seeker.getNextSibling();
-      if (seeker instanceof PsiWhiteSpace) sb.append(seeker.getText());
-      else break;
+      if (seeker instanceof PsiWhiteSpace) {
+        sb.append(seeker.getText());
+      }
+      else {
+        break;
+      }
     }
     return Pair.create(sb.toString(), seeker);
   }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java
index 4f0a9d3e1b8e..d47167c9f0ae 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java
@@ -23,14 +23,15 @@ public final class DeclarationConflictChecker {
   /**
    * For each reference in the collection, finds a definition of name visible from the point of the reference. Returns a list of
    * such definitions.
-   * @param name what to look for.
+   *
+   * @param name       what to look for.
    * @param references references to check.
-   * @param ignored if an element defining the name is also listed here, ignore it.
+   * @param ignored    if an element defining the name is also listed here, ignore it.
    * @return a list of pairs (referring element, element that defines name).
    */
   public static @NotNull List> findDefinitions(@NotNull String name,
-                                                                   @NotNull Collection references,
-                                                                   @NotNull Set ignored) {
+                                                                            @NotNull Collection references,
+                                                                            @NotNull Set ignored) {
     final List> conflicts = new ArrayList<>();
     for (PsiReference ref : references) {
       final PsiElement refElement = ref.getElement();
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportFromToImportIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportFromToImportIntention.java
index ecd5a3ff9ff6..dcb7c91516f2 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportFromToImportIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportFromToImportIntention.java
@@ -93,7 +93,9 @@ public final class ImportFromToImportIntention extends PyBaseIntentionAction {
       if (remaining_module instanceof PyQualifiedExpression) {
         remaining_name = PyPsiUtils.toPath((PyQualifiedExpression)remaining_module);
       }
-      else remaining_name = ""; // unqualified name: "...module"
+      else {
+        remaining_name = ""; // unqualified name: "...module"
+      }
       separated_name = info.myModuleReference.getReferencedName();
       failure = false;
       if (separated_name == null) {
@@ -101,13 +103,17 @@ public final class ImportFromToImportIntention extends PyBaseIntentionAction {
         failure = true;
       }
     }
-    if (strict && failure) return null;
-    else return new String[] {getDots(info.myRelativeLevel)+remaining_name, separated_name};
+    if (strict && failure) {
+      return null;
+    }
+    else {
+      return new String[]{getDots(info.myRelativeLevel) + remaining_name, separated_name};
+    }
   }
 
   private static String getDots(int level) {
     String dots = "";
-    for (int i=0; i 0) {
         relative_names = getRelativeNames(true, info);
         if (relative_names == null) throw new IncorrectOperationException("failed to get relative names");
         qualifier = relative_names[1];
       }
-      else qualifier = info.myModuleName;
+      else {
+        qualifier = info.myModuleName;
+      }
       // find all unqualified references that lead to one of our import elements
       final PyImportElement[] ielts = info.myFromImportStatement.getImportElements();
       final PyStarImportElement star_ielt = info.myFromImportStatement.getStarImportElement();
@@ -211,7 +223,8 @@ public final class ImportFromToImportIntention extends PyBaseIntentionAction {
         sure(feeler instanceof PyQualifiedExpression); // if for some crazy reason module name refers to numbers, etc, no point to continue.
         top_qualifier = (PyQualifiedExpression)feeler;
         feeler = top_qualifier.getQualifier();
-      } while (feeler != null);
+      }
+      while (feeler != null);
       String top_name = top_qualifier.getName();
       Collection possible_targets = references.keySet();
       if (!star_references.isEmpty()) {
@@ -262,7 +275,8 @@ public final class ImportFromToImportIntention extends PyBaseIntentionAction {
         new_import = sure(generator.createFromText(level, PyImportStatement.class, "import " + info.myModuleName));
       }
       else {
-        new_import = sure(generator.createFromText(level, PyFromImportStatement.class, "from " + relative_names[0] + " import " + relative_names[1]));
+        new_import =
+          sure(generator.createFromText(level, PyFromImportStatement.class, "from " + relative_names[0] + " import " + relative_names[1]));
       }
       ASTNode parent = sure(info.myFromImportStatement.getParent().getNode());
       ASTNode old_node = sure(info.myFromImportStatement.getNode());
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToImportFromIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToImportFromIntention.java
index 946b3e8a8cb5..d1be4268d265 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToImportFromIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToImportFromIntention.java
@@ -115,7 +115,7 @@ public final class ImportToImportFromIntention extends PsiBasedModCommandAction<
         Collection referencesToUpdate = unqualifyAll ? myReferences : getSameNameReferences();
         for (PyReferenceExpression ref : referencesToUpdate) {
           final PsiElement parentElt = ref.getParent();
-          assert parentElt instanceof PyReferenceExpression: parentElt.getClass();
+          assert parentElt instanceof PyReferenceExpression : parentElt.getClass();
           final String nameUsed = Objects.requireNonNull(((PyReferenceExpression)parentElt).getReferencedName());
           usedNames.add(nameUsed);
           final PyElement newReference = generator.createExpressionFromText(languageLevel, nameUsed);
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToggleAliasIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToggleAliasIntention.java
index 1e6f48c3d50a..433a987307c3 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToggleAliasIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/ImportToggleAliasIntention.java
@@ -50,8 +50,12 @@ public final class ImportToggleAliasIntention extends PyBaseIntentionAction {
       if (state.myImportElement != null) {
         PyTargetExpression target = state.myImportElement.getAsNameElement();
         PyPsiUtils.assertValid(target);
-        if (target != null) state.myAlias = target.getName();
-        else state.myAlias = null;
+        if (target != null) {
+          state.myAlias = target.getName();
+        }
+        else {
+          state.myAlias = null;
+        }
         state.myFromImportStatement = PsiTreeUtil.getParentOfType(state.myImportElement, PyFromImportStatement.class);
         state.myImportStatement = PsiTreeUtil.getParentOfType(state.myImportElement, PyImportStatement.class);
       }
@@ -86,7 +90,7 @@ public final class ImportToggleAliasIntention extends PyBaseIntentionAction {
           add_name = PyPsiBundle.message("INTN.add.import.alias.to.name", refex.getText());
         }
       }
-      return myAlias == null? add_name : PyPsiBundle.message("INTN.remove.import.alias", myAlias);
+      return myAlias == null ? add_name : PyPsiBundle.message("INTN.remove.import.alias", myAlias);
     }
   }
 
@@ -135,18 +139,20 @@ public final class ImportToggleAliasIntention extends PyBaseIntentionAction {
       else {
         // ask for and add alias
         String alias = PythonUiService.getInstance().showInputDialog(project,
-                                                                     PyPsiBundle.message("INTN.add.import.alias.dialog.message", imported_name),
-                                                                     PyPsiBundle.message("INTN.add.import.alias.title"), "", new InputValidator() {
-            @Override
-            public boolean checkInput(String inputString) {
-              return PyNames.isIdentifier(inputString);
-            }
+                                                                     PyPsiBundle.message("INTN.add.import.alias.dialog.message",
+                                                                                         imported_name),
+                                                                     PyPsiBundle.message("INTN.add.import.alias.title"), "",
+                                                                     new InputValidator() {
+                                                                       @Override
+                                                                       public boolean checkInput(String inputString) {
+                                                                         return PyNames.isIdentifier(inputString);
+                                                                       }
 
-            @Override
-            public boolean canClose(String inputString) {
-              return PyNames.isIdentifier(inputString);
-            }
-        });
+                                                                       @Override
+                                                                       public boolean canClose(String inputString) {
+                                                                         return PyNames.isIdentifier(inputString);
+                                                                       }
+                                                                     });
         if (alias == null) {
           return;
         }
@@ -196,7 +202,8 @@ public final class ImportToggleAliasIntention extends PyBaseIntentionAction {
           }
         });
         // no references here is OK by us.
-        if (PythonUiService.getInstance().showConflicts(project, findDefinitions(target_name, references, Collections.emptySet()), target_name, null)) {
+        if (PythonUiService.getInstance()
+          .showConflicts(project, findDefinitions(target_name, references, Collections.emptySet()), target_name, null)) {
           return; // got conflicts
         }
 
@@ -217,7 +224,8 @@ public final class ImportToggleAliasIntention extends PyBaseIntentionAction {
           // add alias
           WriteAction.run(() -> {
             ASTNode my_ielt_node = sure(state.myImportElement.getNode());
-            PyImportElement fountain = generator.createFromText(languageLevel, PyImportElement.class, "import foo as "+target_name, new int[]{0,2});
+            PyImportElement fountain =
+              generator.createFromText(languageLevel, PyImportElement.class, "import foo as " + target_name, new int[]{0, 2});
             ASTNode graft_node = sure(fountain.getNode()); // at import elt
             graft_node = sure(graft_node.getFirstChildNode()); // at ref
             graft_node = sure(graft_node.getTreeNext()); // space
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAbsoluteToRelativeImportIntention.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAbsoluteToRelativeImportIntention.kt
index 4ee9c07bf59c..91cd8301f896 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAbsoluteToRelativeImportIntention.kt
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAbsoluteToRelativeImportIntention.kt
@@ -23,7 +23,7 @@ class PyAbsoluteToRelativeImportIntention : PyConvertImportIntentionAction("INTN
 
     val targetPath = statement.importSourceQName ?: return null
     val filePath = QualifiedNameFinder.findCanonicalImportPath(context.file, null) ?: return null
-    return if(targetPath.firstComponent == filePath.firstComponent) super.getPresentation(context, element) else null
+    return if (targetPath.firstComponent == filePath.firstComponent) super.getPresentation(context, element) else null
   }
 
   override fun invoke(context: ActionContext, element: PsiElement, updater: ModPsiUpdater) {
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateTypesIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateTypesIntention.java
index 5e81f0737644..f483e5527333 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateTypesIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateTypesIntention.java
@@ -169,7 +169,8 @@ public final class PyAnnotateTypesIntention extends PyBaseIntentionAction {
                                                                              offset);
     if (targetEditor != null) {
       builder.run(targetEditor, true);
-    } else {
+    }
+    else {
       builder.runNonInteractively(true);
     }
   }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateVariableTypeIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateVariableTypeIntention.java
index 4845eb15a830..da65625f47dc 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateVariableTypeIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyAnnotateVariableTypeIntention.java
@@ -88,9 +88,9 @@ public final class PyAnnotateVariableTypeIntention extends PyBaseIntentionAction
                                                                                    @NotNull Set alreadyVisited) {
     alreadyVisited.add(element);
     return StreamEx.of(PyUtil.multiResolveTopPriority(element, resolveContext))
-                   .filter(resolved -> resolved instanceof PyTargetExpression || !alreadyVisited.contains(resolved))
-                   .flatMap(resolved -> expandResolveAugAssignments(resolved, resolveContext, alreadyVisited))
-                   .distinct();
+      .filter(resolved -> resolved instanceof PyTargetExpression || !alreadyVisited.contains(resolved))
+      .flatMap(resolved -> expandResolveAugAssignments(resolved, resolveContext, alreadyVisited))
+      .distinct();
   }
 
   private static @NotNull StreamEx expandResolveAugAssignments(@NotNull PsiElement element,
@@ -150,7 +150,8 @@ public final class PyAnnotateVariableTypeIntention extends PyBaseIntentionAction
     return false;
   }
 
-  private static @NotNull List findClassLevelDefinitions(@NotNull PyTargetExpression target, @NotNull TypeEvalContext context) {
+  private static @NotNull List findClassLevelDefinitions(@NotNull PyTargetExpression target,
+                                                                             @NotNull TypeEvalContext context) {
     assert target.getContainingClass() != null;
     assert target.getName() != null;
     final PyClassTypeImpl classType = new PyClassTypeImpl(target.getContainingClass(), true);
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java
index 69ce7d097615..11ce489d15dc 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java
@@ -140,7 +140,7 @@ public abstract class PyBaseConvertCollectionLiteralIntention extends PsiUpdateM
     }
 
     final String replacedText = literal.getText();
-    
+
     final PsiElement firstChild = literal.getFirstChild();
     final int contentStartOffset;
     if (PyTokenTypes.OPEN_BRACES.contains(firstChild.getNode().getElementType())) {
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertLambdaToFunctionIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertLambdaToFunctionIntention.java
index d3c493b24ebb..b4d0a20a3aba 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertLambdaToFunctionIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertLambdaToFunctionIntention.java
@@ -47,7 +47,8 @@ public final class PyConvertLambdaToFunctionIntention extends PyBaseIntentionAct
       return false;
     }
 
-    PyLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(psiFile.findElementAt(editor.getCaretModel().getOffset()), PyLambdaExpression.class);
+    PyLambdaExpression lambdaExpression =
+      PsiTreeUtil.getParentOfType(psiFile.findElementAt(editor.getCaretModel().getOffset()), PyLambdaExpression.class);
     if (lambdaExpression != null) {
       if (lambdaExpression.getBody() != null) {
         final ControlFlow flow = ControlFlowCache.getControlFlow(lambdaExpression);
@@ -62,7 +63,8 @@ public final class PyConvertLambdaToFunctionIntention extends PyBaseIntentionAct
 
   @Override
   public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
-    PyLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyLambdaExpression.class);
+    PyLambdaExpression lambdaExpression =
+      PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyLambdaExpression.class);
     if (lambdaExpression != null) {
       String name = "function";
       while (IntroduceValidator.isDefinedInScope(name, lambdaExpression)) {
@@ -84,11 +86,12 @@ public final class PyConvertLambdaToFunctionIntention extends PyBaseIntentionAct
       PyFunction function = functionBuilder.buildFunction();
 
       final PyStatement statement = PsiTreeUtil.getParentOfType(lambdaExpression,
-                                                                 PyStatement.class);
+                                                                PyStatement.class);
       if (statement != null) {
         final PsiElement statementParent = statement.getParent();
-        if (statementParent != null)
+        if (statementParent != null) {
           function = (PyFunction)statementParent.addBefore(function, statement);
+        }
       }
 
       function = CodeInsightUtilCore
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertTypeCommentToVariableAnnotationIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertTypeCommentToVariableAnnotationIntention.java
index 0aaebdcad038..eaaf6be28ea4 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertTypeCommentToVariableAnnotationIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyConvertTypeCommentToVariableAnnotationIntention.java
@@ -119,7 +119,8 @@ public final class PyConvertTypeCommentToVariableAnnotationIntention extends PyB
     return Collections.emptyMap();
   }
 
-  private static @NotNull Map mapTargetsToAnnotations(@NotNull PyExpression targetExpr, @NotNull PsiComment typeComment) {
+  private static @NotNull Map mapTargetsToAnnotations(@NotNull PyExpression targetExpr,
+                                                                                  @NotNull PsiComment typeComment) {
     final PyTargetExpression firstTarget = PsiTreeUtil.findChildOfType(targetExpr, PyTargetExpression.class, false);
     if (firstTarget == null || firstTarget.getTypeComment() != typeComment) {
       return Collections.emptyMap();
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictConstructorToLiteralFormIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictConstructorToLiteralFormIntention.java
index d4e59c9e2c41..2e13efd461e6 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictConstructorToLiteralFormIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictConstructorToLiteralFormIntention.java
@@ -66,13 +66,14 @@ public final class PyDictConstructorToLiteralFormIntention extends PsiUpdateModC
         stringBuilder.append(((PyKeywordArgument)argument).getKeyword());
         stringBuilder.append("' : ");
         stringBuilder.append(((PyKeywordArgument)argument).getValueExpression().getText());
-        if (i != size-1)
+        if (i != size - 1) {
           stringBuilder.append(",");
+        }
       }
-
     }
-    PyDictLiteralExpression dict = (PyDictLiteralExpression)elementGenerator.createFromText(LanguageLevel.forElement(expression), PyExpressionStatement.class,
-                                                                                            "{" + stringBuilder + "}").getExpression();
+    PyDictLiteralExpression dict =
+      (PyDictLiteralExpression)elementGenerator.createFromText(LanguageLevel.forElement(expression), PyExpressionStatement.class,
+                                                               "{" + stringBuilder + "}").getExpression();
     expression.replace(dict);
   }
 }
diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictLiteralFormToConstructorIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictLiteralFormToConstructorIntention.java
index 42306976dcbd..59978bfb3d6e 100644
--- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictLiteralFormToConstructorIntention.java
+++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyDictLiteralFormToConstructorIntention.java
@@ -14,7 +14,7 @@ import org.jetbrains.annotations.Nullable;
 
 /**
  * User: catherine
- *
+ * 

* Intention to convert dict literal expression to dict constructor if the keys are all string constants on a literal dict. * For instance, * {} -> dict @@ -65,14 +65,16 @@ public final class PyDictLiteralFormToConstructorIntention extends PsiUpdateModC stringBuilder.append(((PyStringLiteralExpression)key).getStringValue()); stringBuilder.append("="); stringBuilder.append(value.getText()); - if (i != size-1) + if (i != size - 1) { stringBuilder.append(", "); + } } } } stringBuilder.append(")"); PyCallExpression callExpression = (PyCallExpression)elementGenerator.createFromText(LanguageLevel.forElement(dictExpression), - PyExpressionStatement.class, stringBuilder.toString()).getExpression(); + PyExpressionStatement.class, + stringBuilder.toString()).getExpression(); dictExpression.replace(callExpression); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFStringToTStringIntention.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFStringToTStringIntention.kt index d5c5f1e9fa3d..64f2bac5f490 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFStringToTStringIntention.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFStringToTStringIntention.kt @@ -16,7 +16,7 @@ import com.jetbrains.python.psi.* class PyFStringToTStringIntention : PsiUpdateModCommandAction(PyFormattedStringElement::class.java) { override fun getPresentation(context: ActionContext, stringElement: PyFormattedStringElement): Presentation? { if (LanguageLevel.forElement(stringElement).isOlderThan(LanguageLevel.PYTHON314)) return null - + val stringLiteral = stringElement.getParent() as? PyStringLiteralExpression ?: return null val docStringOwner = stringLiteral.parentOfType() if (docStringOwner != null && docStringOwner.getDocStringExpression() === stringLiteral) return null diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFlipComparisonIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFlipComparisonIntention.java index d3190de3fdc3..2289e0023dbe 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFlipComparisonIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyFlipComparisonIntention.java @@ -44,7 +44,7 @@ public final class PyFlipComparisonIntention extends PsiUpdateModCommandAction

(PsiEl return if (ifStatement != null && ifStatement.elifParts.isEmpty() && isAvailableForIfStatement(element, ifStatement) && - ifStatement.ifPart.condition?.let(::isValidConditionExpression) != false) super.getPresentation(context, element) else null + ifStatement.ifPart.condition?.let(::isValidConditionExpression) != false) super.getPresentation(context, element) + else null } @@ -188,7 +189,8 @@ class PyInvertIfConditionIntention : PsiUpdateModCommandAction(PsiEl } private fun invertIfStatementFollowup( - project: Project, file: PsiFile, statement: PyIfStatement, terminableStatement: PyStatementListContainer) { + project: Project, file: PsiFile, statement: PyIfStatement, terminableStatement: PyStatementListContainer, + ) { statement.ifPart.condition?.let { it.replace(getInvertedConditionExpression(project, file, it)) } val ifStatements = statement.ifPart.statementList diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyJoinIfIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyJoinIfIntention.java index e0c08b69be22..e3cd6026c8fe 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyJoinIfIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyJoinIfIntention.java @@ -25,17 +25,17 @@ import static com.jetbrains.python.psi.PyUtil.as; * Intention to merge the if clauses in the case of nested ifs where only the inner if contains code (the outer if only contains the inner one) * For instance, * if a: - * if b: - * # stuff here + * if b: + * # stuff here * into * if a and b: - * #stuff here + * #stuff here */ public final class PyJoinIfIntention extends PsiUpdateModCommandAction { public PyJoinIfIntention() { super(PyIfStatement.class); } - + @Override public @NotNull String getFamilyName() { return PyPsiBundle.message("INTN.NAME.join.if"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyQuotedStringIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyQuotedStringIntention.java index c9c3729ac8a6..40613d7a143f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyQuotedStringIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyQuotedStringIntention.java @@ -70,7 +70,8 @@ public final class PyQuotedStringIntention extends PsiUpdateModCommandAction s.getQuote().equals(originalQuote) && PyQuotesUtil.canBeConverted(s, true)); + s -> s.getQuote().equals(originalQuote) && + PyQuotesUtil.canBeConverted(s, true)); if (entireLiteralCanBeConverted) { stringLiteral.getStringElements().forEach(PyQuotedStringIntention::convertStringElement); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PySplitIfIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PySplitIfIntention.java index 0c20317b1c4e..082f8f398647 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PySplitIfIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PySplitIfIntention.java @@ -51,7 +51,7 @@ public final class PySplitIfIntention extends PyBaseIntentionAction { element = element.getParent(); } if (((PyBinaryExpression)element).getOperator() != PyTokenTypes.AND_KEYWORD - || ((PyBinaryExpression) element).getRightExpression() == null) { + || ((PyBinaryExpression)element).getRightExpression() == null) { return false; } final PsiElement parent = element.getParent(); @@ -83,19 +83,21 @@ public final class PySplitIfIntention extends PyBaseIntentionAction { PyIfStatement ifStatement = PsiTreeUtil.getParentOfType(element, PyIfStatement.class); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); - PyIfStatement subIf = (PyIfStatement) ifStatement.copy(); + PyIfStatement subIf = (PyIfStatement)ifStatement.copy(); subIf.getIfPart().getCondition().replace(element.getRightExpression()); ifStatement.getIfPart().getCondition().replace(element.getLeftExpression()); - PyStatementList statementList = elementGenerator.createFromText(LanguageLevel.getDefault(), PyIfStatement.class, "if a:\n a = 1").getIfPart().getStatementList(); + PyStatementList statementList = + elementGenerator.createFromText(LanguageLevel.getDefault(), PyIfStatement.class, "if a:\n a = 1").getIfPart().getStatementList(); statementList.getStatements()[0].replace(subIf); PyIfStatement newIf = elementGenerator.createFromText(LanguageLevel.getDefault(), PyIfStatement.class, "if a:\n a = 1"); newIf.getIfPart().getCondition().replace(ifStatement.getIfPart().getCondition()); newIf.getIfPart().getStatementList().replace(statementList); - for (PyIfPart elif : ifStatement.getElifParts()) + for (PyIfPart elif : ifStatement.getElifParts()) { newIf.add(elif); + } if (ifStatement.getElsePart() != null) { - newIf.add(ifStatement.getElsePart()); + newIf.add(ifStatement.getElsePart()); } ifStatement.replace(newIf); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyTypeHintGenerationUtil.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyTypeHintGenerationUtil.java index bc478e6ddd2c..7adbe3701759 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyTypeHintGenerationUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyTypeHintGenerationUtil.java @@ -315,7 +315,7 @@ public final class PyTypeHintGenerationUtil { if (type == null || isNoneType(type) || // Will be rendered as just Any - type instanceof PyUnsafeUnionType || + type instanceof PyUnsafeUnionType || type instanceof PyTypeParameterType) { return; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyYieldFromIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyYieldFromIntention.java index 80fd0d1eb97c..302fec90036b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyYieldFromIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/PyYieldFromIntention.java @@ -51,20 +51,20 @@ public final class PyYieldFromIntention extends PsiUpdateModCommandAction * Helps to specify type by assertion */ public final class TypeAssertionIntention extends PyBaseIntentionAction { @@ -74,8 +74,9 @@ public final class TypeAssertionIntention extends PyBaseIntentionAction { final PyExpression qualifier = problemElement.getQualifier(); if (qualifier != null && !qualifier.getText().equals(PyNames.CANONICAL_SELF)) { final String referencedName = problemElement.getReferencedName(); - if (referencedName == null || PyNames.GETITEM.equals(referencedName)) + if (referencedName == null || PyNames.GETITEM.equals(referencedName)) { name = qualifier.getText(); + } } final String text = "assert isinstance(" + name + ", )"; @@ -97,20 +98,25 @@ public final class TypeAssertionIntention extends PyBaseIntentionAction { if (statementList != null) { PsiElement statementListParent = PsiTreeUtil.getParentOfType(statementList, PyStatement.class); if (statementListParent != null && document.getLineNumber(statementList.getTextOffset()) == - document.getLineNumber(statementListParent.getTextOffset())) { + document.getLineNumber(statementListParent.getTextOffset())) { final String substring = - TextRange.create(statementListParent.getTextRange().getStartOffset(), statementList.getTextOffset()).substring(document.getText()); + TextRange.create(statementListParent.getTextRange().getStartOffset(), statementList.getTextOffset()) + .substring(document.getText()); final PyStatement foo = - elementGenerator.createFromText(LanguageLevel.forElement(problemElement), PyStatement.class, substring + "\n\t" + - text + "\n\t" + statementList.getText()); + elementGenerator.createFromText(LanguageLevel.forElement(problemElement), PyStatement.class, substring + + "\n\t" + + text + + "\n\t" + + statementList.getText()); statementListParent = statementListParent.replace(foo); statementList = PsiTreeUtil.findChildOfType(statementListParent, PyStatementList.class); assert statementList != null; element = statementList.getStatements()[0]; } - else + else { element = parent.addBefore(assertStatement, parentStatement); + } } else { element = parent.addBefore(assertStatement, parentStatement); @@ -122,7 +128,7 @@ public final class TypeAssertionIntention extends PyBaseIntentionAction { element = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(element); final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(element); - builder.replaceRange(TextRange.create(text.length()-1, text.length()-1), PyNames.OBJECT); + builder.replaceRange(TextRange.create(text.length() - 1, text.length() - 1), PyNames.OBJECT); builder.run(editor, true); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/TypeIntention.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/TypeIntention.java index a51dc96b4279..b6b75d8ffb5c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/TypeIntention.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/intentions/TypeIntention.java @@ -48,7 +48,9 @@ public abstract class TypeIntention extends PyBaseIntentionAction { return findOnlySuitableFunction(editor, file, input -> !isReturnTypeDefined(input)); } - public static @Nullable PyFunction findOnlySuitableFunction(@NotNull Editor editor, @NotNull PsiFile file, Predicate condition) { + public static @Nullable PyFunction findOnlySuitableFunction(@NotNull Editor editor, + @NotNull PsiFile file, + Predicate condition) { final PsiElement elementAt = getElementUnderCaret(editor, file); return elementAt != null ? ContainerUtil.getOnlyItem(findSuitableFunctions(elementAt, condition)) : null; } @@ -64,7 +66,7 @@ public abstract class TypeIntention extends PyBaseIntentionAction { final PyReferenceExpression referenceExpr = PsiTreeUtil.getParentOfType(elementAt, PyReferenceExpression.class); if (referenceExpr != null) { parameters = StreamEx.of(PyUtil.multiResolveTopPriority(referenceExpr, getResolveContext(elementAt))) - .select(PyNamedParameter.class); + .select(PyNamedParameter.class); } else { parameters = StreamEx.empty(); @@ -93,7 +95,8 @@ public abstract class TypeIntention extends PyBaseIntentionAction { protected abstract boolean isReturnTypeDefined(@NotNull PyFunction function); - private static @NotNull List findSuitableFunctions(@NotNull PsiElement elementAt, @NotNull Predicate extraCondition) { + private static @NotNull List findSuitableFunctions(@NotNull PsiElement elementAt, + @NotNull Predicate extraCondition) { final StreamEx definitions; final PyFunction immediateDefinition = findFunctionDefinitionUnderCaret(elementAt); if (immediateDefinition != null) { @@ -101,9 +104,9 @@ public abstract class TypeIntention extends PyBaseIntentionAction { } else { definitions = StreamEx.of(getCallExpressions(elementAt)) - .flatMap(call -> StreamEx.of(call.multiResolveCallee(getResolveContext(elementAt)))) - .map(result -> result.getCallable()) - .select(PyFunction.class); + .flatMap(call -> StreamEx.of(call.multiResolveCallee(getResolveContext(elementAt)))) + .map(result -> result.getCallable()) + .select(PyFunction.class); } final ProjectFileIndex index = ProjectFileIndex.getInstance(elementAt.getProject()); return definitions @@ -120,7 +123,7 @@ public abstract class TypeIntention extends PyBaseIntentionAction { if (parentFunction != null) { final ASTNode nameNode = parentFunction.getNameNode(); if (nameNode != null) { - final PsiElement prev = elementAt.getContainingFile().findElementAt(elementAt.getTextOffset()-1); + final PsiElement prev = elementAt.getContainingFile().findElementAt(elementAt.getTextOffset() - 1); if (nameNode.getPsi() == elementAt || nameNode.getPsi() == prev) { return parentFunction; } @@ -134,11 +137,11 @@ public abstract class TypeIntention extends PyBaseIntentionAction { final PyReferenceExpression referenceExpr = PsiTreeUtil.getParentOfType(elementAt, PyReferenceExpression.class); if (referenceExpr != null) { final List calls = StreamEx.of(PyUtil.multiResolveTopPriority(referenceExpr, context)) - .select(PyTargetExpression.class) - .filter(target -> context.getTypeEvalContext().maySwitchToAST(target)) - .map(target -> target.findAssignedValue()) - .select(PyCallExpression.class) - .toList(); + .select(PyTargetExpression.class) + .filter(target -> context.getTypeEvalContext().maySwitchToAST(target)) + .map(target -> target.findAssignedValue()) + .select(PyCallExpression.class) + .toList(); if (!calls.isEmpty()) { return calls; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTupleTypeProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTupleTypeProvider.kt index 9a1a1d93c0af..d1e79d73108e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTupleTypeProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTupleTypeProvider.kt @@ -223,9 +223,11 @@ class PyNamedTupleTypeProvider : PyTypeProviderBase() { getDeclaration(targetOrCall)) } - private fun createTypedNamedTupleReplaceType(anchor: PsiElement, - fields: ImmutableNTFields, - qualifierType: PyClassLikeType): PyCallableType { + private fun createTypedNamedTupleReplaceType( + anchor: PsiElement, + fields: ImmutableNTFields, + qualifierType: PyClassLikeType, + ): PyCallableType { val parameters = mutableListOf() val resultType = qualifierType.toInstance() val elementGenerator = PyElementGenerator.getInstance(anchor.project) @@ -244,10 +246,12 @@ class PyNamedTupleTypeProvider : PyTypeProviderBase() { return PyCallableTypeImpl(parameters, resultType) } - private fun createUntypedNamedTupleReplaceType(anchor: PsiElement, - fields: ImmutableNTFields, - qualifierType: PyClassLikeType, - context: TypeEvalContext): PyCallableType? { + private fun createUntypedNamedTupleReplaceType( + anchor: PsiElement, + fields: ImmutableNTFields, + qualifierType: PyClassLikeType, + context: TypeEvalContext, + ): PyCallableType? { val call = anchor as? PyCallExpression ?: return null val parameters = mutableListOf() val resultType = qualifierType.toInstance() @@ -317,10 +321,12 @@ class PyNamedTupleTypeProvider : PyTypeProviderBase() { return result } - private fun parseNamedTupleField(anchor: PsiElement, - type: String?, - hasDefault: Boolean, - context: TypeEvalContext): PyNamedTupleType.FieldTypeAndDefaultValue { + private fun parseNamedTupleField( + anchor: PsiElement, + type: String?, + hasDefault: Boolean, + context: TypeEvalContext, + ): PyNamedTupleType.FieldTypeAndDefaultValue { val pyType = type?.let { Ref.deref(PyTypingTypeProvider.getStringBasedType(type, anchor, context)) } val defaultValue = if (hasDefault) PyElementGenerator.getInstance(anchor.project).createEllipsis() else null return PyNamedTupleType.FieldTypeAndDefaultValue(pyType, defaultValue) diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyOverridingClassDunderMembersProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyOverridingClassDunderMembersProvider.kt index 5d4bee5fe2d6..f06279651639 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyOverridingClassDunderMembersProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyOverridingClassDunderMembersProvider.kt @@ -51,10 +51,12 @@ class PyOverridingClassDunderMembersProvider : PyClassMembersProviderBase(), PyO return result } - private fun processDunderClass(type: PyClassType, - location: PyExpression?, - direction: AccessDirection, - context: TypeEvalContext): List { + private fun processDunderClass( + type: PyClassType, + location: PyExpression?, + direction: AccessDirection, + context: TypeEvalContext, + ): List { return if (type.isDefinition && type.pyClass.isNewStyleClass(context) || /* override */ !type.isDefinition && !type.pyClass.isNewStyleClass(context) /* provide */) { resolveInObject(type, PyNames.__CLASS__, location, direction, context) @@ -62,22 +64,26 @@ class PyOverridingClassDunderMembersProvider : PyClassMembersProviderBase(), PyO else emptyList() } - private fun processNotOverridden(type: PyClassType, - name: String, - location: PyExpression?, - direction: AccessDirection, - context: TypeEvalContext, - overridden: Boolean): List { + private fun processNotOverridden( + type: PyClassType, + name: String, + location: PyExpression?, + direction: AccessDirection, + context: TypeEvalContext, + overridden: Boolean, + ): List { return if (!overridden) resolveInObject(type, name, location, direction, context) else emptyList() } private fun toCustomMembers(name: String, resolved: List) = resolved.map { PyCustomMember(name, it) } - private fun resolveInObject(type: PyClassType, - name: String, - location: PyExpression?, - direction: AccessDirection, - context: TypeEvalContext): List { + private fun resolveInObject( + type: PyClassType, + name: String, + location: PyExpression?, + direction: AccessDirection, + context: TypeEvalContext, + ): List { val objectType = PyBuiltinCache.getInstance(type.pyClass).objectType ?: return emptyList() val resolveContext = PyResolveContext.defaultContext(context) val results = objectType.resolveMember(name, location, direction, resolveContext) ?: return emptyList() diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibOverridingModuleMembersProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibOverridingModuleMembersProvider.kt index 2fb3abbc5835..62fd17b61fff 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibOverridingModuleMembersProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibOverridingModuleMembersProvider.kt @@ -11,7 +11,7 @@ import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.types.PyOverridingModuleMembersProvider import com.jetbrains.python.psi.types.TypeEvalContext -class PyStdlibOverridingModuleMembersProvider: PyOverridingModuleMembersProvider() { +class PyStdlibOverridingModuleMembersProvider : PyOverridingModuleMembersProvider() { override fun getMembersByQName(module: PyFile, qName: String, context: TypeEvalContext): List = emptyList() @@ -19,7 +19,8 @@ class PyStdlibOverridingModuleMembersProvider: PyOverridingModuleMembersProvider if (module.languageLevel.isPython2 && name == "md5" && module.name == "hashlib.py" && - module.getQName() == QualifiedName.fromComponents("hashlib")) { + module.getQName() == QualifiedName.fromComponents("hashlib") + ) { // When module member is not found in it, // `__all__` and nearby module with the specified name are suggested as a fallback. diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibTypeProvider.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibTypeProvider.java index 1511dfbb3ec8..4668a13b4387 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibTypeProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/stdlib/PyStdlibTypeProvider.java @@ -112,7 +112,7 @@ public final class PyStdlibTypeProvider extends PyTypeProviderBase { else if ("enum.StrEnum.value".equals(name) && anchor instanceof PyReferenceExpression) { return Ref.create(PyBuiltinCache.getInstance(referenceTarget).getStrType()); } - else if ((PyNames.TYPE_ENUM_FLAG + ".value").equals(name)&& anchor instanceof PyReferenceExpression) { + else if ((PyNames.TYPE_ENUM_FLAG + ".value").equals(name) && anchor instanceof PyReferenceExpression) { return Ref.create(PyBuiltinCache.getInstance(referenceTarget).getIntType()); } else if ((PyNames.TYPE_ENUM + ".value").equals(name) && @@ -297,8 +297,8 @@ public final class PyStdlibTypeProvider extends PyTypeProviderBase { EnumAttributeKind attributeKind; if (isMember) { attributeKind = type instanceof PyLiteralType literalType && literalType.getPyClass().equals(enumClass) - ? EnumAttributeKind.MEMBER_ALIAS - : EnumAttributeKind.MEMBER; + ? EnumAttributeKind.MEMBER_ALIAS + : EnumAttributeKind.MEMBER; } else { attributeKind = EnumAttributeKind.NONMEMBER; @@ -336,7 +336,9 @@ public final class PyStdlibTypeProvider extends PyTypeProviderBase { private static @Nullable PyType getEnumAutoConstructorType(@NotNull PsiElement target, @NotNull TypeEvalContext context, @Nullable PsiElement anchor) { - if (target instanceof PyClass && PyNames.TYPE_ENUM_AUTO.equals(((PyClass)target).getQualifiedName()) && anchor instanceof PyCallExpression) { + if (target instanceof PyClass && + PyNames.TYPE_ENUM_AUTO.equals(((PyClass)target).getQualifiedName()) && + anchor instanceof PyCallExpression) { PyClassLikeType classType = as(context.getType((PyTypedElement)target), PyClassLikeType.class); if (classType != null) { return new PyCallableTypeImpl(Collections.emptyList(), classType.toInstance()); @@ -387,7 +389,9 @@ public final class PyStdlibTypeProvider extends PyTypeProviderBase { } @Override - public @Nullable Ref getCallType(@NotNull PyFunction function, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { + public @Nullable Ref getCallType(@NotNull PyFunction function, + @NotNull PyCallSiteExpression callSite, + @NotNull TypeEvalContext context) { final String qname = function.getQualifiedName(); if (qname != null) { if ("tuple.__new__".equals(qname) && callSite instanceof PyCallExpression) { @@ -446,7 +450,8 @@ public final class PyStdlibTypeProvider extends PyTypeProviderBase { return null; } - private static @Nullable Ref getTupleConcatenationResultType(@NotNull PyBinaryExpression addition, @NotNull TypeEvalContext context) { + private static @Nullable Ref getTupleConcatenationResultType(@NotNull PyBinaryExpression addition, + @NotNull TypeEvalContext context) { if (addition.getRightExpression() != null) { final PyTupleType leftTupleType = as(context.getType(addition.getLeftExpression()), PyTupleType.class); final PyTupleType rightTupleType = as(context.getType(addition.getRightExpression()), PyTupleType.class); diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyStubPackages.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyStubPackages.kt index a83e7687c2a5..d6bf5af6a73a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyStubPackages.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyStubPackages.kt @@ -46,10 +46,12 @@ fun convertStubToRuntimePackageName(name: QualifiedName): QualifiedName { * * Requires [withoutStubs] to be False and [dir] to be lib root. */ -fun findStubPackage(dir: PsiDirectory, - referencedName: String, - checkForPackage: Boolean, - withoutStubs: Boolean): Set? { +fun findStubPackage( + dir: PsiDirectory, + referencedName: String, + checkForPackage: Boolean, + withoutStubs: Boolean, +): Set? { if (!withoutStubs && dir.virtualFile.let { it == getClassOrContentOrSourceRoot(dir.project, it) }) { val stubPackageName = "$referencedName$STUBS_SUFFIX" val stubPackage = dir.findSubdirectory(stubPackageName) @@ -145,7 +147,8 @@ internal fun isInInlinePackage(element: PsiElement, module: Module?): Boolean { val cached = element.getUserData(INLINE_PACKAGE_KEY) if (cached != null) return cached - val result = !PyiUtil.isPyiFileOfPackage(element) && (element is PyFile || PyUtil.turnDirIntoInit(element) is PyFile) && getPyTyped(element) != null + val result = !PyiUtil.isPyiFileOfPackage(element) && (element is PyFile || PyUtil.turnDirIntoInit(element) is PyFile) && getPyTyped( + element) != null element.putUserData(INLINE_PACKAGE_KEY, result) return result diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeProviderWithCustomContext.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeProviderWithCustomContext.java index 64c63653aa6c..9541f66e8864 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeProviderWithCustomContext.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeProviderWithCustomContext.java @@ -17,7 +17,8 @@ import java.util.function.Function; @ApiStatus.Internal public abstract class PyTypeProviderWithCustomContext extends PyTypeProviderBase { @Override - public final @Nullable PyType getReferenceExpressionType(@NotNull PyReferenceExpression referenceExpression, @NotNull TypeEvalContext context) { + public final @Nullable PyType getReferenceExpressionType(@NotNull PyReferenceExpression referenceExpression, + @NotNull TypeEvalContext context) { return withCustomContext(context, customContext -> { return getReferenceExpressionType(referenceExpression, customContext); }); @@ -28,7 +29,9 @@ public abstract class PyTypeProviderWithCustomContext extends PyTypePro } @Override - public final Ref getReferenceType(@NotNull PsiElement referenceTarget, @NotNull TypeEvalContext context, @Nullable PsiElement anchor) { + public final Ref getReferenceType(@NotNull PsiElement referenceTarget, + @NotNull TypeEvalContext context, + @Nullable PsiElement anchor) { return withCustomContext(context, customContext -> { return getReferenceType(referenceTarget, customContext, anchor); }); @@ -40,8 +43,8 @@ public abstract class PyTypeProviderWithCustomContext extends PyTypePro @Override public final @Nullable Ref getParameterType(@NotNull PyNamedParameter param, - @NotNull PyFunction func, - @NotNull TypeEvalContext context) { + @NotNull PyFunction func, + @NotNull TypeEvalContext context) { return withCustomContext(context, customContext -> { return getParameterType(param, func, customContext); }); @@ -64,8 +67,8 @@ public abstract class PyTypeProviderWithCustomContext extends PyTypePro @Override public final @Nullable Ref getCallType(@NotNull PyFunction function, - @NotNull PyCallSiteExpression callSite, - @NotNull TypeEvalContext context) { + @NotNull PyCallSiteExpression callSite, + @NotNull TypeEvalContext context) { return withCustomContext(context, customContext -> { return getCallType(function, callSite, customContext); }); @@ -76,7 +79,9 @@ public abstract class PyTypeProviderWithCustomContext extends PyTypePro } @Override - public final @Nullable PyType getContextManagerVariableType(PyClass contextManager, PyExpression withExpression, TypeEvalContext context) { + public final @Nullable PyType getContextManagerVariableType(PyClass contextManager, + PyExpression withExpression, + TypeEvalContext context) { return withCustomContext(context, customContext -> { return getContextManagerVariableType(contextManager, withExpression, customContext); }); @@ -121,8 +126,8 @@ public abstract class PyTypeProviderWithCustomContext extends PyTypePro @Override public final @Nullable Ref<@Nullable PyCallableType> prepareCalleeTypeForCall(@Nullable PyType type, - @NotNull PyCallExpression call, - @NotNull TypeEvalContext context) { + @NotNull PyCallExpression call, + @NotNull TypeEvalContext context) { return withCustomContext(context, customContext -> { return prepareCalleeTypeForCall(type, call, customContext); }); diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt index 915a0b70d7fd..7a4d50e3c652 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt @@ -220,8 +220,8 @@ object PyTypeShed { "${PathManager.getConfigPath()}/../typeshed", PythonHelpersLocator.findPathStringInHelpers("typeshed")) return paths.asSequence() - .filter { File(it).exists() } - .firstOrNull() + .filter { File(it).exists() } + .firstOrNull() } fun isInThirdPartyLibraries(file: VirtualFile): Boolean = diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictTypeProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictTypeProvider.kt index f58f59177541..e32a878422c7 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictTypeProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypedDictTypeProvider.kt @@ -371,12 +371,14 @@ class PyTypedDictTypeProvider : PyTypeProviderBase() { return PyTypedDictType.FieldTypeAndTotality(null, pyType, qualifiers) } - private fun getStringBasedTypeForTypedDict(contents: String, - anchor: PsiElement, - context: TypeEvalContext): Pair?, PyTypedDictType.TypedDictFieldQualifiers?>? { + private fun getStringBasedTypeForTypedDict( + contents: String, + anchor: PsiElement, + context: TypeEvalContext, + ): Pair?, PyTypedDictType.TypedDictFieldQualifiers?>? { val file = FileContextUtil.getContextFile(anchor) ?: return null val expr = PyUtil.createExpressionFromFragment(contents, file) - var qualifiers: PyTypedDictType.TypedDictFieldQualifiers ? = null + var qualifiers: PyTypedDictType.TypedDictFieldQualifiers? = null if (expr is PySubscriptionExpression) { qualifiers = parseTypedDictFieldQualifiers(expr, context) } diff --git a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingTypeProvider.java b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingTypeProvider.java index 86e5399240bb..d439e7108379 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingTypeProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyTypingTypeProvider.java @@ -1147,8 +1147,9 @@ public final class PyTypingTypeProvider extends PyTypeProviderWithCustomContext< var class_ = PyPsiFacade.getInstance(element.getProject()).createClassByQName(element.getText(), element); type = class_ != null ? class_.getType(typeContext) : null; } - else + else { type = typeContext.getType((PyTypedElement)element); + } if (type instanceof PyClassLikeType classLikeType) { if (classLikeType.isDefinition()) { // If we're interpreting a type hint like "MyGeneric" that is not followed by a list of type arguments (e.g. MyGeneric[int]), @@ -2345,7 +2346,9 @@ public final class PyTypingTypeProvider extends PyTypeProviderWithCustomContext< return staticWithCustomContext(context, false, delegate); } - private static T staticWithCustomContext(@NotNull TypeEvalContext context, boolean useFqn, @NotNull Function<@NotNull Context, T> delegate) { + private static T staticWithCustomContext(@NotNull TypeEvalContext context, + boolean useFqn, + @NotNull Function<@NotNull Context, T> delegate) { Context customContext = context.getProcessingContext().get(TYPE_HINT_EVAL_CONTEXT); boolean firstEntrance = customContext == null; if (firstEntrance) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java b/python/python-psi-impl/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java index 3400b36c5ebb..4c8660c3f857 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/debugger/PySignatureCacheManagerImpl.java @@ -107,7 +107,8 @@ public final class PySignatureCacheManagerImpl extends PySignatureCacheManager { } else { //noinspection ConstantConditions - return signatureToString(stringToSignature(filePath, oldSignatureString).addAllArgs(signature).addReturnType(signature.getReturnTypeQualifiedName())); + return signatureToString( + stringToSignature(filePath, oldSignatureString).addAllArgs(signature).addReturnType(signature.getReturnTypeQualifiedName())); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/defaultProjectAwareService/PyDefaultProjectAwareModuleConfiguratorImpl.java b/python/python-psi-impl/src/com/jetbrains/python/defaultProjectAwareService/PyDefaultProjectAwareModuleConfiguratorImpl.java index 1f7d3bbf7939..fda67c86a2a1 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/defaultProjectAwareService/PyDefaultProjectAwareModuleConfiguratorImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/defaultProjectAwareService/PyDefaultProjectAwareModuleConfiguratorImpl.java @@ -62,8 +62,8 @@ public final class PyDefaultProjectAwareModuleConfiguratorImpl< Collection pyFiles = ReadAction.nonBlocking(() -> FilenameIndex .getAllFilesByExt(project, extension, searchScope)) - .inSmartMode(project) - .executeSynchronously(); + .inSmartMode(project) + .executeSynchronously(); STATE state = detector.fun(Pair.create(module, pyFiles)); if (state != null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationBuilder.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationBuilder.java index 0075c76d0860..6cdc4d1e779c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationBuilder.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationBuilder.java @@ -373,7 +373,7 @@ public final class PyDocumentationBuilder { final PyStringLiteralExpression effectiveDocstring = modifyDocStringByOwnerType(ownDocstring, elementDefinition, isProperty); if (PyUtil.isTopLevel(elementDefinition)) { - final PsiFile containing = ObjectUtils.chooseNotNull(PyiUtil.getOriginalElement(elementDefinition), + final PsiFile containing = ObjectUtils.chooseNotNull(PyiUtil.getOriginalElement(elementDefinition), elementDefinition).getContainingFile(); if (containing instanceof PyFile) { final HtmlChunk linkToModule = getLinkToModule((PyFile)containing); @@ -837,7 +837,9 @@ public final class PyDocumentationBuilder { return Objects.hash(body, fragments); } - @NotNull @NlsSafe String getBody() { + @NotNull + @NlsSafe + String getBody() { return body; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationLink.kt b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationLink.kt index 92d688b5b04f..d6ea59b57b7a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationLink.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyDocumentationLink.kt @@ -78,7 +78,7 @@ object PyDocumentationLink { } @JvmStatic - fun toTypeAliasStatement(@NlsSafe content: String, typeAliasStatement: PyTypeAliasStatement) : HtmlChunk { + fun toTypeAliasStatement(@NlsSafe content: String, typeAliasStatement: PyTypeAliasStatement): HtmlChunk { val qualifiedName = typeAliasStatement.qualifiedName return when { qualifiedName != null -> HtmlChunk.link("${DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL}$LINK_TYPE_FUNC$qualifiedName", content) diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyTypeRenderer.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyTypeRenderer.java index 5aad66cf210e..927c7ee3b057 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/PyTypeRenderer.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/PyTypeRenderer.java @@ -40,7 +40,7 @@ public abstract class PyTypeRenderer extends PyTypeVisitorExt<@NotNull HtmlChunk protected int myDepth = 0; protected final @NotNull TypeEvalContext myTypeEvalContext; protected final EnumSet myRenderingFeatures; - + public enum Feature { /** * Render fully qualified names of all classes and type forms, e.g. {@code typing.Callable[[mod.MyClass], typing.Any]}. @@ -115,8 +115,8 @@ public abstract class PyTypeRenderer extends PyTypeVisitorExt<@NotNull HtmlChunk } public static final class TypeHint extends PyTypeRenderer { - private static final EnumSet SUPPORTED_FEATURES = EnumSet.of(Feature.USE_FQN); - + private static final EnumSet SUPPORTED_FEATURES = EnumSet.of(Feature.USE_FQN); + public TypeHint(@NotNull TypeEvalContext typeEvalContext, @NotNull EnumSet features) { super(typeEvalContext, validateFeatures(features)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/PythonDocumentationMap.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/PythonDocumentationMap.java index 904d56930714..671fe1f3504e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/PythonDocumentationMap.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/PythonDocumentationMap.java @@ -29,7 +29,8 @@ public class PythonDocumentationMap implements PersistentStateComponent R}, not as {@code Callable[[T1, T2, ...], R]}. * To render a type as a valid expression for a type annotation use {@link #getTypeHint(PyType, TypeEvalContext)}. * - * @param type the type to render - * @param context TypeEvalContext instance to infer extra types with + * @param type the type to render + * @param context TypeEvalContext instance to infer extra types with * @return string representation of the type * @see #getTypeHint(PyType, TypeEvalContext) */ diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringReferenceProvider.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringReferenceProvider.java index b68cf5f5022f..c63c54864f8c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringReferenceProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringReferenceProvider.java @@ -106,6 +106,7 @@ public class DocStringReferenceProvider extends PsiReferenceProvider { } return result; } + private static List referencesFromNames(@NotNull PyStringLiteralExpression element, int offset, @NotNull StructuredDocString docString, @@ -135,7 +136,7 @@ public class DocStringReferenceProvider extends PsiReferenceProvider { @Nullable ReferenceType nameRefType) { final List result = new ArrayList<>(); for (SectionBasedDocString.SectionField field : fields) { - for (Substring nameSub: field.getNamesAsSubstrings()) { + for (Substring nameSub : field.getNamesAsSubstrings()) { if (nameRefType != null && nameSub != null && !nameSub.isEmpty()) { final TextRange range = nameSub.getTextRange().shiftRight(offset); result.add(new DocStringParameterReference(element, range, nameRefType)); @@ -173,9 +174,9 @@ public class DocStringReferenceProvider extends PsiReferenceProvider { String foundTag = null; for (String paramTag : paramTags) { int tagPos = docString.indexOf(paramTag, pos); - while(tagPos >= 0 && tagPos + paramTag.length() < docString.length() && - Character.isLetterOrDigit(docString.charAt(tagPos + paramTag.length()))) { - tagPos = docString.indexOf(paramTag, tagPos+1); + while (tagPos >= 0 && tagPos + paramTag.length() < docString.length() && + Character.isLetterOrDigit(docString.charAt(tagPos + paramTag.length()))) { + tagPos = docString.indexOf(paramTag, tagPos + 1); } if (tagPos >= 0 && tagPos < result) { foundTag = paramTag; diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringUtil.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringUtil.java index 1c39b4501709..144091b3fbed 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/docstrings/DocStringUtil.java @@ -63,7 +63,8 @@ public final class DocStringUtil { return parseDocString(DocStringParser.guessDocStringFormat(stringLiteral.getStringValue(), stringLiteral), stringLiteral); } - public static @NotNull StructuredDocString parseDocString(@NotNull DocStringFormat format, @NotNull PyStringLiteralExpression stringLiteral) { + public static @NotNull StructuredDocString parseDocString(@NotNull DocStringFormat format, + @NotNull PyStringLiteralExpression stringLiteral) { return parseDocString(format, stringLiteral.getStringNodes().get(0)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLanguageInjector.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLanguageInjector.java index 3a2fe07d2b91..21d7443a1b8c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLanguageInjector.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLanguageInjector.java @@ -33,7 +33,8 @@ import java.util.List; public class PyDocstringLanguageInjector implements LanguageInjector { @Override - public void getLanguagesToInject(final @NotNull PsiLanguageInjectionHost host, final @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { + public void getLanguagesToInject(final @NotNull PsiLanguageInjectionHost host, + final @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { if (!(host instanceof PyStringLiteralExpression)) { return; } @@ -45,7 +46,7 @@ public class PyDocstringLanguageInjector implements LanguageInjector { int end = host.getTextLength() - 1; final String text = host.getText(); - final Pair quotes = PyStringLiteralCoreUtil.getQuotes(text); + final Pair quotes = PyStringLiteralCoreUtil.getQuotes(text); final List strings = StringUtil.split(text, "\n", false); boolean gotExample = false; @@ -57,51 +58,60 @@ public class PyDocstringLanguageInjector implements LanguageInjector { final String trimmedString = string.trim(); if (!trimmedString.startsWith(">>>") && !trimmedString.startsWith("...") && gotExample && start < end) { gotExample = false; - if (!endsWithSlash) - injectionPlacesRegistrar.addPlace(PyDocstringLanguageDialect.getInstance(), TextRange.create(start, end), null, null); + if (!endsWithSlash) { + injectionPlacesRegistrar.addPlace(PyDocstringLanguageDialect.getInstance(), TextRange.create(start, end), null, null); + } } final String closingQuote = quotes == null ? text.substring(0, 1) : quotes.second; if (endsWithSlash && !trimmedString.endsWith("\\")) { endsWithSlash = false; injectionPlacesRegistrar.addPlace(PyDocstringLanguageDialect.getInstance(), - TextRange.create(start, getEndOffset(currentPosition, string, maxPosition, closingQuote)), null, null); + TextRange.create(start, getEndOffset(currentPosition, string, maxPosition, closingQuote)), null, + null); } if (trimmedString.startsWith(">>>")) { - if (trimmedString.endsWith("\\")) + if (trimmedString.endsWith("\\")) { endsWithSlash = true; + } - if (!gotExample) + if (!gotExample) { start = currentPosition; + } gotExample = true; end = getEndOffset(currentPosition, string, maxPosition, closingQuote); } else if (trimmedString.startsWith("...") && gotExample) { - if (trimmedString.endsWith("\\")) + if (trimmedString.endsWith("\\")) { endsWithSlash = true; + } end = getEndOffset(currentPosition, string, maxPosition, closingQuote); } currentPosition += string.length(); } - if (gotExample && start < end) - injectionPlacesRegistrar.addPlace(PyDocstringLanguageDialect.getInstance(), TextRange.create(start, end), null, null); + if (gotExample && start < end) { + injectionPlacesRegistrar.addPlace(PyDocstringLanguageDialect.getInstance(), TextRange.create(start, end), null, null); + } } } private static int getEndOffset(int start, String s, int maxPosition, String closingQuote) { int end; int length = s.length(); - if (s.trim().endsWith(closingQuote)) + if (s.trim().endsWith(closingQuote)) { length -= 3; - else if (start + length == maxPosition && (s.trim().endsWith("\"") || s.trim().endsWith("'"))) + } + else if (start + length == maxPosition && (s.trim().endsWith("\"") || s.trim().endsWith("'"))) { length -= 1; + } end = start + length; - if (s.endsWith("\n")) + if (s.endsWith("\n")) { end -= 1; + } return end; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLexer.java b/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLexer.java index 2f955e707221..e9ca223c61e9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLexer.java +++ b/python/python-psi-impl/src/com/jetbrains/python/documentation/doctest/PyDocstringLexer.java @@ -38,15 +38,17 @@ public class PyDocstringLexer extends PythonIndentingLexer { @Override protected int getNextLineIndent() { int indent = super.getNextLineIndent(); - if (!ourIgnoreSet.contains(getBaseTokenType())) + if (!ourIgnoreSet.contains(getBaseTokenType())) { return indent; + } indent = 0; - while (getBaseTokenType() != null && ourIgnoreSet.contains(getBaseTokenType())) + while (getBaseTokenType() != null && ourIgnoreSet.contains(getBaseTokenType())) { advanceBase(); + } while (getBaseTokenType() != null && (PyTokenTypes.WHITESPACE_OR_LINEBREAK.contains(getBaseTokenType()) || - ourIgnoreSet.contains(getBaseTokenType()))) { + ourIgnoreSet.contains(getBaseTokenType()))) { if (getBaseTokenType() == PyTokenTypes.TAB) { indent = ((indent / 8) + 1) * 8; } @@ -64,17 +66,18 @@ public class PyDocstringLexer extends PythonIndentingLexer { if (getBaseTokenType() == null) { return 0; } - return indent > 0? indent - 1 : indent; + return indent > 0 ? indent - 1 : indent; } @Override protected void checkSignificantTokens() { IElementType tokenType = getBaseTokenType(); if (!PyTokenTypes.WHITESPACE_OR_LINEBREAK.contains(tokenType) && tokenType != getCommentTokenType() && - ! ourIgnoreSet.contains(tokenType)) { + !ourIgnoreSet.contains(tokenType)) { myLineHasSignificantTokens = true; } } + @Override protected void checkStartState(int startOffset, int initialState) { } diff --git a/python/python-psi-impl/src/com/jetbrains/python/extensions/PsiFileSystemItemExt.kt b/python/python-psi-impl/src/com/jetbrains/python/extensions/PsiFileSystemItemExt.kt index 0d3d300c8b88..d2cfd2850e31 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/extensions/PsiFileSystemItemExt.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/extensions/PsiFileSystemItemExt.kt @@ -23,7 +23,7 @@ import com.jetbrains.python.psi.PyPsiFacade * @author Ilya.Kazakevich */ -fun PsiFileSystemItem.getQName(): QualifiedName? { +fun PsiFileSystemItem.getQName(): QualifiedName? { val name = PyPsiFacade.getInstance(this.project).findShortestImportableName(this.virtualFile, this) ?: return null return QualifiedName.fromDottedString(name) } \ No newline at end of file diff --git a/python/python-psi-impl/src/com/jetbrains/python/facet/PythonPathContributingFacet.java b/python/python-psi-impl/src/com/jetbrains/python/facet/PythonPathContributingFacet.java index 093801998ee5..022fcc984b1d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/facet/PythonPathContributingFacet.java +++ b/python/python-psi-impl/src/com/jetbrains/python/facet/PythonPathContributingFacet.java @@ -21,5 +21,6 @@ import java.util.List; @Deprecated public interface PythonPathContributingFacet { List getAdditionalPythonPath(); + boolean acceptRootAsTopLevelPackage(); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyClassFindUsagesHandler.java b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyClassFindUsagesHandler.java index 31eae6b39905..8119233df357 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyClassFindUsagesHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyClassFindUsagesHandler.java @@ -32,5 +32,4 @@ public class PyClassFindUsagesHandler extends PyFindUsagesHandler { protected boolean isSearchForTextOccurrencesAvailable(@NotNull PsiElement psiElement, boolean isSingleFile) { return true; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyFindUsagesHandler.java b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyFindUsagesHandler.java index b57c96448c9e..8e4b67fffb74 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyFindUsagesHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyFindUsagesHandler.java @@ -58,7 +58,7 @@ public abstract class PyFindUsagesHandler extends FindUsagesHandlerBase { protected void completePrimaryElementsWithStubAndOriginalElements(@NotNull List result) { List additionalElements = new ArrayList<>(); - for (PsiElement element: result) { + for (PsiElement element : result) { PsiElement stubElement = tryGetStubElement(element); if (stubElement != null) { additionalElements.add(stubElement); diff --git a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyModuleFindUsagesHandler.java b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyModuleFindUsagesHandler.java index 6a17a0a98992..c252a8f78339 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyModuleFindUsagesHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyModuleFindUsagesHandler.java @@ -44,13 +44,13 @@ public class PyModuleFindUsagesHandler extends PyFindUsagesHandler { @Override public PsiElement @NotNull [] getPrimaryElements() { - return new PsiElement[] {myElement}; + return new PsiElement[]{myElement}; } @Override public @NotNull Collection findReferencesToHighlight(@NotNull PsiElement target, @NotNull SearchScope searchScope) { if (target instanceof PyImportedModule) { - target = ((PyImportedModule) target).resolve(); + target = ((PyImportedModule)target).resolve(); } if (target instanceof PyFile && PyNames.INIT_DOT_PY.equals(((PyFile)target).getName())) { List result = new ArrayList<>(super.findReferencesToHighlight(target, searchScope)); diff --git a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyWordsScanner.java b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyWordsScanner.java index 61a772b6346e..d90341840868 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyWordsScanner.java +++ b/python/python-psi-impl/src/com/jetbrains/python/findUsages/PyWordsScanner.java @@ -33,9 +33,9 @@ class PyWordsScanner extends VersionedWordsScanner { DefaultWordsScanner delegate = myDelegate; if (delegate == null) { myDelegate = delegate = new DefaultWordsScanner(new PythonLexer(), - TokenSet.create(PyTokenTypes.IDENTIFIER), - TokenSet.create(PyTokenTypes.END_OF_LINE_COMMENT), - PyTokenTypes.STRING_NODES); + TokenSet.create(PyTokenTypes.IDENTIFIER), + TokenSet.create(PyTokenTypes.END_OF_LINE_COMMENT), + PyTokenTypes.STRING_NODES); } delegate.processWords(fileText, processor); } @@ -44,5 +44,4 @@ class PyWordsScanner extends VersionedWordsScanner { public int getVersion() { return super.getVersion() + 1; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentEqualDefaultInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentEqualDefaultInspection.java index 3188904d8f44..e8b0eb891bce 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentEqualDefaultInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentEqualDefaultInspection.java @@ -28,7 +28,7 @@ import java.util.Set; /** * User: catherine - * + *

* Inspection to detect situations, where argument passed to function * is equal to default parameter value * for instance, @@ -102,14 +102,15 @@ public final class PyArgumentEqualDefaultInspection extends PyInspection { } } boolean canDelete = true; - for (int i = arguments.length-1; i != -1; --i) { + for (int i = arguments.length - 1; i != -1; --i) { if (problemElements.contains(arguments[i])) { - if (canDelete) + if (canDelete) { registerProblem(arguments[i], PyPsiBundle.message("INSP.argument.equals.to.default"), new RemoveArgumentEqualDefaultQuickFix(problemElements)); - else + } + else { registerProblem(arguments[i], PyPsiBundle.message("INSP.argument.equals.to.default")); - + } } else if (!(arguments[i] instanceof PyKeywordArgument)) canDelete = false; } @@ -144,12 +145,14 @@ public final class PyArgumentEqualDefaultInspection extends PyInspection { isBothInstanceOf(key, defaultValue, PyBinaryExpression.class) || isBothInstanceOf(key, defaultValue, PyNoneLiteralExpression.class) || isBothInstanceOf(key, defaultValue, PyBoolLiteralExpression.class)) { - if (key.getText().equals(defaultValue.getText())) + if (key.getText().equals(defaultValue.getText())) { return true; + } } else if (key instanceof PyStringLiteralExpression && defaultValue instanceof PyStringLiteralExpression) { - if (((PyStringLiteralExpression)key).getStringValue().equals(((PyStringLiteralExpression)defaultValue).getStringValue())) + if (((PyStringLiteralExpression)key).getStringValue().equals(((PyStringLiteralExpression)defaultValue).getStringValue())) { return true; + } } else if (key instanceof PyReferenceExpression && PyUtil.isPy2ReservedWord((PyReferenceExpression)key) && key.getText().equals(defaultValue.getText())) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentListInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentListInspection.java index 1aae6a66b517..10db699936a5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentListInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyArgumentListInspection.java @@ -37,7 +37,9 @@ import java.util.stream.Collectors; public final class PyArgumentListInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } @@ -73,7 +75,8 @@ public final class PyArgumentListInspection extends PyInspection { final PyCallableParameter allegedFirstParam = ContainerUtil.getOrElse(params, firstParamOffset - 1, null); if (allegedFirstParam == null || allegedFirstParam.isKeywordContainer()) { // no parameters left to pass function implicitly, or wrong param type - registerProblem(deco, PyPsiBundle.message("INSP.function.lacks.positional.argument", callable.getName())); // TODO: better names for anon lambdas + registerProblem(deco, PyPsiBundle.message("INSP.function.lacks.positional.argument", + callable.getName())); // TODO: better names for anon lambdas } else { // possible unfilled params for (int i = firstParamOffset; i < params.size(); i++) { @@ -250,7 +253,8 @@ public final class PyArgumentListInspection extends PyInspection { final Project project = node.getProject(); if (callable instanceof PyFunction && !PyPsiIndexUtil.isNotUnderSourceRoot(project, callable.getContainingFile())) { final String message = PyPsiBundle.message("INSP.unexpected.arg(s)"); - holder.registerProblem(node, message, ProblemHighlightType.INFORMATION, PythonUiService.getInstance().createPyChangeSignatureQuickFixForMismatchedCall(mapping)); + holder.registerProblem(node, message, ProblemHighlightType.INFORMATION, + PythonUiService.getInstance().createPyChangeSignatureQuickFixForMismatchedCall(mapping)); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAttributeOutsideInitInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAttributeOutsideInitInspection.java index cafd1a1be118..2272609fe0b5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAttributeOutsideInitInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAttributeOutsideInitInspection.java @@ -44,7 +44,7 @@ import java.util.Set; /** * User: ktisha - * + *

* Inspection to detect situations, where instance attribute is defined outside __init__ function. */ public final class PyAttributeOutsideInitInspection extends PyInspection { @@ -77,12 +77,12 @@ public final class PyAttributeOutsideInitInspection extends PyInspection { } final Map localProperties = containingClass.getProperties(); - final MultiMap declaredAttributes = new MultiMap<>(); + final MultiMap declaredAttributes = new MultiMap<>(); final Set inheritedProperties = new HashSet<>(); StreamEx.of(containingClass.getClassAttributes()) - .filter(attribute -> !localProperties.containsKey(attribute.getName())) - .forEach(attribute -> declaredAttributes.putValue(attribute.getName(), attribute)); + .filter(attribute -> !localProperties.containsKey(attribute.getName())) + .forEach(attribute -> declaredAttributes.putValue(attribute.getName(), attribute)); final PyFunction initMethod = containingClass.findMethodByName(PyNames.INIT, false, myTypeEvalContext); if (initMethod != null) { @@ -144,8 +144,8 @@ public final class PyAttributeOutsideInitInspection extends PyInspection { @NotNull Collection properties, @NotNull MultiMap attributesInInit) { return StreamEx.of(properties) - .filter(it -> isSetBy(attribute, it)) - .anyMatch(it -> attributesInInit.containsKey(it.getName())); + .filter(it -> isSetBy(attribute, it)) + .anyMatch(it -> attributesInInit.containsKey(it.getName())); } private static boolean isApplicable(@NotNull PyClass containingClass, @NotNull TypeEvalContext context) { @@ -174,8 +174,8 @@ public final class PyAttributeOutsideInitInspection extends PyInspection { return propertyTargetExpressions != null && attribute.getName() != null && StreamEx.of(propertyTargetExpressions) - .map(targetExpression -> targetExpression.getName()) - .nonNull() - .anyMatch(name -> name.equals(attribute.getName())); + .map(targetExpression -> targetExpression.getName()) + .nonNull() + .anyMatch(name -> name.equals(attribute.getName())); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java index a5c8216269ad..1736cf0f9ee2 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyAugmentAssignmentInspection.java @@ -41,14 +41,16 @@ import java.util.Set; /** * User: catherine - * + *

* Inspection to detect assignments that can be replaced with augmented assignments. */ public final class PyAugmentAssignmentInspection extends PyInspection { private static final @NotNull TokenSet OPERATIONS = TokenSet.create(PyTokenTypes.PLUS, PyTokenTypes.MINUS, PyTokenTypes.MULT, - PyTokenTypes.FLOORDIV, PyTokenTypes.DIV, PyTokenTypes.PERC, PyTokenTypes.AND, - PyTokenTypes.OR, PyTokenTypes.XOR, PyTokenTypes.LTLT, PyTokenTypes.GTGT, + PyTokenTypes.FLOORDIV, PyTokenTypes.DIV, PyTokenTypes.PERC, + PyTokenTypes.AND, + PyTokenTypes.OR, PyTokenTypes.XOR, PyTokenTypes.LTLT, + PyTokenTypes.GTGT, PyTokenTypes.EXP); private static final @NotNull TokenSet COMMUTATIVE_OPERATIONS = TokenSet.create(PyTokenTypes.PLUS, PyTokenTypes.MULT, PyTokenTypes.OR, PyTokenTypes.AND); @@ -103,7 +105,8 @@ public final class PyAugmentAssignmentInspection extends PyInspection { final PyElementType operator = value.getOperator(); if (operator != null && assignmentCanBeReplaced(mainOperandExpression, otherOperandExpression, operator, changedParts)) { - registerProblem(node, PyPsiBundle.message("INSP.assignment.can.be.replaced.with.augmented.assignment"), new AugmentedAssignmentQuickFix()); + registerProblem(node, PyPsiBundle.message("INSP.assignment.can.be.replaced.with.augmented.assignment"), + new AugmentedAssignmentQuickFix()); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBaseDocstringInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBaseDocstringInspection.java index c18eefad9fd0..e93d35cd656d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBaseDocstringInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBaseDocstringInspection.java @@ -28,7 +28,9 @@ import org.jetbrains.annotations.Nullable; */ public abstract class PyBaseDocstringInspection extends PyInspection { @Override - public abstract @NotNull Visitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session); + public abstract @NotNull Visitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session); protected abstract static class Visitor extends PyInspectionVisitor { public Visitor(@Nullable ProblemsHolder holder, diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBroadExceptionInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBroadExceptionInspection.java index 55c519afbcef..1fed76bcbe96 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBroadExceptionInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyBroadExceptionInspection.java @@ -53,10 +53,11 @@ public final class PyBroadExceptionInspection extends PyInspection { } @Override - public void visitPyExceptBlock(final @NotNull PyExceptPart node){ + public void visitPyExceptBlock(final @NotNull PyExceptPart node) { PyExpression exceptClass = node.getExceptClass(); - if (reRaised(node)) + if (reRaised(node)) { return; + } if (exceptClass == null) { registerProblem(node.getFirstChild(), PyPsiBundle.message("INSP.too.broad.exception.clause")); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyByteLiteralInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyByteLiteralInspection.java index b716a179101b..f8f5792ceb57 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyByteLiteralInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyByteLiteralInspection.java @@ -63,9 +63,12 @@ public final class PyByteLiteralInspection extends PyInspection { final String charsetString = PythonFileType.getCharsetFromEncodingDeclaration(file); try { - if (charsetString != null && !Charset.forName(charsetString).equals(StandardCharsets.US_ASCII)) + if (charsetString != null && !Charset.forName(charsetString).equals(StandardCharsets.US_ASCII)) { default_bytes = false; - } catch (UnsupportedCharsetException | IllegalCharsetNameException ignored) {} + } + } + catch (UnsupportedCharsetException | IllegalCharsetNameException ignored) { + } boolean hasNonAscii = false; @@ -73,7 +76,7 @@ public final class PyByteLiteralInspection extends PyInspection { char c; for (int i = 0; i < length; ++i) { c = value.charAt(i); - if (((int) c) > 255) { + if (((int)c) > 255) { hasNonAscii = true; break; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java index 12c8bfaf5499..05f809652f98 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyChainedComparisonsInspection.java @@ -38,7 +38,7 @@ import static com.jetbrains.python.psi.PyUtil.as; /** * User: catherine - * + *

* Inspection to detect chained comparisons which can be simplified * For instance, a < b and b < c --> a < b < c */ @@ -119,7 +119,8 @@ public final class PyChainedComparisonsInspection extends PyInspection { } } else { - registerProblem(node, PyPsiBundle.message("INSP.simplify.chained.comparison"), new ChainedComparisonsQuickFix(myIsLeft, myIsRight, getInnerRight)); + registerProblem(node, PyPsiBundle.message("INSP.simplify.chained.comparison"), + new ChainedComparisonsQuickFix(myIsLeft, myIsRight, getInnerRight)); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassVarInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassVarInspection.kt index 206966fcc7f1..8505524e092b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassVarInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassVarInspection.kt @@ -15,17 +15,19 @@ import com.jetbrains.python.psi.types.* class PyClassVarInspection : PyInspection() { - override fun buildVisitor(holder: ProblemsHolder, - isOnTheFly: Boolean, - session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, - PyInspectionVisitor.getContext(session)) + override fun buildVisitor( + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession, + ): PsiElementVisitor = Visitor(holder, + PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPyTargetExpression(node: PyTargetExpression) { - checkClassVarReassignment(node) - checkClassVarDeclaration(node) - checkAssignedValue(node) + checkClassVarReassignment(node) + checkClassVarDeclaration(node) + checkAssignedValue(node) } override fun visitPyReferenceExpression(node: PyReferenceExpression) { @@ -100,7 +102,8 @@ class PyClassVarInspection : PyInspection() { val expectedType = myTypeEvalContext.getType(node) val actualType = node.findAssignedValue()?.let { myTypeEvalContext.getType(it) } if (expectedType != null && actualType != null && - !PyTypeChecker.match(expectedType, actualType, myTypeEvalContext)) { + !PyTypeChecker.match(expectedType, actualType, myTypeEvalContext) + ) { val expectedName = PythonDocumentationProvider.getTypeName(expectedType, myTypeEvalContext) val actualName = PythonDocumentationProvider.getTypeName(actualType, myTypeEvalContext) registerProblem(node.findAssignedValue(), diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassicStyleClassInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassicStyleClassInspection.java index 7a06909ff231..1681ae4d725b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassicStyleClassInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyClassicStyleClassInspection.java @@ -48,8 +48,10 @@ public final class PyClassicStyleClassInspection extends PyInspection { if (!node.isNewStyleClass(myTypeEvalContext) && nameNode != null) { PyExpression[] superClassExpressions = node.getSuperClassExpressions(); if (superClassExpressions.length == 0) { - registerProblem(nameNode.getPsi(), PyPsiBundle.message("INSP.classic.class.usage.old.style.class"), new TransformClassicClassQuickFix()); - } else { + registerProblem(nameNode.getPsi(), PyPsiBundle.message("INSP.classic.class.usage.old.style.class"), + new TransformClassicClassQuickFix()); + } + else { registerProblem(nameNode.getPsi(), PyPsiBundle.message("INSP.classic.class.usage.old.style.class.ancestors")); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyComparisonWithNoneInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyComparisonWithNoneInspection.java index 8fdc7f780349..e9cd3c5e605f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyComparisonWithNoneInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyComparisonWithNoneInspection.java @@ -56,7 +56,8 @@ public final class PyComparisonWithNoneInspection extends PyInspection { assert reference != null; PsiElement result = reference.resolve(); if (result == null || PyBuiltinCache.getInstance(node).isBuiltin(result)) { - registerProblem(node, PyPsiBundle.message("INSP.comparison.with.none.performed.with.equality.operators"), new ComparisonWithNoneQuickFix()); + registerProblem(node, PyPsiBundle.message("INSP.comparison.with.none.performed.with.equality.operators"), + new ComparisonWithNoneQuickFix()); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyCompatibilityInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyCompatibilityInspection.java index f14948492cc8..c2c9aa985881 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyCompatibilityInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyCompatibilityInspection.java @@ -59,7 +59,7 @@ import static com.intellij.codeInspection.options.OptPane.*; /** * User: catherine - * + *

* Inspection to detect code incompatibility with python versions */ public final class PyCompatibilityInspection extends PyInspection { @@ -74,7 +74,8 @@ public final class PyCompatibilityInspection extends PyInspection { public static final int LATEST_INSPECTION_VERSION = 3; - public static final @NotNull List DEFAULT_PYTHON_VERSIONS = ImmutableList.of(LanguageLevel.PYTHON27, LanguageLevel.getLatest()); + public static final @NotNull List DEFAULT_PYTHON_VERSIONS = + ImmutableList.of(LanguageLevel.PYTHON27, LanguageLevel.getLatest()); public static final @NotNull List SUPPORTED_LEVELS = StreamEx .of(LanguageLevel.values()) @@ -86,7 +87,7 @@ public final class PyCompatibilityInspection extends PyInspection { // Legacy DefaultJDOMExternalizer requires public fields for proper serialization public JDOMExternalizableStringList ourVersions = new JDOMExternalizableStringList(); - public PyCompatibilityInspection () { + public PyCompatibilityInspection() { if (ApplicationManager.getApplication().isUnitTestMode()) { ourVersions.addAll(SUPPORTED_IN_SETTINGS); } @@ -94,7 +95,7 @@ public final class PyCompatibilityInspection extends PyInspection { ourVersions.addAll(ContainerUtil.map(DEFAULT_PYTHON_VERSIONS, LanguageLevel::toString)); } } - + public static @Nullable PyCompatibilityInspection getInstance(@NotNull PsiElement element) { final InspectionProfile inspectionProfile = InspectionProjectProfileManager.getInstance(element.getProject()).getCurrentProfile(); final String toolName = PyCompatibilityInspection.class.getSimpleName(); @@ -242,9 +243,10 @@ public final class PyCompatibilityInspection extends PyInspection { } final String moduleName = qName.toString(); - registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName), - PyPsiBundle.message("INSP.compatibility.feature.have.module", moduleName), - importElement); + registerForAllMatchingVersions( + level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName), + PyPsiBundle.message("INSP.compatibility.feature.have.module", moduleName), + importElement); } } @@ -271,9 +273,10 @@ public final class PyCompatibilityInspection extends PyInspection { if (name != null && source != null) { final String moduleName = name.toString(); - registerForAllMatchingVersions(level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName), - PyPsiBundle.message("INSP.compatibility.feature.have.module", name), - source); + registerForAllMatchingVersions( + level -> UnsupportedFeaturesUtil.MODULES.get(level).contains(moduleName) && !BACKPORTED_PACKAGES.contains(moduleName), + PyPsiBundle.message("INSP.compatibility.feature.have.module", name), + source); } } @@ -408,7 +411,7 @@ public final class PyCompatibilityInspection extends PyInspection { private boolean importedFromCompatibilityLibs(@NotNull PyExpression callee) { if (callee instanceof PyQualifiedExpression) { - QualifiedName qualifiedName = ((PyQualifiedExpression) callee).asQualifiedName(); + QualifiedName qualifiedName = ((PyQualifiedExpression)callee).asQualifiedName(); return qualifiedName != null && myFromCompatibilityLibs.contains(qualifiedName.getFirstComponent()); } return myFromCompatibilityLibs.contains(callee.getName()); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt index 2f33880a05f4..fb1a87b62e80 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDataclassInspection.kt @@ -33,10 +33,12 @@ class PyDataclassInspection : PyInspection() { } } - override fun buildVisitor(holder: ProblemsHolder, - isOnTheFly: Boolean, - session: LocalInspectionToolSession): PsiElementVisitor = Visitor( - holder,PyInspectionVisitor.getContext(session)) + override fun buildVisitor( + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession, + ): PsiElementVisitor = Visitor( + holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { @@ -359,7 +361,8 @@ class PyDataclassInspection : PyInspection() { "__repr__" -> reprMethod = it "__str__" -> strMethod = it "__eq__", - in ORDER_OPERATORS -> cmpMethods.add(it) + in ORDER_OPERATORS, + -> cmpMethods.add(it) "__setattr__", "__delattr__" -> mutatingMethods.add(it) PyNames.HASH -> hashMethod = it } @@ -474,9 +477,11 @@ class PyDataclassInspection : PyInspection() { sameAttrInitializers .asSequence() .drop(1) - .forEach { registerProblem(it.nameIdentifier, - PyPsiBundle.message("INSP.dataclasses.attribute.default.set.using.method", first.name), - ProblemHighlightType.GENERIC_ERROR) } + .forEach { + registerProblem(it.nameIdentifier, + PyPsiBundle.message("INSP.dataclasses.attribute.default.set.using.method", first.name), + ProblemHighlightType.GENERIC_ERROR) + } } } @@ -596,10 +601,12 @@ class PyDataclassInspection : PyInspection() { } } - private fun processPostInitDefinition(cls: PyClass, - postInit: PyFunction, - dataclassParameters: PyDataclassParameters, - localInitVars: List) { + private fun processPostInitDefinition( + cls: PyClass, + postInit: PyFunction, + dataclassParameters: PyDataclassParameters, + localInitVars: List, + ) { if (!dataclassParameters.init) { registerProblem(postInit.nameIdentifier, PyPsiBundle.message("INSP.dataclasses.post.init.would.not.be.called.until.init.parameter.set.to.true"), diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDecoratorInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDecoratorInspection.java index 5b8b30e9c482..18f2b9d2bf66 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDecoratorInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDecoratorInspection.java @@ -30,7 +30,7 @@ import org.jetbrains.annotations.Nullable; /** * User: catherine - * + *

* Inspection to detect occurrences of @classmethod and @staticmethod * on methods outside of a class */ @@ -50,19 +50,22 @@ public final class PyDecoratorInspection extends PyInspection { } @Override - public void visitPyFunction(final @NotNull PyFunction node){ + public void visitPyFunction(final @NotNull PyFunction node) { PyClass containingClass = node.getContainingClass(); - if (containingClass != null) + if (containingClass != null) { return; + } PyDecoratorList decorators = node.getDecoratorList(); - if (decorators == null) + if (decorators == null) { return; + } for (PyDecorator decorator : decorators.getDecorators()) { String name = decorator.getText(); - if (name.equals("@classmethod") || name.equals("@staticmethod")) + if (name.equals("@classmethod") || name.equals("@staticmethod")) { registerProblem(decorator, PyPsiBundle.message("INSP.decorators.method.only.decorator.on.method.outside.class", name), new RemoveDecoratorQuickFix()); + } } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictCreationInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictCreationInspection.java index 5963d2e5db1b..bf4bca6efbf0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictCreationInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictCreationInspection.java @@ -45,6 +45,7 @@ public final class PyDictCreationInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyAssignmentStatement(@NotNull PyAssignmentStatement node) { if (node.getAssignedValue() instanceof PyDictLiteralExpression) { @@ -61,8 +62,9 @@ public final class PyDictCreationInspection extends PyInspection { while (statement instanceof PyAssignmentStatement assignmentStatement) { final List> targets = getDictTargets(target, name, assignmentStatement); - if (targets == null) + if (targets == null) { return; + } if (!targets.isEmpty()) { registerProblem(node, PyPsiBundle.message("INSP.dict.creation.this.dictionary.creation.could.be.rewritten.as.dictionary.literal"), @@ -87,8 +89,9 @@ public final class PyDictCreationInspection extends PyInspection { targets.add(targetToValue); } } - else + else { return null; + } } return targets; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictDuplicateKeysInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictDuplicateKeysInspection.java index adf45f2bebee..ad8026be8a93 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictDuplicateKeysInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDictDuplicateKeysInspection.java @@ -40,7 +40,7 @@ import java.util.Map; /** * User: catherine - * + *

* Inspection to detect using the same value as dictionary key twice. */ public final class PyDictDuplicateKeysInspection extends PyInspection { @@ -57,6 +57,7 @@ public final class PyDictDuplicateKeysInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyDictLiteralExpression(@NotNull PyDictLiteralExpression node) { if (node.isEmpty()) return; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt index ba9d486af492..ea41b4b3df35 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyDunderSlotsInspection.kt @@ -26,7 +26,7 @@ class PyDunderSlotsInspection : PyInspection() { isOnTheFly: Boolean, session: LocalInspectionToolSession, ): PsiElementVisitor = Visitor( - holder,PyInspectionVisitor.getContext(session)) + holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyEncodingUtil.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyEncodingUtil.java index 23efd1861a46..be3aadac0379 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyEncodingUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyEncodingUtil.java @@ -25,15 +25,24 @@ public final class PyEncodingUtil { private PyEncodingUtil() { } - public static final @NlsSafe String[] POSSIBLE_ENCODINGS = new String[]{"ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", - "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", "cp874", - "cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", "cp1256", "cp1257", - "cp1258", "euc-jp", "euc-jis-2004", "euc-kr", "gb2312", "gbk", "gb18030", "hz", "iso2022-jp", "iso2022-jp-1", "iso2022-jp-2", "iso2022-jp-2004", - "iso2022-jp-3", "iso2022-jp-ext", "iso2022-kr", "latin-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5", "iso8859-6", "iso8859-7", - "iso8859-8", "iso8859-9", "iso8859-10", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16", "johab", "koi8-r", "koi8-u", "mac-cyrillic", - "mac-greek", "mac-iceland", "mac-latin2", "mac-roman", "mac-turkish", "ptcp154", "shift-jis", "shift-jis-2004", "shift-jisx0213", "utf-32", - "utf-32-be", "utf-32-le", "utf-16", "utf-16-be", "utf-16-le", "utf-7", "utf-8", "utf-8-sig"}; + public static final @NlsSafe String[] POSSIBLE_ENCODINGS = + new String[]{"ascii", "big5", "big5hkscs", "cp037", "cp424", "cp437", "cp500", "cp720", "cp737", + "cp775", "cp850", "cp852", "cp855", "cp856", "cp857", "cp858", "cp860", "cp861", "cp862", "cp863", "cp864", "cp865", "cp866", "cp869", + "cp874", + "cp875", "cp932", "cp949", "cp950", "cp1006", "cp1026", "cp1140", "cp1250", "cp1251", "cp1252", "cp1253", "cp1254", "cp1255", + "cp1256", "cp1257", + "cp1258", "euc-jp", "euc-jis-2004", "euc-kr", "gb2312", "gbk", "gb18030", "hz", "iso2022-jp", "iso2022-jp-1", "iso2022-jp-2", + "iso2022-jp-2004", + "iso2022-jp-3", "iso2022-jp-ext", "iso2022-kr", "latin-1", "iso8859-2", "iso8859-3", "iso8859-4", "iso8859-5", "iso8859-6", + "iso8859-7", + "iso8859-8", "iso8859-9", "iso8859-10", "iso8859-13", "iso8859-14", "iso8859-15", "iso8859-16", "johab", "koi8-r", "koi8-u", + "mac-cyrillic", + "mac-greek", "mac-iceland", "mac-latin2", "mac-roman", "mac-turkish", "ptcp154", "shift-jis", "shift-jis-2004", "shift-jisx0213", + "utf-32", + "utf-32-be", "utf-32-le", "utf-16", "utf-16-be", "utf-16-le", "utf-7", "utf-8", "utf-8-sig"}; - public static final @NlsSafe String[] ENCODING_FORMAT = new String[]{"# coding=", "# -*- coding: -*-", "# vim: set fileencoding= :"}; - public static final @NlsSafe String[] ENCODING_FORMAT_PATTERN = new String[]{"# coding=%s", "# -*- coding: %s -*-", "# vim: set fileencoding=%s :"}; + public static final @NlsSafe String[] ENCODING_FORMAT = + new String[]{"# coding=", "# -*- coding: -*-", "# vim: set fileencoding= :"}; + public static final @NlsSafe String[] ENCODING_FORMAT_PATTERN = + new String[]{"# coding=%s", "# -*- coding: %s -*-", "# vim: set fileencoding=%s :"}; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptClausesOrderInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptClausesOrderInspection.java index ca7ac560c1df..cbfa1f487eea 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptClausesOrderInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptClausesOrderInspection.java @@ -31,7 +31,9 @@ import java.util.Set; public final class PyExceptClausesOrderInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } @@ -49,12 +51,13 @@ public final class PyExceptClausesOrderInspection extends PyInspection { for (PyExceptPart exceptPart : exceptParts) { PyExpression exceptClass = exceptPart.getExceptClass(); if (exceptClass instanceof PyReferenceExpression) { - PsiElement element = ((PyReferenceExpression) exceptClass).followAssignmentsChain(getResolveContext()).getElement(); + PsiElement element = ((PyReferenceExpression)exceptClass).followAssignmentsChain(getResolveContext()).getElement(); if (element instanceof PyClass pyClass) { if (exceptClasses.contains(pyClass)) { registerProblem(exceptClass, PyPsiBundle.message("INSP.bad.except.exception.class.already.caught", pyClass.getName())); - } else { - for (PyClass superClass: pyClass.getSuperClasses(null)) { + } + else { + for (PyClass superClass : pyClass.getSuperClasses(null)) { if (exceptClasses.contains(superClass)) { registerProblem(exceptClass, PyPsiBundle .message("INSP.bad.except.superclass.of.exception.class.already.caught", superClass.getName(), pyClass.getName()), diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptionInheritInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptionInheritInspection.java index 7ecab9828916..347882753be6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptionInheritInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyExceptionInheritInspection.java @@ -44,6 +44,7 @@ public final class PyExceptionInheritInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyRaiseStatement(@NotNull PyRaiseStatement node) { PyExpression[] expressions = node.getExpressions(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt index 73a886fd9634..5d84cef38a9f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFinalInspection.kt @@ -29,9 +29,11 @@ import com.jetbrains.python.refactoring.PyDefUseUtil class PyFinalInspection : PyInspection() { - override fun buildVisitor(holder: ProblemsHolder, - isOnTheFly: Boolean, - session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session)) + override fun buildVisitor( + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession, + ): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { @@ -222,8 +224,10 @@ class PyFinalInspection : PyInspection() { return Pair(classFinals, instanceFinals) } - private fun checkClassLevelFinalsAreInitialized(classLevelFinals: Map, - initAttributes: Map) { + private fun checkClassLevelFinalsAreInitialized( + classLevelFinals: Map, + initAttributes: Map, + ) { classLevelFinals.forEach { (name, psi) -> if (!psi.hasAssignedValue() && name !in initAttributes) { registerProblem(psi, PyPsiBundle.message("INSP.final.final.name.should.be.initialized.with.value")) @@ -231,8 +235,10 @@ class PyFinalInspection : PyInspection() { } } - private fun checkSameNameClassAndInstanceFinals(classLevelFinals: Map, - initAttributes: Map) { + private fun checkSameNameClassAndInstanceFinals( + classLevelFinals: Map, + initAttributes: Map, + ) { initAttributes.forEach { (name, initAttribute) -> val sameNameClassLevelFinal = classLevelFinals[name] @@ -266,10 +272,12 @@ class PyFinalInspection : PyInspection() { } } - private fun checkOverridingInheritedFinalWithNewOne(newFinals: Map, - inheritedFinals: Map, - ancestorName: String?, - notRegistered: MutableSet) { + private fun checkOverridingInheritedFinalWithNewOne( + newFinals: Map, + inheritedFinals: Map, + ancestorName: String?, + notRegistered: MutableSet, + ) { if (notRegistered.isEmpty()) return for (commonFinal in newFinals.keys.intersect(inheritedFinals.keys)) { @@ -324,7 +332,7 @@ class PyFinalInspection : PyInspection() { return } if (e.parent.let { it is PyNonlocalStatement || it is PyGlobalStatement } && - PyUtil.multiResolveTopPriority(e, resolveContext).any { it is PyTargetExpression && isFinal(it) }) { + PyUtil.multiResolveTopPriority(e, resolveContext).any { it is PyTargetExpression && isFinal(it) }) { registerProblem(target, PyPsiBundle.message("INSP.final.final.target.could.not.be.reassigned", target.name)) return } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFromFutureImportInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFromFutureImportInspection.java index cac5c43b998d..4e91749b44b0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFromFutureImportInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyFromFutureImportInspection.java @@ -42,6 +42,7 @@ public final class PyFromFutureImportInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyFromImportStatement(@NotNull PyFromImportStatement node) { PyReferenceExpression importSource = node.getImportSource(); @@ -52,7 +53,7 @@ public final class PyFromFutureImportInspection extends PyInspection { boolean skippedDocString = false; for (PyStatement statement : statementList) { if (statement instanceof PyExpressionStatement && - ((PyExpressionStatement) statement).getExpression() instanceof PyStringLiteralExpression && + ((PyExpressionStatement)statement).getExpression() instanceof PyStringLiteralExpression && !skippedDocString) { skippedDocString = true; continue; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyGlobalUndefinedInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyGlobalUndefinedInspection.java index 6909ec045297..6bf3f5a93bdd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyGlobalUndefinedInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyGlobalUndefinedInspection.java @@ -32,7 +32,7 @@ import java.util.List; /** * User: ktisha - * + *

* pylint W0601 */ public final class PyGlobalUndefinedInspection extends PyInspection { @@ -49,6 +49,7 @@ public final class PyGlobalUndefinedInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyGlobalStatement(@NotNull PyGlobalStatement node) { final PyTargetExpression[] globals = node.getGlobals(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInconsistentIndentationInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInconsistentIndentationInspection.java index 7fde0042c2d7..e725508181fc 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInconsistentIndentationInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInconsistentIndentationInspection.java @@ -67,7 +67,7 @@ public final class PyInconsistentIndentationInspection extends PyInspection { final IElementType tokenType = lexer.getTokenType(); if (tokenType == PyTokenTypes.STATEMENT_BREAK) { lexer.advance(); - while(lexer.getTokenType() != null && lexer.getTokenType() != PyTokenTypes.LINE_BREAK) { + while (lexer.getTokenType() != null && lexer.getTokenType() != PyTokenTypes.LINE_BREAK) { lexer.advance(); } if (lexer.getTokenType() == PyTokenTypes.LINE_BREAK) { @@ -82,13 +82,15 @@ public final class PyInconsistentIndentationInspection extends PyInspection { private void validateIndent(final int tokenStart, String indent) { int lastLF = indent.lastIndexOf('\n'); - String lastLineIndent = indent.substring(lastLF+1); + String lastLineIndent = indent.substring(lastLF + 1); int spaces = 0; int tabs = 0; final int length = lastLineIndent.length(); for (int i = 0; i < length; i++) { final char c = lastLineIndent.charAt(i); - if (c == ' ') spaces++; + if (c == ' ') { + spaces++; + } else if (c == '\t') tabs++; } final int problemStart = tokenStart + lastLF + 1; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyIncorrectDocstringInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyIncorrectDocstringInspection.java index e555f4e26f08..1837722dcf22 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyIncorrectDocstringInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyIncorrectDocstringInspection.java @@ -84,13 +84,14 @@ public final class PyIncorrectDocstringInspection extends PyBaseDocstringInspect }; } - private static @NotNull List getMissingParams(@NotNull StructuredDocString docString, PyParameter @NotNull [] realParams) { + private static @NotNull List getMissingParams(@NotNull StructuredDocString docString, + PyParameter @NotNull [] realParams) { final List missing = new ArrayList<>(); final List docStringParameters = docString.getParameters(); if (docStringParameters.isEmpty()) { return Collections.emptyList(); } - + for (PyParameter p : realParams) { final PyNamedParameter named = as(p, PyNamedParameter.class); if (p.isSelf() || named == null || named.isPositionalContainer() || named.isKeywordContainer()) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionVisitor.java index 6f2a159bf126..bcefd29cb986 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionVisitor.java @@ -106,7 +106,8 @@ public abstract class PyInspectionVisitor extends PyElementVisitor { return; } if (myHolder != null) { - myHolder.registerProblem(myHolder.getManager().createProblemDescriptor(element, message, (LocalQuickFix)null, type, myHolder.isOnTheFly())); + myHolder.registerProblem( + myHolder.getManager().createProblemDescriptor(element, message, (LocalQuickFix)null, type, myHolder.isOnTheFly())); } } @@ -120,7 +121,7 @@ public abstract class PyInspectionVisitor extends PyElementVisitor { @NotNull @InspectionMessage String descriptionTemplate, @NotNull ProblemHighlightType highlightType, @Nullable HintAction hintAction, - @NotNull LocalQuickFix @NotNull... fixes) { + @NotNull LocalQuickFix @NotNull ... fixes) { registerProblem(psiElement, descriptionTemplate, highlightType, hintAction, null, fixes); } @@ -135,7 +136,7 @@ public abstract class PyInspectionVisitor extends PyElementVisitor { @NotNull ProblemHighlightType highlightType, @Nullable HintAction hintAction, @Nullable TextRange rangeInElement, - @NotNull LocalQuickFix @NotNull... fixes) { + @NotNull LocalQuickFix @NotNull ... fixes) { if (myHolder != null && !(psiElement instanceof PsiErrorElement)) { myHolder.registerProblem(new ProblemDescriptorImpl(psiElement, psiElement, descriptionTemplate, fixes, highlightType, false, rangeInElement, hintAction, myHolder.isOnTheFly())); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionsSuppressor.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionsSuppressor.java index 33e0461afdf7..a0661e8aa751 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionsSuppressor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInspectionsSuppressor.java @@ -21,7 +21,7 @@ public final class PyInspectionsSuppressor implements InspectionSuppressor { private static final Pattern SUPPRESS_PATTERN = Pattern.compile(SuppressionUtil.COMMON_SUPPRESS_REGEXP); private static final String PY_INCORRECT_DOCSTRING_INSPECTION_ID = new PyIncorrectDocstringInspection().getID(); private static final String PY_MISSING_OR_EMPTY_DOCSTRING_INSPECTION_ID = new PyMissingOrEmptyDocstringInspection().getID(); - + @Override public SuppressQuickFix @NotNull [] getSuppressActions(@Nullable PsiElement element, @NotNull String toolId) { if (PY_INCORRECT_DOCSTRING_INSPECTION_ID.equals(toolId) || PY_MISSING_OR_EMPTY_DOCSTRING_INSPECTION_ID.equals(toolId)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInvalidCastInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInvalidCastInspection.kt index d3e142300302..c8d65f5577bd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInvalidCastInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyInvalidCastInspection.kt @@ -19,8 +19,10 @@ class PyInvalidCastInspection : PyInspection() { return object : PyInspectionVisitor(holder, getContext(session)) { override fun visitPyCallExpression(callExpression: PyCallExpression) { val callees = callExpression.multiResolveCalleeFunction(resolveContext) - val isCastCall = callees.any { (it as? PyFunction)?.qualifiedName == PyTypingTypeProvider.CAST || - (it as? PyFunction)?.qualifiedName == PyTypingTypeProvider.CAST_EXT } + val isCastCall = callees.any { + (it as? PyFunction)?.qualifiedName == PyTypingTypeProvider.CAST || + (it as? PyFunction)?.qualifiedName == PyTypingTypeProvider.CAST_EXT + } if (!isCastCall) return val args = callExpression.getArguments() diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMandatoryEncodingInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMandatoryEncodingInspection.java index 42b6634c0757..9989cf7cd07c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMandatoryEncodingInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMandatoryEncodingInspection.java @@ -52,6 +52,7 @@ public final class PyMandatoryEncodingInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyFile(@NotNull PyFile node) { if (!(myAllPythons || LanguageLevel.forElement(node).isPython2())) return; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodFirstArgAssignmentInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodFirstArgAssignmentInspection.java index 9941a638b015..cf55572e53bd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodFirstArgAssignmentInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodFirstArgAssignmentInspection.java @@ -47,7 +47,7 @@ public final class PyMethodFirstArgAssignmentInspection extends PyInspection { // are we a method? List place = PyUtil.searchForWrappingMethod(node, true); if (place == null || place.size() < 2) return null; - PyFunction method = (PyFunction)place.get(place.size()-2); + PyFunction method = (PyFunction)place.get(place.size() - 2); //PyClass owner = (PyClass)place.get(place.size()-1); // what is our first param? PyParameter[] params = method.getParameterList().getParameters(); @@ -83,7 +83,9 @@ public final class PyMethodFirstArgAssignmentInspection extends PyInspection { final String first_param_name = extractFirstParamName(node); if (first_param_name != null) { PyExpression target = node.getTarget(); - if (target instanceof PyQualifiedExpression) handleTarget((PyQualifiedExpression)target, first_param_name); + if (target instanceof PyQualifiedExpression) { + handleTarget((PyQualifiedExpression)target, first_param_name); + } else if (target instanceof PyTupleExpression) { for (PyExpression elt : PyUtil.flattenedParensAndTuples(((PyTupleExpression)target).getElements())) { if (elt instanceof PyQualifiedExpression) handleTarget((PyQualifiedExpression)elt, first_param_name); @@ -107,7 +109,8 @@ public final class PyMethodFirstArgAssignmentInspection extends PyInspection { private void markDefinition(PyElement definer) { final String first_param_name = extractFirstParamName(definer); if (first_param_name != null && first_param_name.equals(definer.getName())) { - complain(definer.getNode().findChildByType(PyTokenTypes.IDENTIFIER).getPsi(), first_param_name); // no NPE here, or we won't have the name + complain(definer.getNode().findChildByType(PyTokenTypes.IDENTIFIER).getPsi(), + first_param_name); // no NPE here, or we won't have the name } } @@ -120,7 +123,5 @@ public final class PyMethodFirstArgAssignmentInspection extends PyInspection { public void visitPyClass(@NotNull PyClass definer) { markDefinition(definer); } - - } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java index 72d4f735b288..b2fabdaa7385 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java @@ -52,6 +52,7 @@ public final class PyMethodMayBeStaticInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyFunction(@NotNull PyFunction node) { if (isBuiltin(node)) return; @@ -93,8 +94,9 @@ public final class PyMethodMayBeStaticInspection extends PyInspection { final PyExpression expression = expressions[0]; if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); - if (callee != null && PyNames.NOT_IMPLEMENTED_ERROR.equals(callee.getText())) + if (callee != null && PyNames.NOT_IMPLEMENTED_ERROR.equals(callee.getText())) { mayBeStatic[0] = false; + } } else if (PyNames.NOT_IMPLEMENTED_ERROR.equals(expression.getText())) { mayBeStatic[0] = false; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodOverridingInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodOverridingInspection.java index 63e0ca54974c..f46a25bbb15a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodOverridingInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMethodOverridingInspection.java @@ -47,9 +47,10 @@ public final class PyMethodOverridingInspection extends PyInspection { if (!PyUtil.isSignatureCompatibleTo(function, baseMethod, myTypeEvalContext)) { final PyClass baseClass = baseMethod.getContainingClass(); final String msg = PyPsiBundle.message("INSP.signature.mismatch", - cls.getName() + "." + function.getName() + "()", - baseClass != null ? baseClass.getName() : ""); - registerProblem(function.getParameterList(), msg, PythonUiService.getInstance().createPyChangeSignatureQuickFixForMismatchingMethods(function, baseMethod)); + cls.getName() + "." + function.getName() + "()", + baseClass != null ? baseClass.getName() : ""); + registerProblem(function.getParameterList(), msg, + PythonUiService.getInstance().createPyChangeSignatureQuickFixForMismatchingMethods(function, baseMethod)); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingConstructorInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingConstructorInspection.java index 6af4f9f34039..d56ee8dd5ddd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingConstructorInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingConstructorInspection.java @@ -34,13 +34,15 @@ import static com.jetbrains.python.PyNames.*; /** * User: catherine - * + *

* Inspection to warn if call to super constructor in class is missed */ public final class PyMissingConstructorInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } @@ -49,6 +51,7 @@ public final class PyMissingConstructorInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyClass(@NotNull PyClass node) { final PsiElement[] superClasses = node.getSuperClassExpressions(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java index 43f104343827..7b1e08450e32 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyMissingTypeHintsInspection.java @@ -32,7 +32,9 @@ public final class PyMissingTypeHintsInspection extends PyInspection { public boolean m_onlyWhenTypesAreKnown = true; @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new PyInspectionVisitor(holder, PyInspectionVisitor.getContext(session)) { @Override public void visitPyFunction(@NotNull PyFunction function) { @@ -59,7 +61,8 @@ public final class PyMissingTypeHintsInspection extends PyInspection { if (instance != null) { PySignature signature = instance.findSignature(function); return signature != null && canAnnotate(signature); - } else { + } + else { return false; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt index 362b65fdbbbc..7030d1c9d71c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNamedTupleInspection.kt @@ -23,13 +23,15 @@ import com.jetbrains.python.psi.types.TypeEvalContext class PyNamedTupleInspection : PyInspection() { companion object { - fun inspectFieldsOrder(cls: PyClass, - classFieldsFilter: (PyClass) -> Boolean, - checkInheritedOrder: Boolean, - context: TypeEvalContext, - callback: (PsiElement, @InspectionMessage String, ProblemHighlightType) -> Unit, - fieldsFilter: (PyTargetExpression) -> Boolean = { true }, - hasAssignedValue: (PyTargetExpression) -> Boolean = PyTargetExpression::hasAssignedValue) { + fun inspectFieldsOrder( + cls: PyClass, + classFieldsFilter: (PyClass) -> Boolean, + checkInheritedOrder: Boolean, + context: TypeEvalContext, + callback: (PsiElement, @InspectionMessage String, ProblemHighlightType) -> Unit, + fieldsFilter: (PyTargetExpression) -> Boolean = { true }, + hasAssignedValue: (PyTargetExpression) -> Boolean = PyTargetExpression::hasAssignedValue, + ) { val fieldsProcessor = if (classFieldsFilter(cls)) processFields(cls, fieldsFilter, hasAssignedValue, context) else null if ((fieldsProcessor == null || fieldsProcessor.fieldsWithoutDefaultValue.isEmpty()) && !checkInheritedOrder) return @@ -60,7 +62,8 @@ class PyNamedTupleInspection : PyInspection() { seenAncestorHavingFieldWithDefaultValue = ancestor } else if (ancestorKind == Ancestor.HAS_FIELD_WITHOUT_DEFAULT_VALUE && seenAncestorHavingFieldWithDefaultValue != null) { - val msg = PyPsiBundle.message("INSP.named.tuple.default.value.order.inherited", ancestor.name, seenAncestorHavingFieldWithDefaultValue.name) + val msg = PyPsiBundle.message("INSP.named.tuple.default.value.order.inherited", ancestor.name, + seenAncestorHavingFieldWithDefaultValue.name) callback(cls.superClassExpressionList!!, msg, ProblemHighlightType.GENERIC_ERROR) break } @@ -90,10 +93,12 @@ class PyNamedTupleInspection : PyInspection() { } } - private fun processFields(cls: PyClass, - filter: (PyTargetExpression) -> Boolean, - hasAssignedValue: (PyTargetExpression) -> Boolean, - context: TypeEvalContext): LocalFieldsProcessor { + private fun processFields( + cls: PyClass, + filter: (PyTargetExpression) -> Boolean, + hasAssignedValue: (PyTargetExpression) -> Boolean, + context: TypeEvalContext, + ): LocalFieldsProcessor { val isDataclass = parseDataclassParameters(cls, context) != null val fieldsProcessor = LocalFieldsProcessor(filter, hasAssignedValue, isDataclass, context) cls.processClassLevelDeclarations(fieldsProcessor) @@ -114,7 +119,8 @@ class PyNamedTupleInspection : PyInspection() { super.visitPyClass(node) if (LanguageLevel.forElement(node).isAtLeast(LanguageLevel.PYTHON36) && - PyNamedTupleTypeProvider.isTypingNamedTupleDirectInheritor(node, myTypeEvalContext)) { + PyNamedTupleTypeProvider.isTypingNamedTupleDirectInheritor(node, myTypeEvalContext) + ) { inspectFieldsOrder(node, { it == node }, false, myTypeEvalContext, this::registerProblem) @@ -122,10 +128,12 @@ class PyNamedTupleInspection : PyInspection() { } } - private class LocalFieldsProcessor(private val filter: (PyTargetExpression) -> Boolean, - private val hasAssignedValue: (PyTargetExpression) -> Boolean, - private val isDataclass: Boolean, - private val context: TypeEvalContext) : PsiScopeProcessor { + private class LocalFieldsProcessor( + private val filter: (PyTargetExpression) -> Boolean, + private val hasAssignedValue: (PyTargetExpression) -> Boolean, + private val isDataclass: Boolean, + private val context: TypeEvalContext, + ) : PsiScopeProcessor { val fieldsWithDefaultValue = mutableListOf() val fieldsWithoutDefaultValue = mutableListOf() var kwOnlyMarkerVisited: Boolean = false @@ -134,7 +142,8 @@ class PyNamedTupleInspection : PyInspection() { if (element is PyTargetExpression && filter(element)) { if (isDataclass && isKwOnlyMarker(element, context)) { kwOnlyMarkerVisited = true - } else if (hasAssignedValue(element) || kwOnlyMarkerVisited) { + } + else if (hasAssignedValue(element) || kwOnlyMarkerVisited) { fieldsWithDefaultValue.add(element) } else { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNestedDecoratorsInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNestedDecoratorsInspection.java index 5f60cf8ea355..413addd0a10d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNestedDecoratorsInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNestedDecoratorsInspection.java @@ -33,12 +33,14 @@ public final class PyNestedDecoratorsInspection extends PyInspection { private static final Set TRANSFORMING_DECORATORS = Set.of(PyNames.CLASSMETHOD, PyNames.STATICMETHOD); private static final Set UNAFFECTED_DECORATORS = Set.of( "typing.final", "typing.no_type_check", "typing.overload", "typing.override", "typing.type_check_only", - "typing_extensions.final", "typing_extensions.no_type_check", "typing_extensions.overload", "typing_extensions.override", "typing_extensions.type_check_only", + "typing_extensions.final", "typing_extensions.no_type_check", "typing_extensions.overload", "typing_extensions.override", + "typing_extensions.type_check_only", "functools.singledispatchmethod", - "pydantic.functional_validators.field_validator", "pydantic.functional_validators.model_validator", "pydantic.class_validators.validator", + "pydantic.functional_validators.field_validator", "pydantic.functional_validators.model_validator", + "pydantic.class_validators.validator", "django.views.decorators.cache.cache_page", "tenacity.retry" - ); + ); public Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNewStyleGenericSyntaxInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNewStyleGenericSyntaxInspection.kt index b7d89a4f0b69..9d39d50531ba 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNewStyleGenericSyntaxInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNewStyleGenericSyntaxInspection.kt @@ -29,13 +29,14 @@ class PyNewStyleGenericSyntaxInspection : PyInspection() { private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPyTypeParameter(typeParameter: PyTypeParameter) { - val boundExpression = typeParameter.boundExpression + val boundExpression = typeParameter.boundExpression val defaultExpression = typeParameter.defaultExpression boundExpression?.accept(object : PyRecursiveElementVisitor() { override fun visitPyElement(node: PyElement) { if (!(node is PyParenthesizedExpression && node === boundExpression) && - !(node is PyTupleExpression && node.parent === boundExpression)) { + !(node is PyTupleExpression && node.parent === boundExpression) + ) { if (node is PyExpression) { if (!PyTypeHintsInspection.isValidTypeHint(node, myTypeEvalContext)) { registerProblem( @@ -167,7 +168,8 @@ class PyNewStyleGenericSyntaxInspection : PyInspection() { override fun visitPyReferenceExpression(node: PyReferenceExpression) { node.getTypeParameterType()?.let { if (it.declarationElement is PyTargetExpression - && ScopeUtil.getScopeOwner(it.declarationElement) !is PyTypeAliasStatement) { + && ScopeUtil.getScopeOwner(it.declarationElement) !is PyTypeAliasStatement + ) { registerProblem(node, message, ProblemHighlightType.GENERIC_ERROR) } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNonAsciiCharInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNonAsciiCharInspection.java index f9db0c57f1ab..edb606c0f316 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNonAsciiCharInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyNonAsciiCharInspection.java @@ -57,6 +57,7 @@ public final class PyNonAsciiCharInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitComment(@NotNull PsiComment node) { checkString(node, node.getText()); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOldStyleClassesInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOldStyleClassesInspection.java index 9ba5cf5913b8..666ecd51856b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOldStyleClassesInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOldStyleClassesInspection.java @@ -38,7 +38,7 @@ import java.util.List; /** * User: catherine - * + *

* Inspection to detect occurrences of new-style class features in old-style classes */ public final class PyOldStyleClassesInspection extends PyInspection { @@ -54,6 +54,7 @@ public final class PyOldStyleClassesInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyClass(final @NotNull PyClass node) { final List expressions = node.getSuperClassTypes(myTypeEvalContext); @@ -65,16 +66,18 @@ public final class PyOldStyleClassesInspection extends PyInspection { if (!node.isNewStyleClass(myTypeEvalContext)) { for (PyTargetExpression attr : node.getClassAttributes()) { if (PyNames.SLOTS.equals(attr.getName())) { - registerProblem(attr, PyPsiBundle.message("INSP.oldstyle.class.slots"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, quickFixes.toArray( - LocalQuickFix.EMPTY_ARRAY)); + registerProblem(attr, PyPsiBundle.message("INSP.oldstyle.class.slots"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, + quickFixes.toArray( + LocalQuickFix.EMPTY_ARRAY)); } } for (PyFunction attr : node.getMethods()) { if (PyNames.GETATTRIBUTE.equals(attr.getName())) { final ASTNode nameNode = attr.getNameNode(); assert nameNode != null; - registerProblem(nameNode.getPsi(), PyPsiBundle.message("INSP.oldstyle.class.getattribute"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, quickFixes.toArray( - LocalQuickFix.EMPTY_ARRAY)); + registerProblem(nameNode.getPsi(), PyPsiBundle.message("INSP.oldstyle.class.getattribute"), + ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, quickFixes.toArray( + LocalQuickFix.EMPTY_ARRAY)); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOverridesInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOverridesInspection.kt index bb2608065925..ea54a252f718 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOverridesInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyOverridesInspection.kt @@ -13,16 +13,18 @@ import com.jetbrains.python.psi.types.TypeEvalContext class PyOverridesInspection : PyInspection() { - override fun buildVisitor(holder: ProblemsHolder, - isOnTheFly: Boolean, - session: LocalInspectionToolSession): PsiElementVisitor = + override fun buildVisitor( + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession, + ): PsiElementVisitor = Visitor(holder, PyInspectionVisitor.getContext(session)) private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPyFunction(node: PyFunction) { super.visitPyFunction(node) - + if (node.containingClass?.getAncestorTypes(myTypeEvalContext)?.contains(null) ?: false) return val overrideDecorator = node.decoratorList?.decorators?.firstOrNull { decorator -> diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyAccessInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyAccessInspection.java index 59c16e51308a..0bd2f704d4d9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyAccessInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyAccessInspection.java @@ -34,7 +34,9 @@ import org.jetbrains.annotations.NotNull; public final class PyPropertyAccessInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java index 13a6fed2d391..ef0511ce545d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyPropertyDefinitionInspection.java @@ -45,7 +45,9 @@ public final class PyPropertyDefinitionInspection extends PyInspection { private static final ImmutableList SUFFIXES = ImmutableList.of(PyNames.SETTER, PyNames.DELETER); @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java index f38711b3e9bc..94057c8ede51 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java @@ -42,7 +42,7 @@ import static com.intellij.codeInspection.options.OptPane.pane; /** * User: ktisha - * + *

* Inspection to detect situations, where * protected member (i.e. class member with a name beginning with an underscore) * is access outside the class or a descendant of the class where it's defined. @@ -63,6 +63,7 @@ public final class PyProtectedMemberInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyImportElement(@NotNull PyImportElement node) { final PyStatement statement = node.getContainingImportStatement(); @@ -159,8 +160,8 @@ public final class PyProtectedMemberInspection extends PyInspection { } final PyType type = myTypeEvalContext.getType(qualifier); final @InspectionMessage String message = type instanceof PyModuleType - ? PyPsiBundle.message("INSP.protected.member.access.to.protected.member.of.module", name) - : PyPsiBundle.message("INSP.protected.member.access.to.protected.member.of.class", name); + ? PyPsiBundle.message("INSP.protected.member.access.to.protected.member.of.module", name) + : PyPsiBundle.message("INSP.protected.member.access.to.protected.member.of.class", name); registerProblem(node, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, null, quickFixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyReachableElementVisitor.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyReachableElementVisitor.kt index ba20569b3d41..1c9d1487abff 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyReachableElementVisitor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyReachableElementVisitor.kt @@ -6,8 +6,8 @@ import com.jetbrains.python.psi.PyElementVisitor import com.jetbrains.python.psi.types.TypeEvalContext class PyReachableElementVisitor( - private val delegate: PyElementVisitor, - private val context: TypeEvalContext + private val delegate: PyElementVisitor, + private val context: TypeEvalContext, ) : PyElementVisitor() { override fun visitPyElement(node: PyElement) { if (!node.isUnreachableForInspection(context)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java index aca334dda5ff..585c51b84371 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyRedeclarationInspection.java @@ -62,6 +62,7 @@ public final class PyRedeclarationInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyFunction(final @NotNull PyFunction node) { if (!PyKnownDecoratorUtil.hasUnknownDecorator(node, myTypeEvalContext) && diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySetFunctionToLiteralInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySetFunctionToLiteralInspection.java index 32ff9dd87af7..37a165b0b49f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySetFunctionToLiteralInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySetFunctionToLiteralInspection.java @@ -29,7 +29,7 @@ import org.jetbrains.annotations.Nullable; /** * User: catherine - * + *

* Inspection to find set built-in function and replace it with set literal * available if the selected language level supports set literals. */ @@ -46,6 +46,7 @@ public final class PySetFunctionToLiteralInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyCallExpression(final @NotNull PyCallExpression node) { PyExpression callee = node.getCallee(); @@ -53,9 +54,10 @@ public final class PySetFunctionToLiteralInspection extends PyInspection { PyExpression[] arguments = node.getArguments(); if (arguments.length == 1) { PyElement[] elements = getSetCallArguments(node); - if (elements.length != 0) - registerProblem(node, PyPsiBundle.message("INSP.NAME.set.function.to.literal"), - new ReplaceFunctionWithSetLiteralQuickFix()); + if (elements.length != 0) { + registerProblem(node, PyPsiBundle.message("INSP.NAME.set.function.to.literal"), + new ReplaceFunctionWithSetLiteralQuickFix()); + } } } } @@ -67,13 +69,15 @@ public final class PySetFunctionToLiteralInspection extends PyInspection { return PyElement.EMPTY_ARRAY; } if ((argument instanceof PySequenceExpression || (argument instanceof PyParenthesizedExpression && - ((PyParenthesizedExpression)argument).getContainedExpression() instanceof PyTupleExpression))) { + ((PyParenthesizedExpression)argument).getContainedExpression() instanceof PyTupleExpression))) { - if (argument instanceof PySequenceExpression) + if (argument instanceof PySequenceExpression) { return ((PySequenceExpression)argument).getElements(); + } PyExpression tuple = ((PyParenthesizedExpression)argument).getContainedExpression(); - if (tuple instanceof PyTupleExpression) + if (tuple instanceof PyTupleExpression) { return ((PyTupleExpression)(tuple)).getElements(); + } } return PyElement.EMPTY_ARRAY; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyShadowingNamesInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyShadowingNamesInspection.java index eccb81bb1d7e..16c91fb1352a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyShadowingNamesInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyShadowingNamesInspection.java @@ -56,6 +56,7 @@ public final class PyShadowingNamesInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyClass(@NotNull PyClass node) { processElement(node); @@ -109,7 +110,7 @@ public final class PyShadowingNamesInspection extends PyInspection { return; } if (Arrays.stream(PyInspectionExtension.EP_NAME.getExtensions()) - .anyMatch(o -> o.ignoreShadowed(resolved))) { + .anyMatch(o -> o.ignoreShadowed(resolved))) { return; } registerProblem(problemElement, PyPsiBundle.message("INSP.shadows.name.from.outer.scope", name), diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySimplifyBooleanCheckInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySimplifyBooleanCheckInspection.java index 46744f659da1..ae3b0d4cfdfa 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySimplifyBooleanCheckInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySimplifyBooleanCheckInspection.java @@ -84,7 +84,7 @@ public final class PySimplifyBooleanCheckInspection extends PyInspection { PyBinaryExpressionVisitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context, - boolean ignoreComparisonToZero) { + boolean ignoreComparisonToZero) { super(holder, context); myIgnoreComparisonToZero = ignoreComparisonToZero; } @@ -112,10 +112,10 @@ public final class PySimplifyBooleanCheckInspection extends PyInspection { // because we are comparing to literal values, there will only ever be a union on one side final var unionMembers = (leftType instanceof PyUnionType unionType) + ? unionType.getMembers() + : (rightType instanceof PyUnionType unionType) ? unionType.getMembers() - : (rightType instanceof PyUnionType unionType) - ? unionType.getMembers() - : null; + : null; final var isOptional = unionMembers != null && ContainerUtil.exists(unionMembers, PyNoneTypeKt::isNoneType); @@ -156,7 +156,8 @@ public final class PySimplifyBooleanCheckInspection extends PyInspection { } private void registerProblem(PyBinaryExpression binaryExpression) { - registerProblem(binaryExpression, PyPsiBundle.message("INSP.expression.can.be.simplified"), new SimplifyBooleanCheckQuickFix(binaryExpression)); + registerProblem(binaryExpression, PyPsiBundle.message("INSP.expression.can.be.simplified"), + new SimplifyBooleanCheckQuickFix(binaryExpression)); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySingleQuotedDocstringInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySingleQuotedDocstringInspection.java index 8c12f2651bb1..fccdab7dbf55 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySingleQuotedDocstringInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySingleQuotedDocstringInspection.java @@ -31,7 +31,7 @@ import org.jetbrains.annotations.Nullable; /** * User: catherine - * + *

* Inspection to detect docstrings not using triple double-quoted string */ public final class PySingleQuotedDocstringInspection extends PyInspection { @@ -55,7 +55,7 @@ public final class PySingleQuotedDocstringInspection extends PyInspection { stringText = stringText.substring(length); final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(string, PyDocStringOwner.class); if (docStringOwner != null) { - if (docStringOwner.getDocStringExpression() == string) { + if (docStringOwner.getDocStringExpression() == string) { if (!stringText.startsWith("\"\"\"") && !stringText.endsWith("\"\"\"")) { ProblemsHolder holder = getHolder(); if (holder != null) { @@ -63,12 +63,13 @@ public final class PySingleQuotedDocstringInspection extends PyInspection { if (stringText.startsWith("'''") && stringText.endsWith("'''")) { quoteCount = 3; } - TextRange trStart = new TextRange(length, length+quoteCount); - TextRange trEnd = new TextRange(stringText.length()+length-quoteCount, - stringText.length()+length); - if (string.getStringValue().isEmpty()) + TextRange trStart = new TextRange(length, length + quoteCount); + TextRange trEnd = new TextRange(stringText.length() + length - quoteCount, + stringText.length() + length); + if (string.getStringValue().isEmpty()) { holder.registerProblem(string, PyPsiBundle.message("INSP.message.single.quoted.docstring"), new ConvertDocstringQuickFix()); + } else { holder.registerProblem(string, trStart, PyPsiBundle.message("INSP.message.single.quoted.docstring"), new ConvertDocstringQuickFix()); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyStatementEffectInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyStatementEffectInspection.java index c14371dab14b..db08c0fd88a3 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyStatementEffectInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyStatementEffectInspection.java @@ -38,7 +38,9 @@ import java.util.List; public final class PyStatementEffectInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } @@ -60,8 +62,9 @@ public final class PyStatementEffectInspection extends PyInspection { return; } final PyExpression expression = node.getExpression(); - if (PsiTreeUtil.hasErrorElements(expression)) + if (PsiTreeUtil.hasErrorElements(expression)) { return; + } if (hasEffect(expression)) return; // https://twitter.com/gvanrossum/status/112670605505077248 diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySuperArgumentsInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySuperArgumentsInspection.java index 4e8c4b201ab1..bb3d3d9d8e46 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PySuperArgumentsInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PySuperArgumentsInspection.java @@ -34,7 +34,9 @@ import org.jetbrains.annotations.Nullable; public final class PySuperArgumentsInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } @@ -72,7 +74,9 @@ public final class PySuperArgumentsInspection extends PyInspection { private @Nullable PyClass findClassOf(PyExpression argument) { PsiElement firstElement = ((PyReferenceExpression)argument).followAssignmentsChain(getResolveContext()).getElement(); PyClass firstClass = null; - if (firstElement instanceof PyClass) firstClass = (PyClass)firstElement; + if (firstElement instanceof PyClass) { + firstClass = (PyClass)firstElement; + } else if (firstElement instanceof PyExpression) { PyType first_type = myTypeEvalContext.getType((PyExpression)firstElement); if (first_type instanceof PyClassType) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleAssignmentBalanceInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleAssignmentBalanceInspection.java index eca1d873c23d..e99fc0ae49b4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleAssignmentBalanceInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleAssignmentBalanceInspection.java @@ -45,6 +45,7 @@ public final class PyTupleAssignmentBalanceInspection extends PyInspection { Visitor(@Nullable ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } + @Override public void visitPyAssignmentStatement(@NotNull PyAssignmentStatement node) { final PyExpression lhsExpression = PyPsiUtils.flattenParens(node.getLeftHandSideExpression()); @@ -107,7 +108,7 @@ public final class PyTupleAssignmentBalanceInspection extends PyInspection { private static int countStarExpressions(PyExpression @NotNull [] expressions) { if (expressions.length != 0 && !LanguageLevel.forElement(expressions[0]).isPython2()) { - return (int) Arrays + return (int)Arrays .stream(expressions) .filter(PyStarExpression.class::isInstance) .count(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleItemAssignmentInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleItemAssignmentInspection.java index d06a707c5076..be2046e57ba6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleItemAssignmentInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTupleItemAssignmentInspection.java @@ -33,7 +33,9 @@ import org.jetbrains.annotations.NotNull; public final class PyTupleItemAssignmentInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java index 7bed62b15d42..711068574dd1 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspection.java @@ -41,7 +41,9 @@ public class PyTypeCheckerInspection extends PyInspection { private static final Key TIME_KEY = Key.create("PyTypeCheckerInspection.StartTime"); @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { if (LOG.isDebugEnabled()) { session.putUserData(TIME_KEY, System.nanoTime()); } @@ -130,7 +132,8 @@ public class PyTypeCheckerInspection extends PyInspection { final String expectedName = PythonDocumentationProvider.getVerboseTypeName(expected, myTypeEvalContext); final String actualName = PythonDocumentationProvider.getTypeName(actual, myTypeEvalContext); getHolder() - .problem(returnExpr != null ? returnExpr : node, PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedName, actualName)) + .problem(returnExpr != null ? returnExpr : node, + PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedName, actualName)) .fix(new PyMakeFunctionReturnTypeQuickFix(function, myTypeEvalContext)) .register(); } @@ -142,18 +145,18 @@ public class PyTypeCheckerInspection extends PyInspection { public void visitPyYieldExpression(@NotNull PyYieldExpression node) { ScopeOwner owner = ScopeUtil.getScopeOwner(node); if (!(owner instanceof PyFunction function)) return; - + if (node.isDelegating()) { visitDelegatingYieldExpression(node, function); return; } - + final var annotatedGeneratorDesc = getGeneratorDescriptorFromAnnotation(function, node); if (annotatedGeneratorDesc == null) return; - + checkYieldType(annotatedGeneratorDesc.yieldType(), node, function); } - + private void visitDelegatingYieldExpression(@NotNull PyYieldExpression node, @NotNull PyFunction function) { assert node.isDelegating(); @@ -185,8 +188,9 @@ public class PyTypeCheckerInspection extends PyInspection { registerProblem(yieldExpr, PyPsiBundle.message("INSP.type.checker.yield.from.send.type.mismatch", expectedName, actualName)); } } - - private @Nullable GeneratorTypeDescriptor getGeneratorDescriptorFromAnnotation(@NotNull PyFunction function, @NotNull PyYieldExpression yieldExpr) { + + private @Nullable GeneratorTypeDescriptor getGeneratorDescriptorFromAnnotation(@NotNull PyFunction function, + @NotNull PyYieldExpression yieldExpr) { final PyAnnotation annotation = function.getAnnotation(); final String typeCommentAnnotation = function.getTypeCommentAnnotation(); if (annotation == null && typeCommentAnnotation == null) return null; @@ -209,7 +213,7 @@ public class PyTypeCheckerInspection extends PyInspection { } return annotatedGeneratorDesc; } - + private boolean checkYieldType(@Nullable PyType expectedYieldType, @NotNull PyYieldExpression node, @NotNull PyFunction function) { final PyType thisYieldType = node.getYieldType(myTypeEvalContext); if (!PyTypeChecker.match(expectedYieldType, thisYieldType, myTypeEvalContext)) { @@ -217,7 +221,8 @@ public class PyTypeCheckerInspection extends PyInspection { String expectedName = PythonDocumentationProvider.getVerboseTypeName(expectedYieldType, myTypeEvalContext); String actualName = PythonDocumentationProvider.getTypeName(thisYieldType, myTypeEvalContext); getHolder() - .problem(yieldExpr != null ? yieldExpr : node, PyPsiBundle.message("INSP.type.checker.yield.type.mismatch", expectedName, actualName)) + .problem(yieldExpr != null ? yieldExpr : node, + PyPsiBundle.message("INSP.type.checker.yield.type.mismatch", expectedName, actualName)) .fix(new PyMakeFunctionReturnTypeQuickFix(function, myTypeEvalContext)) .register(); return true; @@ -258,7 +263,8 @@ public class PyTypeCheckerInspection extends PyInspection { PyType expected = myTypeEvalContext.getType(node); Ref classAttrType = getClassAttributeType(node); if (classAttrType != null) { - Ref dunderSetValueType = PyDescriptorTypeUtil.getExpectedValueTypeForDunderSet(node, classAttrType.get(), myTypeEvalContext); + Ref dunderSetValueType = + PyDescriptorTypeUtil.getExpectedValueTypeForDunderSet(node, classAttrType.get(), myTypeEvalContext); if (dunderSetValueType != null) { expected = dunderSetValueType.get(); descriptor = true; @@ -303,7 +309,9 @@ public class PyTypeCheckerInspection extends PyInspection { private static boolean requiresTypeSpecialization(@Nullable PyType type) { if (type instanceof PyTypeParameterType typeParameterType && typeParameterType.getDefaultType() == null && - !(type instanceof PySelfType)) return true; + !(type instanceof PySelfType)) { + return true; + } return type instanceof PyCollectionType collectionType && exists(collectionType.getElementTypes(), Visitor::requiresTypeSpecialization); } @@ -495,7 +503,8 @@ public class PyTypeCheckerInspection extends PyInspection { final var paramSpec = concatenateType.getParamSpec(); final var restArguments = allArguments.subList(argumentRightBound, allArguments.size()); if (paramSpec != null) { - analyzeParamSpec(paramSpec, restArguments, substitutions, result, unexpectedArgumentForParamSpecs, unfilledParameterFromParamSpecs); + analyzeParamSpec(paramSpec, restArguments, substitutions, result, unexpectedArgumentForParamSpecs, + unfilledParameterFromParamSpecs); } } @@ -515,7 +524,8 @@ public class PyTypeCheckerInspection extends PyInspection { PyParamSpecType paramSpecType = getParamSpecTypeFromContainerParameters(keywordContainer, positionalContainer); if (paramSpecType != null) { - analyzeParamSpec(paramSpecType, allArguments, substitutions, result, unexpectedArgumentForParamSpecs, unfilledParameterFromParamSpecs); + analyzeParamSpec(paramSpecType, allArguments, substitutions, result, unexpectedArgumentForParamSpecs, + unfilledParameterFromParamSpecs); } else { if (positionalContainer != null) { @@ -527,24 +537,23 @@ public class PyTypeCheckerInspection extends PyInspection { } List unfilledPositionalVarargs = new ArrayList<>(); - for (var unmappedContainer: mapping.getUnmappedContainerParameters()) { + for (var unmappedContainer : mapping.getUnmappedContainerParameters()) { PyType containerType = unmappedContainer.getArgumentType(myTypeEvalContext); if (unmappedContainer.getName() == null || !(containerType instanceof PyPositionalVariadicType)) continue; PyType expandedVararg = PyTypeChecker.substitute(containerType, substitutions, myTypeEvalContext); if (!(expandedVararg instanceof PyUnpackedTupleType unpackedTuple) || unpackedTuple.isUnbound()) continue; unfilledPositionalVarargs.add( - new UnfilledPositionalVararg(unmappedContainer.getName(), + new UnfilledPositionalVararg(unmappedContainer.getName(), PythonDocumentationProvider.getTypeName(expandedVararg, myTypeEvalContext))); } - return new AnalyzeCalleeResults(callableType, callableType.getCallable(), result, + return new AnalyzeCalleeResults(callableType, callableType.getCallable(), result, unexpectedArgumentForParamSpecs, unfilledParameterFromParamSpecs, unfilledPositionalVarargs); } - private void analyzeParamSpec(@NotNull PyParamSpecType paramSpec, @NotNull List arguments, @NotNull PyTypeChecker.GenericSubstitutions substitutions, @NotNull List result, @@ -554,7 +563,7 @@ public class PyTypeCheckerInspection extends PyInspection { if (paramSpecSubst == null) return; var mapping = analyzeArguments(arguments, paramSpecSubst.getParameters(), myTypeEvalContext); - for (var item: mapping.getMappedParameters().entrySet()) { + for (var item : mapping.getMappedParameters().entrySet()) { PyExpression argument = item.getKey(); PyCallableParameter parameter = item.getValue(); PyType argType = myTypeEvalContext.getType(argument); @@ -563,7 +572,7 @@ public class PyTypeCheckerInspection extends PyInspection { result.add(new AnalyzeArgumentResult(argument, paramType, substituteGenerics(paramType, substitutions), argType, matched)); } if (!mapping.getUnmappedArguments().isEmpty()) { - for (var argument: mapping.getUnmappedArguments()) { + for (var argument : mapping.getUnmappedArguments()) { unexpectedArgumentForParamSpecs.add(new UnexpectedArgumentForParamSpec(argument, paramSpec)); } } @@ -654,7 +663,8 @@ public class PyTypeCheckerInspection extends PyInspection { !PyProtocolsKt.matchingProtocolDefinitions(parameterType, argumentType, myTypeEvalContext); } - private @Nullable PyType substituteGenerics(@Nullable PyType expectedArgumentType, @NotNull PyTypeChecker.GenericSubstitutions substitutions) { + private @Nullable PyType substituteGenerics(@Nullable PyType expectedArgumentType, + @NotNull PyTypeChecker.GenericSubstitutions substitutions) { return PyTypeChecker.hasGenerics(expectedArgumentType, myTypeEvalContext) ? PyTypeChecker.substitute(expectedArgumentType, substitutions, myTypeEvalContext) : null; @@ -835,5 +845,4 @@ public class PyTypeCheckerInspection extends PyInspection { record UnfilledPositionalVararg(@NotNull String varargName, @NotNull String expectedTypes) { } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspectionProblemRegistrar.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspectionProblemRegistrar.java index 6eafb91cd1e0..35df41e6eab8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspectionProblemRegistrar.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeCheckerInspectionProblemRegistrar.java @@ -84,7 +84,8 @@ final class PyTypeCheckerInspectionProblemRegistrar { var parameterName = unfilledParameterFromParamSpec.getParameter().getName(); var paramSpecTypeName = unfilledParameterFromParamSpec.getParamSpecType().getVariableName(); if (parameterName != null) { - visitor.registerProblem(rpar, PyPsiBundle.message("INSP.type.checker.unfilled.parameter.for.paramspec", parameterName, paramSpecTypeName)); + visitor.registerProblem(rpar, PyPsiBundle.message("INSP.type.checker.unfilled.parameter.for.paramspec", parameterName, + paramSpecTypeName)); } } @@ -151,7 +152,8 @@ final class PyTypeCheckerInspectionProblemRegistrar { } if (expectedSubstitutedName != null) { - return PyPsiBundle.message("INSP.type.checker.expected.matched.type.got.type.instead", expectedSubstitutedName, expectedTypeName, actualTypeName); + return PyPsiBundle.message("INSP.type.checker.expected.matched.type.got.type.instead", expectedSubstitutedName, expectedTypeName, + actualTypeName); } else { return PyPsiBundle.message("INSP.type.checker.expected.type.got.type.instead", expectedTypeName, actualTypeName); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt index 97ba63a59935..73c06ada355d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypeHintsInspection.kt @@ -71,7 +71,7 @@ class PyTypeHintsInspection : PyInspection() { val calleeQName = callee?.let { PyResolveUtil.resolveImportedElementQNameLocally(it) } ?: emptyList() if (QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR) in calleeQName || - QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR_EXT) in calleeQName) { + QualifiedName.fromDottedString(PyTypingTypeProvider.TYPE_VAR_EXT) in calleeQName) { val target = getTargetFromAssignment(node) checkTypeVarPlacement(node, target) @@ -135,7 +135,8 @@ class PyTypeHintsInspection : PyInspection() { val typeExpression = node.typeExpression ?: return if (!isValidTypeHint(typeExpression, myTypeEvalContext)) { registerProblem(typeExpression, PyPsiBundle.message("INSP.type.hints.type.hint.is.not.valid")) - } else { + } + else { val typeExpression = node.typeExpression if (typeExpression != null) { if (PyTypingTypeProvider.getType(typeExpression, myTypeEvalContext) == null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt index ac83335a4d53..e57ccbb07d2b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyTypedDictInspection.kt @@ -23,9 +23,11 @@ import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL class PyTypedDictInspection : PyInspection() { - override fun buildVisitor(holder: ProblemsHolder, - isOnTheFly: Boolean, - session: LocalInspectionToolSession): PsiElementVisitor { + override fun buildVisitor( + holder: ProblemsHolder, + isOnTheFly: Boolean, + session: LocalInspectionToolSession, + ): PsiElementVisitor { return Visitor(holder, PyInspectionVisitor.getContext(session)) } @@ -366,8 +368,10 @@ class PyTypedDictInspection : PyInspection() { } } - private fun matchTypedDictFieldTypeAndTotality(expected: PyTypedDictType.FieldTypeAndTotality, - actual: PyTypedDictType.FieldTypeAndTotality): Boolean { + private fun matchTypedDictFieldTypeAndTotality( + expected: PyTypedDictType.FieldTypeAndTotality, + actual: PyTypedDictType.FieldTypeAndTotality, + ): Boolean { return expected.qualifiers.isRequired == actual.qualifiers.isRequired && PyTypeChecker.match(expected.type, actual.type, myTypeEvalContext) } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java index 20ff67c94233..e3bf0b0b6623 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnboundLocalVariableInspection.java @@ -36,12 +36,15 @@ import java.util.Set; public final class PyUnboundLocalVariableInspection extends PyInspection { @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, final @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + final @NotNull LocalInspectionToolSession session) { return new Visitor(holder, PyInspectionVisitor.getContext(session)); } public static class Visitor extends PyInspectionVisitor { Set LARGE_FUNCTIONS = new HashSet<>(); + Visitor(final ProblemsHolder holder, @NotNull TypeEvalContext context) { super(holder, context); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnnecessaryBackslashInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnnecessaryBackslashInspection.java index 18ece57dcfa7..a72e72f5ab7e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnnecessaryBackslashInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnnecessaryBackslashInspection.java @@ -60,8 +60,9 @@ public final class PyUnnecessaryBackslashInspection extends PyInspection { @Override public void visitPyTupleExpression(@NotNull PyTupleExpression node) { - if (node.getParent() instanceof PyParenthesizedExpression) + if (node.getParent() instanceof PyParenthesizedExpression) { findProblem(node); + } } @Override @@ -117,6 +118,5 @@ public final class PyUnnecessaryBackslashInspection extends PyInspection { } } } - } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnresolvedReferenceQuickFixProvider.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnresolvedReferenceQuickFixProvider.java index 2b0ca1a8d69f..1657c615101a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnresolvedReferenceQuickFixProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/PyUnresolvedReferenceQuickFixProvider.java @@ -10,11 +10,12 @@ import java.util.List; public interface PyUnresolvedReferenceQuickFixProvider { - ExtensionPointName EP_NAME = ExtensionPointName.create("Pythonid.unresolvedReferenceQuickFixProvider"); + ExtensionPointName EP_NAME = + ExtensionPointName.create("Pythonid.unresolvedReferenceQuickFixProvider"); /** * @param reference The reference containing an unresolved import. - * @param existing All already suggested quick fixes, including not only import fixes. + * @param existing All already suggested quick fixes, including not only import fixes. */ void registerQuickFixes(@NotNull PsiReference reference, @NotNull List existing); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AddGlobalQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AddGlobalQuickFix.java index 1c453dc0cf32..9552c5bdceab 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AddGlobalQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AddGlobalQuickFix.java @@ -23,31 +23,34 @@ public class AddGlobalQuickFix extends PsiUpdateModCommandQuickFix { if (element instanceof PyReferenceExpression expression) { final String name = expression.getReferencedName(); final ScopeOwner owner = PsiTreeUtil.getParentOfType(element, ScopeOwner.class); - assert owner instanceof PyClass || owner instanceof PyFunction : "Add global quickfix is available only inside class or function, but applied for " + owner; + assert owner instanceof PyClass || owner instanceof PyFunction : + "Add global quickfix is available only inside class or function, but applied for " + + owner; final Ref added = new Ref<>(false); - owner.accept(new PyRecursiveElementVisitor(){ + owner.accept(new PyRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { - if (!added.get()){ + if (!added.get()) { super.visitElement(element); } } + @Override public void visitPyGlobalStatement(final @NotNull PyGlobalStatement node) { - if (!added.get()){ + if (!added.get()) { node.addGlobal(name); added.set(true); } } }); - if (added.get()){ + if (added.get()) { return; } final PyGlobalStatement globalStatement = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyGlobalStatement.class, "global " + name); final PyStatementList statementList; boolean hasDocString = false; - if (owner instanceof PyClass){ + if (owner instanceof PyClass) { statementList = ((PyClass)owner).getStatementList(); if (((PyClass)owner).getDocStringExpression() != null) hasDocString = true; } @@ -56,8 +59,9 @@ public class AddGlobalQuickFix extends PsiUpdateModCommandQuickFix { if (((PyFunction)owner).getDocStringExpression() != null) hasDocString = true; } PyStatement first = statementList.getStatements()[0]; - if (hasDocString) + if (hasDocString) { first = statementList.getStatements()[1]; + } statementList.addBefore(globalStatement, first); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AugmentedAssignmentQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AugmentedAssignmentQuickFix.java index b7ee417cb0d2..4615e110236a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AugmentedAssignmentQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/AugmentedAssignmentQuickFix.java @@ -16,7 +16,7 @@ import java.util.List; /** * User: catherine - * + *

* QuickFix to replace assignment that can be replaced with augmented assignment. * for instance, i = i + 1 --> i +=1 */ @@ -35,8 +35,9 @@ public class AugmentedAssignmentQuickFix extends PsiUpdateModCommandQuickFix { if (expression == null) return; PyExpression leftExpression = expression.getLeftExpression(); PyExpression rightExpression = expression.getRightExpression(); - if (rightExpression instanceof PyParenthesizedExpression) + if (rightExpression instanceof PyParenthesizedExpression) { rightExpression = ((PyParenthesizedExpression)rightExpression).getContainedExpression(); + } if (target != null && rightExpression != null) { final String targetText = target.getText(); final String rightText = rightExpression.getText(); @@ -54,16 +55,17 @@ public class AugmentedAssignmentQuickFix extends PsiUpdateModCommandQuickFix { final PsiElement psiOperator = expression.getPsiOperator(); if (psiOperator == null) return; stringBuilder.append(targetText).append(" "). - append(psiOperator.getText()).append("= ").append(rightExpression.getText()); + append(psiOperator.getText()).append("= ").append(rightExpression.getText()); final PyAugAssignmentStatementImpl augAssignment = elementGenerator.createFromText(LanguageLevel.forElement(element), - PyAugAssignmentStatementImpl.class, stringBuilder.toString()); - for (PsiComment comment : comments) + PyAugAssignmentStatementImpl.class, + stringBuilder.toString()); + for (PsiComment comment : comments) { augAssignment.add(comment); + } statement.replace(augAssignment); } } } } } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ChainedComparisonsQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ChainedComparisonsQuickFix.java index 464f1600905d..e6857a054f8e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ChainedComparisonsQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ChainedComparisonsQuickFix.java @@ -22,7 +22,7 @@ import static com.jetbrains.python.psi.PyUtil.as; /** * User: catherine - * + *

* QuickFix to replace chained comparisons with more simple version * For instance, a < b and b < c --> a < b < c */ @@ -97,7 +97,8 @@ public class ChainedComparisonsQuickFix extends PsiUpdateModCommandQuickFix { rightExpression.delete(); } - private static @NotNull PyExpression makePsiConsistentBinaryExpression(@NotNull Project project, @NotNull PyBinaryExpression binaryExpression) { + private static @NotNull PyExpression makePsiConsistentBinaryExpression(@NotNull Project project, + @NotNull PyBinaryExpression binaryExpression) { final ArrayList elements = new ArrayList<>(); final ArrayList operators = new ArrayList<>(); collectExpressionsDfs(elements, operators, binaryExpression); @@ -155,7 +156,8 @@ public class ChainedComparisonsQuickFix extends PsiUpdateModCommandQuickFix { return op; } - private static @NotNull PyExpression invertExpression(@NotNull PyBinaryExpression expression, @NotNull PyElementGenerator elementGenerator) { + private static @NotNull PyExpression invertExpression(@NotNull PyBinaryExpression expression, + @NotNull PyElementGenerator elementGenerator) { if (isComparisonExpression(expression)) { final PyExpression left = expression.getLeftExpression(); final PyExpression right = expression.getRightExpression(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java index 75ddc1b8c22b..2756f7b3414d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ConvertDocstringQuickFix.java @@ -16,7 +16,7 @@ import org.jetbrains.annotations.NotNull; /** * User: catherine - * + *

* QuickFix to convert docstrings to the common form according to PEP-257 * For consistency, always use """triple double quotes""" around docstrings. */ @@ -35,19 +35,21 @@ public class ConvertDocstringQuickFix extends PsiUpdateModCommandQuickFix { int prefixLength = PyStringLiteralUtil.getPrefixLength(stringText); String prefix = stringText.substring(0, prefixLength); String content = stringText.substring(prefixLength); - if (content.startsWith("'''") ) { - content = content.substring(3, content.length()-3); - } else if (content.startsWith("\"\"\"")) + if (content.startsWith("'''")) { + content = content.substring(3, content.length() - 3); + } + else if (content.startsWith("\"\"\"")) { return; + } else { - content = content.length() == 1 ? "" : content.substring(1, content.length()-1); + content = content.length() == 1 ? "" : content.substring(1, content.length() - 1); + } + if (content.endsWith("\"")) { + content = StringUtil.replaceSubstring(content, TextRange.create(content.length() - 1, content.length()), "\\\""); } - if (content.endsWith("\"")) - content = StringUtil.replaceSubstring(content, TextRange.create(content.length()-1, content.length()), "\\\""); - PyExpression newString = elementGenerator.createDocstring(prefix+"\"\"\"" + content + "\"\"\"").getExpression(); + PyExpression newString = elementGenerator.createDocstring(prefix + "\"\"\"" + content + "\"\"\"").getExpression(); element.replace(newString); } } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ListCreationQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ListCreationQuickFix.java index edeb53fb1fc2..bb9837a4e222 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ListCreationQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ListCreationQuickFix.java @@ -43,7 +43,8 @@ public class ListCreationQuickFix extends PsiUpdateModCommandQuickFix { assignedValue.replace(elementGenerator.createExpressionFromText(LanguageLevel.forElement(assignedValue), text)); } - private static @NotNull List buildLiteralItems(@NotNull PyExpression assignedValue, List statements) { + private static @NotNull List buildLiteralItems(@NotNull PyExpression assignedValue, + List statements) { final List values = new ArrayList<>(); ContainerUtil.addAll(values, ((PyListLiteralExpression)assignedValue).getElements()); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddExceptionSuperClassQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddExceptionSuperClassQuickFix.java index 5a616b1b356e..de6a9d24a302 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddExceptionSuperClassQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddExceptionSuperClassQuickFix.java @@ -46,5 +46,4 @@ public class PyAddExceptionSuperClassQuickFix extends PsiUpdateModCommandQuickFi } } } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddPropertyForFieldQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddPropertyForFieldQuickFix.java index 741a8aaaec32..43864c2ce2c3 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddPropertyForFieldQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddPropertyForFieldQuickFix.java @@ -37,10 +37,11 @@ public class PyAddPropertyForFieldQuickFix extends PsiUpdateModCommandQuickFix { final String name = target.getName(); if (name == null) return; String propertyName = StringUtil.trimStart(name, "_"); - final Map properties = containingClass.getProperties(); + final Map properties = containingClass.getProperties(); final PyElementGenerator generator = PyElementGenerator.getInstance(project); if (!properties.containsKey(propertyName)) { - final PyFunction property = generator.createProperty(LanguageLevel.forElement(containingClass), propertyName, name, AccessDirection.READ); + final PyFunction property = + generator.createProperty(LanguageLevel.forElement(containingClass), propertyName, name, AccessDirection.READ); PyPsiRefactoringUtil.addElementToStatementList(property, containingClass.getStatementList(), false); } final PyExpression qualifier = ((PyReferenceExpression)element).getQualifier(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddSpecifierToFormatQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddSpecifierToFormatQuickFix.java index a0c75464eeaa..f14fb842a178 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddSpecifierToFormatQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyAddSpecifierToFormatQuickFix.java @@ -63,7 +63,8 @@ public class PyAddSpecifierToFormatQuickFix extends PsiUpdateModCommandQuickFix int shift = 1; for (int i = 0; i < chunks.size(); i++) { - final PyStringFormatParser.PercentSubstitutionChunk chunk = PyUtil.as(chunks.get(i), PyStringFormatParser.PercentSubstitutionChunk.class); + final PyStringFormatParser.PercentSubstitutionChunk chunk = + PyUtil.as(chunks.get(i), PyStringFormatParser.PercentSubstitutionChunk.class); if (chunk != null) { if (elements.length <= i) return; final PyType type = context.getType(elements[i]); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyDefaultArgumentQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyDefaultArgumentQuickFix.java index e654d8d8e60a..59e45dd68a01 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyDefaultArgumentQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyDefaultArgumentQuickFix.java @@ -28,14 +28,14 @@ import org.jetbrains.annotations.NotNull; /** * User: catherine - * + *

* QuickFix to replace mutable default argument. For instance, * def foo(args=[]): - pass + * pass * replace with: * def foo(args=None): - if not args: args = [] - pass + * if not args: args = [] + * pass */ public class PyDefaultArgumentQuickFix extends PsiUpdateModCommandQuickFix { @@ -53,7 +53,7 @@ public class PyDefaultArgumentQuickFix extends PsiUpdateModCommandQuickFix { if (function != null && defName != null) { final PyElementGenerator generator = PyElementGenerator.getInstance(project); final LanguageLevel languageLevel = LanguageLevel.forElement(function); - + final PyNamedParameter newParam = generator.createParameter(defName, PyNames.NONE, null, languageLevel); param.replace(newParam); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeFunctionReturnTypeQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeFunctionReturnTypeQuickFix.java index c11ebca524f9..9a9224f583ef 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeFunctionReturnTypeQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeFunctionReturnTypeQuickFix.java @@ -77,7 +77,7 @@ public class PyMakeFunctionReturnTypeQuickFix extends PsiUpdateModCommandAction< PyTypeHintGenerationUtil.addImportsForTypeAnnotations(List.of(myReturnTypeFqName), function); } } - + PsiComment typeComment = function.getTypeComment(); if (typeComment != null) { StringBuilder typeCommentAnnotation = new StringBuilder(typeComment.getText()); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeReturnExplicitFix.kt b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeReturnExplicitFix.kt index 9d33cbb8ef77..5f708d14c69e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeReturnExplicitFix.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyMakeReturnExplicitFix.kt @@ -20,7 +20,7 @@ class PyMakeReturnExplicitFix(statement: PyStatement) : PsiUpdateModCommandActio } return super.getPresentation(context, element) } - + override fun invoke(context: ActionContext, element: PyStatement, updater: ModPsiUpdater) { val elementGenerator = PyElementGenerator.getInstance(element.getProject()) val languageLevel = LanguageLevel.forElement(element) diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyQuickFixUtil.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyQuickFixUtil.java index 532041d72c7c..6e54229ad2fb 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyQuickFixUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyQuickFixUtil.java @@ -11,7 +11,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class PyQuickFixUtil { - public static @Nullable Editor getEditor(@NotNull PsiElement element) { + public static @Nullable Editor getEditor(@NotNull PsiElement element) { Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile()); if (document == null) { return null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRemoveStatementQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRemoveStatementQuickFix.java index 583b044c160c..4d564b3f1930 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRemoveStatementQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRemoveStatementQuickFix.java @@ -24,7 +24,7 @@ import com.jetbrains.python.PyPsiBundle; import com.jetbrains.python.psi.PyStatement; import org.jetbrains.annotations.NotNull; -public class PyRemoveStatementQuickFix extends PsiUpdateModCommandQuickFix { +public class PyRemoveStatementQuickFix extends PsiUpdateModCommandQuickFix { @Override public @NotNull String getFamilyName() { return PyPsiBundle.message("QFIX.NAME.remove.statement"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRenameUnresolvedRefQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRenameUnresolvedRefQuickFix.java index 8088394bc842..d436f3880991 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRenameUnresolvedRefQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyRenameUnresolvedRefQuickFix.java @@ -39,7 +39,7 @@ import java.util.*; /** * User : ktisha - * + *

* Quick fix to rename unresolved references */ public class PyRenameUnresolvedRefQuickFix implements LocalQuickFix { @@ -66,7 +66,7 @@ public class PyRenameUnresolvedRefQuickFix implements LocalQuickFix { ReferenceNameExpression refExpr = new ReferenceNameExpression(items, name); TemplateBuilderImpl builder = (TemplateBuilderImpl)TemplateBuilderFactory.getInstance(). - createTemplateBuilder(parentScope); + createTemplateBuilder(parentScope); for (PyReferenceExpression expr : refs) { if (!expr.equals(referenceExpression)) { builder.replaceElement(expr, name, name, false); @@ -82,7 +82,7 @@ public class PyRenameUnresolvedRefQuickFix implements LocalQuickFix { public static boolean isValidReference(final PsiReference reference) { if (!(reference instanceof PyReferenceImpl)) return false; ResolveResult[] results = ((PyReferenceImpl)reference).multiResolve(true); - if(results.length == 0) return false; + if (results.length == 0) return false; for (ResolveResult result : results) { if (!result.isValidResult()) return false; } @@ -113,8 +113,9 @@ public class PyRenameUnresolvedRefQuickFix implements LocalQuickFix { final Collection usedNames = PyUtil.collectUsedNames(parentScope); for (String name : usedNames) { - if (name != null) + if (name != null) { items.add(LookupElementBuilder.create(name)); + } } return items.toArray(LookupElement.EMPTY_ARRAY); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyReplaceTupleWithListQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyReplaceTupleWithListQuickFix.java index 961224fa59ff..d555341177f6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyReplaceTupleWithListQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyReplaceTupleWithListQuickFix.java @@ -52,7 +52,7 @@ public class PyReplaceTupleWithListQuickFix extends PsiUpdateModCommandQuickFix } private static void replaceWithListLiteral(PsiElement element, PyTupleExpression expression) { - final String expressionText = expression.isEmpty() ? "" :expression.getText(); + final String expressionText = expression.isEmpty() ? "" : expression.getText(); final PyExpression literal = PyElementGenerator.getInstance(element.getProject()). createExpressionFromText(LanguageLevel.forElement(element), "[" + expressionText + "]"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyUnpackTypeVarTupleQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyUnpackTypeVarTupleQuickFix.java index ca03f8f0a74c..be4d7cb6be3d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyUnpackTypeVarTupleQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/PyUnpackTypeVarTupleQuickFix.java @@ -20,7 +20,7 @@ public class PyUnpackTypeVarTupleQuickFix extends PsiUpdateModCommandQuickFix { } public static void replaceToTypingExtensionsUnpack(@NotNull PsiElement elementTpReplace, @NotNull PsiElement elementInUnpack, - @NotNull PsiFile file, @NotNull Project project) { + @NotNull PsiFile file, @NotNull Project project) { AddImportHelper.addOrUpdateFromImportStatement(file, "typing_extensions", "Unpack", null, AddImportHelper.ImportPriority.FUTURE, null); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemovePrefixQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemovePrefixQuickFix.java index 61aa39cc62f7..d60570dcbd01 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemovePrefixQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemovePrefixQuickFix.java @@ -54,7 +54,8 @@ public class RemovePrefixQuickFix extends PsiUpdateModCommandQuickFix { final String nodeText = node.getText(); final int prefixLength = PyStringLiteralUtil.getPrefixLength(nodeText); if (nodeText.substring(0, prefixLength).equalsIgnoreCase(myPrefix)) { - final PyStringLiteralExpression replacement = elementGenerator.createStringLiteralAlreadyEscaped(nodeText.substring(prefixLength)); + final PyStringLiteralExpression replacement = + elementGenerator.createStringLiteralAlreadyEscaped(nodeText.substring(prefixLength)); node.getPsi().replace(replacement.getFirstChild()); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemoveUnnecessaryBackslashQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemoveUnnecessaryBackslashQuickFix.java index 906b80088c33..8f2db98a31dd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemoveUnnecessaryBackslashQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/RemoveUnnecessaryBackslashQuickFix.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.NotNull; /** * User: catherine - * + *

* QuickFix to remove all unnecessary backslashes in expression */ public class RemoveUnnecessaryBackslashQuickFix extends PsiUpdateModCommandQuickFix { @@ -26,17 +26,19 @@ public class RemoveUnnecessaryBackslashQuickFix extends PsiUpdateModCommandQuick @Override public void applyFix(@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { - PsiElement parent = PsiTreeUtil.getParentOfType(element, PyEditorHandlerConfig.IMPLICIT_WRAP_CLASSES); - removeBackSlash(parent); + PsiElement parent = PsiTreeUtil.getParentOfType(element, PyEditorHandlerConfig.IMPLICIT_WRAP_CLASSES); + removeBackSlash(parent); } public static void removeBackSlash(PsiElement parent) { if (parent != null) { Stack stack = new Stack<>(); - if (parent instanceof PyParenthesizedExpression) + if (parent instanceof PyParenthesizedExpression) { stack.push(((PyParenthesizedExpression)parent).getContainedExpression()); - else + } + else { stack.push(parent); + } while (!stack.isEmpty()) { PsiElement el = stack.pop(); PsiWhiteSpace[] children = PsiTreeUtil.getChildrenOfType(el, PsiWhiteSpace.class); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceExceptPartQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceExceptPartQuickFix.java index ccfc6929a4b4..07bfaff09ad9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceExceptPartQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceExceptPartQuickFix.java @@ -45,11 +45,11 @@ public class ReplaceExceptPartQuickFix extends PsiUpdateModCommandQuickFix { } assert element != null; PyTryExceptStatement newElement = - elementGenerator.createFromText(LanguageLevel.forElement(exceptPart), PyTryExceptStatement.class, "try: pass except a as b: pass"); + elementGenerator.createFromText(LanguageLevel.forElement(exceptPart), PyTryExceptStatement.class, + "try: pass except a as b: pass"); ASTNode node = newElement.getExceptParts()[0].getNode().findChildByType(PyTokenTypes.AS_KEYWORD); assert node != null; element.replace(node.getPsi()); } } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceFunctionWithSetLiteralQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceFunctionWithSetLiteralQuickFix.java index 8933a66b46ab..96445521045c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceFunctionWithSetLiteralQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceFunctionWithSetLiteralQuickFix.java @@ -43,11 +43,12 @@ public class ReplaceFunctionWithSetLiteralQuickFix extends PsiUpdateModCommandQu for (int i = 0; i != elements.length; ++i) { PyElement e = elements[i]; str.append(e.getText()); - if (i != elements.length-1) + if (i != elements.length - 1) { str.append(", "); + } } str.append("}"); element.replace(elementGenerator.createFromText(LanguageLevel.forElement(element), PyExpressionStatement.class, - str.toString()).getExpression()); + str.toString()).getExpression()); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceNotEqOperatorQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceNotEqOperatorQuickFix.java index 5c95f9f0aa8b..5c9847a4f032 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceNotEqOperatorQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceNotEqOperatorQuickFix.java @@ -26,7 +26,7 @@ import com.jetbrains.python.psi.PyBinaryExpression; import com.jetbrains.python.psi.PyElementGenerator; import org.jetbrains.annotations.NotNull; -public class ReplaceNotEqOperatorQuickFix extends PsiUpdateModCommandQuickFix { +public class ReplaceNotEqOperatorQuickFix extends PsiUpdateModCommandQuickFix { @Override public @NotNull String getFamilyName() { return PyPsiBundle.message("INTN.replace.noteq.operator"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceRaiseStatementQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceRaiseStatementQuickFix.java index ea92df6de76b..f6ed501332d6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceRaiseStatementQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/ReplaceRaiseStatementQuickFix.java @@ -39,10 +39,16 @@ public class ReplaceRaiseStatementQuickFix extends PsiUpdateModCommandQuickFix { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); String newExpressionText = expressions[0].getText() + "(" + expressions[1].getText() + ")"; if (expressions.length == 2) { - element.replace(elementGenerator.createFromText(LanguageLevel.forElement(element), PyRaiseStatement.class, "raise " + newExpressionText)); - } else if (expressions.length == 3) { + element.replace( + elementGenerator.createFromText(LanguageLevel.forElement(element), PyRaiseStatement.class, "raise " + newExpressionText)); + } + else if (expressions.length == 3) { element.replace(elementGenerator.createFromText(LanguageLevel.forElement(element), PyRaiseStatement.class, - "raise " + newExpressionText + ".with_traceback(" + expressions[2].getText() + ")")); + "raise " + + newExpressionText + + ".with_traceback(" + + expressions[2].getText() + + ")")); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/SimplifyBooleanCheckQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/SimplifyBooleanCheckQuickFix.java index aff2316f73f3..e31dfcdf6d12 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/SimplifyBooleanCheckQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/SimplifyBooleanCheckQuickFix.java @@ -67,7 +67,8 @@ public class SimplifyBooleanCheckQuickFix extends PsiUpdateModCommandQuickFix { || isEmpty(rightExpression) || isEmpty(leftExpression); if (isTrue(leftExpression) || isFalse(leftExpression) || isNull(leftExpression) || isEmpty(leftExpression)) { resultExpression = rightExpression; - } else { + } + else { resultExpression = leftExpression; } return ((positiveCondition) ? "" : "not ") + resultExpression.getText(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectFunctionCallQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectFunctionCallQuickFix.java index c9b967d58000..7a4af2188dbd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectFunctionCallQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectFunctionCallQuickFix.java @@ -17,7 +17,7 @@ import org.jetbrains.annotations.Nullable; /** * User: catherine - * + *

* QuickFix to replace statement that has no effect with function call */ public class StatementEffectFunctionCallQuickFix extends PsiUpdateModCommandQuickFix { @@ -30,13 +30,16 @@ public class StatementEffectFunctionCallQuickFix extends PsiUpdateModCommandQuic public void applyFix(@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { if (element instanceof PyReferenceExpression) { final String expressionText = element.getText(); - if (PyNames.PRINT.equals(expressionText)) + if (PyNames.PRINT.equals(expressionText)) { replacePrint(element); - else if (PyNames.EXEC.equals(expressionText)) + } + else if (PyNames.EXEC.equals(expressionText)) { replaceExec(element); - else + } + else { element.replace(PyElementGenerator.getInstance(project).createCallExpression(LanguageLevel.forElement(element), - expressionText)); + expressionText)); + } } } @@ -105,8 +108,9 @@ public class StatementEffectFunctionCallQuickFix extends PsiUpdateModCommandQuic stringBuilder.append(binaryExpression.getLeftExpression().getText()); stringBuilder.append(", "); final PyExpression rightExpression = binaryExpression.getRightExpression(); - if (rightExpression != null) + if (rightExpression != null) { stringBuilder.append(rightExpression.getText()); + } } private static void replacePrint(final @NotNull PsiElement expression) { @@ -142,8 +146,9 @@ public class StatementEffectFunctionCallQuickFix extends PsiUpdateModCommandQuic } } } - else + else { next = whiteSpace; + } RemoveUnnecessaryBackslashQuickFix.removeBackSlash(next); if (whiteSpace != null) whiteSpace.delete(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectIntroduceVariableQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectIntroduceVariableQuickFix.java index c24fb2db18b8..ae2c559b6f15 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectIntroduceVariableQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/StatementEffectIntroduceVariableQuickFix.java @@ -15,7 +15,7 @@ import org.jetbrains.annotations.NotNull; /** * User: catherine - * + *

* Quickfix to introduce variable if statement seems to have no effect */ public class StatementEffectIntroduceVariableQuickFix extends PsiUpdateModCommandQuickFix { @@ -37,5 +37,5 @@ public class StatementEffectIntroduceVariableQuickFix extends PsiUpdateModComman final PyExpression leftHandSideExpression = ((PyAssignmentStatement)element).getLeftHandSideExpression(); assert leftHandSideExpression != null; updater.templateBuilder().field(leftHandSideExpression, "var"); - } + } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/TransformClassicClassQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/TransformClassicClassQuickFix.java index 2c8a791cf710..0b2453c5120c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/TransformClassicClassQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/TransformClassicClassQuickFix.java @@ -24,17 +24,18 @@ public class TransformClassicClassQuickFix extends PsiUpdateModCommandQuickFix { public void applyFix(@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { element = PsiTreeUtil.getParentOfType(element, PyClass.class); if (element != null) { - PyClass pyClass = (PyClass) element; + PyClass pyClass = (PyClass)element; PyExpression[] superClassExpressions = pyClass.getSuperClassExpressions(); PyElementGenerator generator = PyElementGenerator.getInstance(project); if (superClassExpressions.length == 0) { pyClass.replace(generator.createFromText(LanguageLevel.getDefault(), PyClass.class, "class " + pyClass.getName() + "(" + PyNames.OBJECT + "):\n " + pyClass.getStatementList().getText())); - } else { + } + else { StringBuilder stringBuilder = new StringBuilder("class "); stringBuilder.append(pyClass.getName()).append("("); - for (PyExpression expression: superClassExpressions) { + for (PyExpression expression : superClassExpressions) { stringBuilder.append(expression.getText()).append(", "); } stringBuilder.append(PyNames.OBJECT).append(":\n "); diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/UnresolvedReferenceAddParameterQuickFix.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/UnresolvedReferenceAddParameterQuickFix.java index a7a555208cf1..df5a6e13e228 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/UnresolvedReferenceAddParameterQuickFix.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/quickfix/UnresolvedReferenceAddParameterQuickFix.java @@ -20,11 +20,12 @@ import org.jetbrains.annotations.NotNull; /** * User: ktisha - * + *

* QuickFix to add parameter to unresolved reference */ public class UnresolvedReferenceAddParameterQuickFix implements LocalQuickFix { private final String myName; + public UnresolvedReferenceAddParameterQuickFix(String name) { myName = name; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesVisitor.java index e5564b956d8b..efc5feba464d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesVisitor.java @@ -137,8 +137,8 @@ public abstract class PyUnresolvedReferencesVisitor extends PyInspectionVisitor boolean ignoreUnresolved = ignoreUnresolved(node, reference) || !evaluateVersionsForElement(node).contains(myVersion); if (!ignoreUnresolved) { HighlightSeverity severity = reference instanceof PsiReferenceEx - ? ((PsiReferenceEx)reference).getUnresolvedHighlightSeverity(myTypeEvalContext) - : HighlightSeverity.ERROR; + ? ((PsiReferenceEx)reference).getUnresolvedHighlightSeverity(myTypeEvalContext) + : HighlightSeverity.ERROR; if (severity == null) { if (isAwaitCallToImportedNonAsyncFunction(reference)) { // special case: type of prefixExpression.getQualifier() is null but we want to check whether the called function is async @@ -166,7 +166,8 @@ public abstract class PyUnresolvedReferencesVisitor extends PyInspectionVisitor String unionMemberRender = PythonDocumentationProvider.getTypeName(unionMemberMissingAttr, myTypeEvalContext); registerProblem( node, - PyPsiBundle.message("INSP.unresolved.refs.unresolved.attribute.in.union.type", unionMemberRender, unionTypeRender, referencedName), + PyPsiBundle.message("INSP.unresolved.refs.unresolved.attribute.in.union.type", unionMemberRender, unionTypeRender, + referencedName), ProblemHighlightType.WEAK_WARNING, null, reference.getRangeInElement() diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspection.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspection.java index b52d32fa57e9..9a98c6138a5a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspection.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspection.java @@ -24,12 +24,15 @@ public final class PyUnusedLocalInspection extends PyInspection { public boolean ignoreVariablesStartingWithUnderscore = true; @Override - public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly, @NotNull LocalInspectionToolSession session) { + public @NotNull PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, + boolean isOnTheFly, + @NotNull LocalInspectionToolSession session) { final PyUnusedLocalInspectionVisitor visitor = new PyUnusedLocalInspectionVisitor(holder, ignoreTupleUnpacking, ignoreLambdaParameters, ignoreLoopIterationVariables, - ignoreVariablesStartingWithUnderscore, PyInspectionVisitor.getContext(session)); + ignoreVariablesStartingWithUnderscore, + PyInspectionVisitor.getContext(session)); // buildVisitor() will be called on injected files in the same session - don't overwrite if we already have one final PyUnusedLocalInspectionVisitor existingVisitor = session.getUserData(KEY); if (existingVisitor == null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspectionVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspectionVisitor.java index 370ff0173931..bb3f3918b950 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspectionVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/inspections/unusedLocal/PyUnusedLocalInspectionVisitor.java @@ -213,7 +213,7 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { allPathsScopeReads.addAll(analyzeReadsInDoctests(docstring, owner)); } } - + final Instruction[] instructions = ControlFlowCache.getControlFlow(owner).getInstructions(); for (int i = 0; i < instructions.length; i++) { final Instruction instruction = instructions[i]; @@ -239,7 +239,8 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { else { startInstruction = i; } - allPathsScopeReads.addAll(analyzeReadsInScope(name, owner, instructions, startInstruction, PyUtil.as(element, PyReferenceExpression.class))); + allPathsScopeReads.addAll( + analyzeReadsInScope(name, owner, instructions, startInstruction, PyUtil.as(element, PyReferenceExpression.class))); } } myScopeReads.put(owner, Collections.unmodifiableSet(allPathsScopeReads)); @@ -293,15 +294,16 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { return readsFromInstruction; } - static class DontPerformException extends RuntimeException {} + static class DontPerformException extends RuntimeException { + } private static boolean callsLocals(final ScopeOwner owner) { try { - owner.acceptChildren(new PyRecursiveElementVisitor(){ + owner.acceptChildren(new PyRecursiveElementVisitor() { @Override public void visitPyCallExpression(final @NotNull PyCallExpression node) { final PyExpression callee = node.getCallee(); - if (callee != null && "locals".equals(callee.getName())){ + if (callee != null && "locals".equals(callee.getName())) { throw new DontPerformException(); } node.acceptChildren(this); // look at call expr in arguments @@ -369,8 +371,8 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { String name = element instanceof PsiNamedElement namedElement ? StringUtil.notNullize(namedElement.getName()) : element.getText(); if (element instanceof PyNamedParameter || element.getParent() instanceof PyNamedParameter) { PyNamedParameter namedParameter = element instanceof PyNamedParameter - ? (PyNamedParameter) element - : (PyNamedParameter) element.getParent(); + ? (PyNamedParameter)element + : (PyNamedParameter)element.getParent(); name = namedParameter.getName(); // When function is inside a class, first parameter may be either self or cls which is always 'used'. if (namedParameter.isSelf()) { @@ -405,7 +407,7 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { } } boolean canRemove = !(PsiTreeUtil.getPrevSiblingOfType(element, PyParameter.class) instanceof PySingleStarParameter) || - PsiTreeUtil.getNextSiblingOfType(element, PyParameter.class) != null; + PsiTreeUtil.getNextSiblingOfType(element, PyParameter.class) != null; final List fixes = new ArrayList<>(); if (mayBeField) { @@ -414,7 +416,8 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { if (canRemove) { fixes.add(new PyRemoveParameterQuickFix()); } - registerWarning(element, PyPsiBundle.message("INSP.unused.locals.parameter.isnot.used", name), fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); + registerWarning(element, PyPsiBundle.message("INSP.unused.locals.parameter.isnot.used", name), + fixes.toArray(LocalQuickFix.EMPTY_ARRAY)); } else { if (myIgnoreVariablesStartingWithUnderscore && element.getText().startsWith(PyNames.UNDERSCORE)) continue; @@ -521,14 +524,14 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { } // Handling of the star expressions PsiElement parent = element.getParent(); - if (parent instanceof PyStarExpression){ + if (parent instanceof PyStarExpression) { element = parent; parent = element.getParent(); } if (parent instanceof PyTupleExpression tuple) { // if all the items of the tuple are unused, we still highlight all of them; if some are unused, we ignore for (PyExpression expression : tuple.getElements()) { - if (expression instanceof PyStarExpression){ + if (expression instanceof PyStarExpression) { if (!unusedElements.contains(((PyStarExpression)expression).getExpression())) { return true; } @@ -541,7 +544,7 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { return false; } - private void registerWarning(@NotNull PsiElement element, @InspectionMessage String msg, @NotNull LocalQuickFix @NotNull... quickfixes) { + private void registerWarning(@NotNull PsiElement element, @InspectionMessage String msg, @NotNull LocalQuickFix @NotNull ... quickfixes) { registerProblem(element, msg, ProblemHighlightType.LIKE_UNUSED_SYMBOL, null, quickfixes); } @@ -553,8 +556,8 @@ public final class PyUnusedLocalInspectionVisitor extends PyInspectionVisitor { @Override public void applyFix(@NotNull Project project, @NotNull PsiElement element, @NotNull ModPsiUpdater updater) { - final PyFile pyFile = (PyFile) PyElementGenerator.getInstance(element.getProject()).createDummyFile(LanguageLevel.getDefault(), - "for _ in tuples:\n pass" + final PyFile pyFile = (PyFile)PyElementGenerator.getInstance(element.getProject()).createDummyFile(LanguageLevel.getDefault(), + "for _ in tuples:\n pass" ); final PyExpression target = ((PyForStatement)pyFile.getStatements().get(0)).getForPart().getTarget(); if (target != null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/magicLiteral/PyMagicLiteralTools.java b/python/python-psi-impl/src/com/jetbrains/python/magicLiteral/PyMagicLiteralTools.java index d9ca050cdc84..1d101606e9bb 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/magicLiteral/PyMagicLiteralTools.java +++ b/python/python-psi-impl/src/com/jetbrains/python/magicLiteral/PyMagicLiteralTools.java @@ -30,7 +30,7 @@ public final class PyMagicLiteralTools { */ public static boolean couldBeMagicLiteral(final @NotNull PsiElement element) { return (element instanceof StringLiteralExpression) && (element.getReferences().length == 0) && - Arrays.stream(PyMagicLiteralExtensionPoint.EP_NAME.getExtensions()).anyMatch(o-> o.isEnabled(element)); + Arrays.stream(PyMagicLiteralExtensionPoint.EP_NAME.getExtensions()).anyMatch(o -> o.isEnabled(element)); } /** diff --git a/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyClassMembersProvider.java b/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyClassMembersProvider.java index 9f03c74c0ff0..20a5e353e65c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyClassMembersProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyClassMembersProvider.java @@ -37,5 +37,4 @@ public final class NumpyClassMembersProvider extends PyClassMembersProviderBase } return Collections.emptyList(); } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyDocStringTypeProvider.java b/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyDocStringTypeProvider.java index 69cc32fe6223..f1bd2a88116a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyDocStringTypeProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/numpy/codeInsight/NumpyDocStringTypeProvider.java @@ -34,7 +34,10 @@ import com.jetbrains.python.documentation.docstrings.SectionBasedDocString.Secti import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyBuiltinCache; import com.jetbrains.python.psi.resolve.PyResolveImportUtil; -import com.jetbrains.python.psi.types.*; +import com.jetbrains.python.psi.types.PyClassTypeImpl; +import com.jetbrains.python.psi.types.PyType; +import com.jetbrains.python.psi.types.PyTypeProviderBase; +import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.toolbox.Substring; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -96,7 +99,9 @@ public final class NumpyDocStringTypeProvider extends PyTypeProviderBase { NUMPY_ALIAS_TO_REAL_TYPE.put("non-zero int", "int"); } - private static @Nullable NumpyDocString forFunction(@NotNull PyFunction function, @Nullable PsiElement reference, @Nullable String knownSignature) { + private static @Nullable NumpyDocString forFunction(@NotNull PyFunction function, + @Nullable PsiElement reference, + @Nullable String knownSignature) { String docString = function.getDocStringValue(); if (docString == null) { // Docstring for constructor can be found in the docstring of class @@ -193,7 +198,9 @@ public final class NumpyDocStringTypeProvider extends PyTypeProviderBase { } @Override - public @Nullable Ref getCallType(@NotNull PyFunction function, @NotNull PyCallSiteExpression callSite, @NotNull TypeEvalContext context) { + public @Nullable Ref getCallType(@NotNull PyFunction function, + @NotNull PyCallSiteExpression callSite, + @NotNull TypeEvalContext context) { if (isApplicable(function)) { final PyExpression callee = callSite instanceof PyCallExpression ? ((PyCallExpression)callSite).getCallee() : null; final NumpyDocString docString = forFunction(function, callee); @@ -250,7 +257,9 @@ public final class NumpyDocStringTypeProvider extends PyTypeProviderBase { } @Override - public @Nullable Ref getParameterType(@NotNull PyNamedParameter parameter, @NotNull PyFunction function, @NotNull TypeEvalContext context) { + public @Nullable Ref getParameterType(@NotNull PyNamedParameter parameter, + @NotNull PyFunction function, + @NotNull TypeEvalContext context) { if (isApplicable(function)) { final String name = parameter.getName(); if (name != null) { @@ -279,7 +288,7 @@ public final class NumpyDocStringTypeProvider extends PyTypeProviderBase { private static boolean isApplicable(@NotNull PsiElement element) { final Module module = ModuleUtilCore.findModuleForPsiElement(element); - if (module != null){ + if (module != null) { if (PyDocumentationSettings.getInstance(module).isNumpyFormat(element.getContainingFile())) { return true; } @@ -382,7 +391,8 @@ public final class NumpyDocStringTypeProvider extends PyTypeProviderBase { } if (paramType != null) { if (isUfuncType(function, paramType)) { - return getPsiFacade(function).parseTypeAnnotation("numbers.Number or numpy.core.multiarray.ndarray or collections.abc.Iterable", function); + return getPsiFacade(function).parseTypeAnnotation("numbers.Number or numpy.core.multiarray.ndarray or collections.abc.Iterable", + function); } final PyType numpyDocType = parseNumpyDocType(function, paramType); if ("size".equals(parameterName)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/packaging/PyPackageVersion.kt b/python/python-psi-impl/src/com/jetbrains/python/packaging/PyPackageVersion.kt index 7cf4cbd858e5..4b9734792500 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/packaging/PyPackageVersion.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/packaging/PyPackageVersion.kt @@ -6,12 +6,14 @@ package com.jetbrains.python.packaging * * Instances of this class MUST be obtained from [PyPackageVersionNormalizer.normalize]. */ -data class PyPackageVersion internal constructor(val epoch: String? = null, - val release: String, - val pre: String? = null, - val post: String? = null, - val dev: String? = null, - val local: String? = null) { +data class PyPackageVersion internal constructor( + val epoch: String? = null, + val release: String, + val pre: String? = null, + val post: String? = null, + val dev: String? = null, + val local: String? = null, +) { /** * String representation that follows spelling described in [PEP-440][https://www.python.org/dev/peps/pep-0440/#normalization] diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecorator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecorator.java index f5e7ee869345..25d0063930f4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecorator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecorator.java @@ -25,7 +25,11 @@ public class PyKnownDecorator { myIsStaticMethod = false; } - private PyKnownDecorator(@NotNull String qualifiedName, boolean isProperty, boolean isMutableProperty, boolean isGeneratorBasedCoroutine, boolean isAbstract, + private PyKnownDecorator(@NotNull String qualifiedName, + boolean isProperty, + boolean isMutableProperty, + boolean isGeneratorBasedCoroutine, + boolean isAbstract, boolean isClassMethod, boolean isStaticMethod) { myQualifiedName = QualifiedName.fromDottedString(qualifiedName); @@ -81,7 +85,8 @@ public class PyKnownDecorator { } public @NotNull PyKnownDecorator build() { - return new PyKnownDecorator(qualifiedName, isProperty, isMutableProperty, isGeneratorBasedCoroutine, isAbstract, isClassMethod, isStaticMethod); + return new PyKnownDecorator(qualifiedName, isProperty, isMutableProperty, isGeneratorBasedCoroutine, isAbstract, isClassMethod, + isStaticMethod); } } @@ -102,16 +107,23 @@ public class PyKnownDecorator { public final static PyKnownDecorator FUNCTOOLS_WRAPS = new PyKnownDecorator("functools.wraps"); public final static PyKnownDecorator FUNCTOOLS_TOTAL_ORDERING = new PyKnownDecorator("functools.total_ordering"); public final static PyKnownDecorator FUNCTOOLS_SINGLEDISPATCH = new PyKnownDecorator("functools.singledispatch"); - public final static PyKnownDecorator FUNCTOOLS_CACHED_PROPERTY = new PyKnownDecorator.Builder("functools.cached_property").setProperty().setMutableProperty().build(); + public final static PyKnownDecorator FUNCTOOLS_CACHED_PROPERTY = + new PyKnownDecorator.Builder("functools.cached_property").setProperty().setMutableProperty().build(); public final static PyKnownDecorator ABC_ABSTRACTMETHOD = new PyKnownDecorator.Builder("abc.abstractmethod").setAbstract().build(); - public final static PyKnownDecorator ABC_ABSTRACTCLASSMETHOD = new PyKnownDecorator.Builder("abc.abstractclassmethod").setAbstract().setClassMethod().build(); - public final static PyKnownDecorator ABC_ABSTRACTSTATICMETHOD = new PyKnownDecorator.Builder("abc.abstractstaticmethod").setAbstract().setStaticMethod().build(); - public final static PyKnownDecorator ABC_ABSTRACTPROPERTY = new PyKnownDecorator.Builder("abc.abstractproperty").setAbstract().setProperty().build(); + public final static PyKnownDecorator ABC_ABSTRACTCLASSMETHOD = + new PyKnownDecorator.Builder("abc.abstractclassmethod").setAbstract().setClassMethod().build(); + public final static PyKnownDecorator ABC_ABSTRACTSTATICMETHOD = + new PyKnownDecorator.Builder("abc.abstractstaticmethod").setAbstract().setStaticMethod().build(); + public final static PyKnownDecorator ABC_ABSTRACTPROPERTY = + new PyKnownDecorator.Builder("abc.abstractproperty").setAbstract().setProperty().build(); - public final static PyKnownDecorator ASYNCIO_TASKS_COROUTINE = new PyKnownDecorator.Builder("asyncio.tasks.coroutine").setGeneratorBasedCoroutine().build(); - public final static PyKnownDecorator ASYNCIO_COROUTINES_COROUTINE = new PyKnownDecorator.Builder("asyncio.coroutines.coroutine").setGeneratorBasedCoroutine().build(); - public final static PyKnownDecorator TYPES_COROUTINE = new PyKnownDecorator.Builder("types.coroutine").setGeneratorBasedCoroutine().build(); + public final static PyKnownDecorator ASYNCIO_TASKS_COROUTINE = + new PyKnownDecorator.Builder("asyncio.tasks.coroutine").setGeneratorBasedCoroutine().build(); + public final static PyKnownDecorator ASYNCIO_COROUTINES_COROUTINE = + new PyKnownDecorator.Builder("asyncio.coroutines.coroutine").setGeneratorBasedCoroutine().build(); + public final static PyKnownDecorator TYPES_COROUTINE = + new PyKnownDecorator.Builder("types.coroutine").setGeneratorBasedCoroutine().build(); public final static PyKnownDecorator UNITTEST_SKIP = new PyKnownDecorator("unittest.case.skip"); public final static PyKnownDecorator UNITTEST_SKIP_IF = new PyKnownDecorator("unittest.case.skipIf"); @@ -138,8 +150,10 @@ public class PyKnownDecorator { public final static PyKnownDecorator REPRLIB_RECURSIVE_REPR = new PyKnownDecorator("reprlib.recursive_repr"); - public final static PyKnownDecorator PYRAMID_DECORATOR_REIFY = new PyKnownDecorator.Builder("pyramid.decorator.reify").setProperty().build(); - public final static PyKnownDecorator KOMBU_UTILS_CACHED_PROPERTY = new PyKnownDecorator.Builder("kombu.utils.cached_property").setProperty().setMutableProperty().build(); + public final static PyKnownDecorator PYRAMID_DECORATOR_REIFY = + new PyKnownDecorator.Builder("pyramid.decorator.reify").setProperty().build(); + public final static PyKnownDecorator KOMBU_UTILS_CACHED_PROPERTY = + new PyKnownDecorator.Builder("kombu.utils.cached_property").setProperty().setMutableProperty().build(); public final static PyKnownDecorator DATACLASSES_DATACLASS = new PyKnownDecorator("dataclasses.dataclass"); public final static PyKnownDecorator ATTR_S = new PyKnownDecorator("attr.s"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecoratorProvider.java b/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecoratorProvider.java index fcd1cbfb9851..62d95a6433e4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecoratorProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/PyKnownDecoratorProvider.java @@ -20,7 +20,8 @@ public interface PyKnownDecoratorProvider { * @deprecated Use {@link #getKnownDecorators()} instead to provide a new {@link PyKnownDecorator} using {@link PyKnownDecorator.Builder} */ @Deprecated(forRemoval = true) - @Nullable default String toKnownDecorator(String decoratorName) { + @Nullable + default String toKnownDecorator(String decoratorName) { return null; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/PyUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/PyUtil.java index 92f0221f9b67..3924373d8eee 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/PyUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/PyUtil.java @@ -65,7 +65,7 @@ import static com.jetbrains.python.ast.PyAstFunction.Modifier.STATICMETHOD; /** * Assorted utility methods for Python code insight. - * + *

* These methods don't depend on the Python runtime. * * @see PyPsiUtils for utilities used in Python PSI API @@ -421,7 +421,8 @@ public final class PyUtil { // Note that returned list may contain null items, e.g. for unresolved import elements, originally wrapped // in `com.jetbrains.python.psi.resolve.ImportedResolveResult` // TODO: it would be a good idea to revise `filterTopPriority` to return the import definer when the element is null - public static @NotNull List<@Nullable PsiElement> multiResolveTopPriority(@NotNull PsiElement element, @NotNull PyResolveContext resolveContext) { + public static @NotNull List<@Nullable PsiElement> multiResolveTopPriority(@NotNull PsiElement element, + @NotNull PyResolveContext resolveContext) { if (element instanceof PyReferenceOwner referenceOwner) { return multiResolveTopPriority(referenceOwner.getReference(resolveContext)); } @@ -555,7 +556,9 @@ public final class PyUtil { * @param value type * @param

key type */ - public static @NotNull T getParameterizedCachedValue(@NotNull PsiElement element, @Nullable P param, @NotNull Function f) { + public static @NotNull T getParameterizedCachedValue(@NotNull PsiElement element, + @Nullable P param, + @NotNull Function f) { final T result = getNullableParameterizedCachedValue(element, param, f); assert result != null; return result; @@ -565,8 +568,8 @@ public final class PyUtil { * Same as {@link #getParameterizedCachedValue(PsiElement, Object, Function)} but allows nulls. */ public static @Nullable T getNullableParameterizedCachedValue(@NotNull PsiElement element, - @Nullable P param, - @NotNull Function f) { + @Nullable P param, + @NotNull Function f) { final CachedValuesManager manager = CachedValuesManager.getManager(element.getProject()); final Map, Optional> cache = CachedValuesManager.getCachedValue(element, manager.getKeyForClass(f.getClass()), () -> { // concurrent hash map is a null-hostile collection @@ -639,7 +642,8 @@ public final class PyUtil { PyUtilCore.updateDocumentUnblockedAndCommitted(anchor, consumer); } - public static @Nullable T updateDocumentUnblockedAndCommitted(@NotNull PsiElement anchor, @NotNull Function func) { + public static @Nullable T updateDocumentUnblockedAndCommitted(@NotNull PsiElement anchor, + @NotNull Function func) { return PyUtilCore.updateDocumentUnblockedAndCommitted(anchor, func); } @@ -912,11 +916,13 @@ public final class PyUtil { /** * Constructs new lookup element for completion of keyword argument with equals sign appended. * - * @param name name of the parameter + * @param name name of the parameter * @param settingsAnchor file to check code style settings and surround equals sign with spaces if necessary * @return lookup element */ - public static @NotNull LookupElement createNamedParameterLookup(@NotNull String name, @NotNull PsiFile settingsAnchor, boolean addEquals) { + public static @NotNull LookupElement createNamedParameterLookup(@NotNull String name, + @NotNull PsiFile settingsAnchor, + boolean addEquals) { final String suffix; if (addEquals) { if (PythonCodeStyleService.getInstance().isSpaceAroundEqInKeywordArgument(settingsAnchor)) { @@ -925,7 +931,8 @@ public final class PyUtil { else { suffix = "="; } - } else { + } + else { suffix = ""; } LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(name + suffix).withIcon( @@ -1248,7 +1255,9 @@ public final class PyUtil { return false; } - public static @Nullable PsiElement findPrevAtOffset(PsiFile psiFile, int caretOffset, @NotNull Class @NotNull ... toSkip) { + public static @Nullable PsiElement findPrevAtOffset(PsiFile psiFile, + int caretOffset, + @NotNull Class @NotNull ... toSkip) { return PyUtilCore.findPrevAtOffset(psiFile, caretOffset, toSkip); } @@ -1264,7 +1273,9 @@ public final class PyUtil { return element; } - public static @Nullable PsiElement findNextAtOffset(final @NotNull PsiFile psiFile, int caretOffset, @NotNull Class @NotNull ... toSkip) { + public static @Nullable PsiElement findNextAtOffset(final @NotNull PsiFile psiFile, + int caretOffset, + @NotNull Class @NotNull ... toSkip) { return PyUtilCore.findNextAtOffset(psiFile, caretOffset, toSkip); } @@ -1700,7 +1711,7 @@ public final class PyUtil { } public static final class IterHelper { // TODO: rename sanely - private IterHelper() {} + private IterHelper() { } public static @Nullable PsiNamedElement findName(Iterable it, String name) { PsiNamedElement ret = null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ParamHelper.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ParamHelper.java index 2fbb07650037..849ced8c77e6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ParamHelper.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ParamHelper.java @@ -42,6 +42,7 @@ public final class ParamHelper { /** * Runs a {@link ParamWalker ParamWalker} down the array of parameters, recursively descending into tuple parameters. * If the array is from PyParamaterList.getParameters(), parameters are visited in the order of textual appearance + * * @param params where to walk * @param walker the walker with callbacks. */ @@ -135,7 +136,9 @@ public final class ParamHelper { public static @NotNull String getNameInSignature(@NotNull PyCallableParameter parameter) { final StringBuilder sb = new StringBuilder(); - if (parameter.isPositionalContainer()) sb.append("*"); + if (parameter.isPositionalContainer()) { + sb.append("*"); + } else if (parameter.isKeywordContainer()) sb.append("**"); final String name = parameter.getName(); @@ -178,25 +181,28 @@ public final class ParamHelper { public interface ParamWalker { /** * Is called when a tuple parameter is encountered, before visiting any parameters nested in it. + * * @param param the parameter * @param first true iff it is the first in the list - * @param last true it is the last in the list + * @param last true it is the last in the list */ void enterTupleParameter(PyTupleParameter param, boolean first, boolean last); /** * Is called when all nested parameters of a given tuple parameter are visited. + * * @param param the parameter * @param first true iff it is the first in the list - * @param last true it is the last in the list + * @param last true it is the last in the list */ void leaveTupleParameter(PyTupleParameter param, boolean first, boolean last); /** * Is called when a named parameter is encountered. + * * @param param the parameter * @param first true iff it is the first in the list - * @param last true it is the last in the list + * @param last true it is the last in the list */ void visitNamedParameter(PyNamedParameter param, boolean first, boolean last); @@ -241,5 +247,4 @@ public final class ParamHelper { ); return result; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PropertyBunch.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PropertyBunch.java index 952c01967b14..61791d09e06b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PropertyBunch.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PropertyBunch.java @@ -85,6 +85,7 @@ public abstract class PropertyBunch { /** * Tries to form a bunch from data available at a possible property() call site. + * * @param source should be a PyCallExpression (if not, null is immediately returned). * @param target what to fill with data (return type contravariance prevents us from creating it inside). * @return true if target was successfully filled. @@ -97,8 +98,8 @@ public abstract class PropertyBunch { PyExpression[] accessors = new PyExpression[3]; String doc = null; int position = 0; - String[] keywords = new String[] { "fget", "fset", "fdel", "doc" }; - for (PyExpression arg: arglist.getArguments()) { + String[] keywords = new String[]{"fget", "fset", "fdel", "doc"}; + for (PyExpression arg : arglist.getArguments()) { int index = -1; if (arg instanceof PyKeywordArgument) { String keyword = ((PyKeywordArgument)arg).getKeyword(); @@ -116,7 +117,7 @@ public abstract class PropertyBunch { if (index >= 0) { arg = PyUtil.peelArgument(arg); if (index < 3) { - accessors [index] = arg; + accessors[index] = arg; } else if (index == 3 && arg instanceof PyStringLiteralExpression) { doc = ((PyStringLiteralExpression)arg).getStringValue(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAnyExpressionEvaluator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAnyExpressionEvaluator.java index 07185f0000e9..218b8c9b0c9d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAnyExpressionEvaluator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAnyExpressionEvaluator.java @@ -67,9 +67,10 @@ public class PyAnyExpressionEvaluator extends PyEvaluator { /** * Evaluates expression to single element + * * @param expression exp to eval - * @param aClass expected class - * @param expected class + * @param aClass expected class + * @param expected class * @return instance of aClass, or null if failed to eval */ public static @Nullable T evaluateOne(final @NotNull PyExpression expression, final @NotNull Class aClass) { @@ -89,6 +90,7 @@ public class PyAnyExpressionEvaluator extends PyEvaluator { /** * Evaluates expression to string + * * @param expression exp to eval * @return string, or null if failed to eval */ @@ -98,12 +100,13 @@ public class PyAnyExpressionEvaluator extends PyEvaluator { /** * Evaluates expression as list of values + * * @param expression exp to eval - * @param aClass expected element class - * @param expected element class + * @param aClass expected element class + * @param expected element class * @return a list of elements of expected type */ - public static @NotNull List evaluateIterable(final @NotNull PyExpression expression, final @NotNull Class aClass) { + public static @NotNull List evaluateIterable(final @NotNull PyExpression expression, final @NotNull Class aClass) { final PyAnyExpressionEvaluator evaluator = new PyAnyExpressionEvaluator(true); final Object evaluate = evaluator.evaluate(expression); final T resultSingle = PyUtil.as(evaluate, aClass); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java index 74a213bbf070..d389299db444 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java @@ -241,6 +241,7 @@ public class PyArgumentListImpl extends PyElementImpl implements PyArgumentList, return (PsiTreeUtil.getParentOfType(input, PyKeywordArgument.class) == null) && !(input instanceof PyKeywordArgument); } } + @Override public @Nullable PyExpression getValueExpressionForParam(final @NotNull FunctionParameter parameter) { final String parameterName = parameter.getName(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAugAssignmentStatementNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAugAssignmentStatementNavigator.java index 4f39b81eeebb..1d6a6854ffc9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAugAssignmentStatementNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyAugAssignmentStatementNavigator.java @@ -24,9 +24,9 @@ public final class PyAugAssignmentStatementNavigator { private PyAugAssignmentStatementNavigator() { } - public static @Nullable PyAugAssignmentStatement getStatementByTarget(final PsiElement element){ + public static @Nullable PyAugAssignmentStatement getStatementByTarget(final PsiElement element) { final PyAugAssignmentStatement statement = PsiTreeUtil.getParentOfType(element, PyAugAssignmentStatement.class); - if (statement == null){ + if (statement == null) { return null; } return statement.getTarget() == element ? statement : null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyBuiltinCache.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyBuiltinCache.kt index f6edeccc1d80..7dfb4c272885 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyBuiltinCache.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyBuiltinCache.kt @@ -68,7 +68,7 @@ class PyBuiltinCache private constructor( @Suppress("KotlinUnreachableCode") fun getByName(name: @NonNls String?): PsiElement? = builtinsFile?.getElementNamed(name)?.let { return it } - ?: myExceptionsFile?.file?.getElementNamed(name) + ?: myExceptionsFile?.file?.getElementNamed(name) fun getClass(name: @NonNls String): PyClass? { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.kt index 617ca4bf9f68..cb967bcf51bc 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionHelper.kt @@ -131,9 +131,9 @@ fun PyCallExpression.multipleResolveCallee(resolveContext: PyResolveContext): Li return PyUtil.getParameterizedCachedValue( this, resolveContext) { - getExplicitResolveResults(it) + - getImplicitResolveResults(it) + - getRemoteResolveResults(it) + getExplicitResolveResults(it) + + getImplicitResolveResults(it) + + getRemoteResolveResults(it) } } @@ -613,9 +613,9 @@ private fun getSuperCallTypeForArguments(context: TypeEvalContext, firstClass: P if (secondClass.isSubclass(firstClass, context)) { val nextAfterFirstInMro = secondClass.getAncestorClasses(context) - .dropWhile { it !== firstClass } - .drop(1) - .firstOrNull() + .dropWhile { it !== firstClass } + .drop(1) + .firstOrNull() if (nextAfterFirstInMro != null) { return PyClassTypeImpl(nextAfterFirstInMro, false) @@ -913,7 +913,7 @@ private fun PyClassType.resolveMetaclassDunderCall( ?.asSequence() ?.map { it.element } ?.toSet() - ?: emptySet() + ?: emptySet() return results.filter { it.element !in typeDunderCall } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionNavigator.java index b69338106884..145a20bb0ab7 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyCallExpressionNavigator.java @@ -23,9 +23,9 @@ public final class PyCallExpressionNavigator { private PyCallExpressionNavigator() { } - public static @Nullable PyCallExpression getPyCallExpressionByCallee(final PsiElement element){ - final PsiElement parent = element.getParent(); - if (parent instanceof PyCallExpression expression){ + public static @Nullable PyCallExpression getPyCallExpressionByCallee(final PsiElement element) { + final PsiElement parent = element.getParent(); + if (parent instanceof PyCallExpression expression) { return expression.getCallee() == element ? expression : null; } return null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassImpl.java index 1a4e4fb8956c..a164b6c5c25d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassImpl.java @@ -169,7 +169,7 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla } public static boolean isSixWithMetaclassCall(@NotNull PyExpression expression) { - if (expression instanceof PyCallExpression){ + if (expression instanceof PyCallExpression) { final PyExpression callee = ((PyCallExpression)expression).getCallee(); if (callee instanceof PyReferenceExpression) { @@ -425,7 +425,8 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla private static @NotNull List mroLinearize(@NotNull PyClassLikeType type, boolean addThisType, @NotNull TypeEvalContext context, - @NotNull Map>> cache) throws MROException { + @NotNull Map>> cache) + throws MROException { final Ref> computed = cache.get(type); if (computed != null) { if (computed.isNull()) { @@ -689,8 +690,8 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla @Override public @NotNull List multiFindInitOrNew(boolean inherited, @Nullable TypeEvalContext context) { final MultiNameFinder processor = isNewStyleClass(context) - ? new MultiNameFinder<>(PyNames.INIT, PyNames.NEW) - : new MultiNameFinder<>(PyNames.INIT); + ? new MultiNameFinder<>(PyNames.INIT, PyNames.NEW) + : new MultiNameFinder<>(PyNames.INIT); visitMethods(processor, inherited, context); return processor.myResult; @@ -1046,7 +1047,9 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla } @Override - public boolean visitClassAttributes(Processor processor, boolean inherited, final @Nullable TypeEvalContext context) { + public boolean visitClassAttributes(Processor processor, + boolean inherited, + final @Nullable TypeEvalContext context) { List methods = getClassAttributes(); if (!ContainerUtil.process(methods, processor)) return false; if (inherited) { @@ -1257,7 +1260,8 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla public boolean isNewStyleClass(@Nullable TypeEvalContext context) { return NotNullLazyValue.>lazy(() -> { return CachedValuesManager.getManager(getProject()) - .createParameterizedCachedValue(param -> new Result<>(calculateNewStyleClass(param), PsiModificationTracker.MODIFICATION_COUNT), false); + .createParameterizedCachedValue(param -> new Result<>(calculateNewStyleClass(param), PsiModificationTracker.MODIFICATION_COUNT), + false); }).getValue().getValue(context); } @@ -1790,7 +1794,8 @@ public class PyClassImpl extends PyBaseElementImpl implements PyCla private static @Nullable PyClassLikeType classTypeFromQName(@NotNull QualifiedName qualifiedName, @NotNull PyFile containingFile, @NotNull TypeEvalContext context) { - final PsiElement element = ContainerUtil.getFirstItem(PyResolveUtil.resolveQualifiedNameInScope(qualifiedName, containingFile, context)); + final PsiElement element = + ContainerUtil.getFirstItem(PyResolveUtil.resolveQualifiedNameInScope(qualifiedName, containingFile, context)); if (element instanceof PyTypedElement) { final PyType type = context.getType((PyTypedElement)element); if (type instanceof PyClassLikeType) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassPatternImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassPatternImpl.java index 77c091bc4643..ecb6e3973eb9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassPatternImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyClassPatternImpl.java @@ -64,7 +64,7 @@ public class PyClassPatternImpl extends PyElementImpl implements PyClassPattern, List matchArgs = getMatchArgs(classType, context); for (int i = 0; i < arguments.size(); i++) { final var member = arguments.get(i); - if (member instanceof PyKeywordPattern keywordPattern) { + if (member instanceof PyKeywordPattern keywordPattern) { if (getMemberType(classType, keywordPattern.getKeyword(), context) == null) { return false; } @@ -90,14 +90,14 @@ public class PyClassPatternImpl extends PyElementImpl implements PyClassPattern, public @Nullable PyType getCaptureTypeForChild(@NotNull PyPattern pattern, @NotNull TypeEvalContext context) { pattern = as(PsiTreeUtil.findFirstParent(pattern, el -> this.getArgumentList() == el.getParent()), PyPattern.class); if (pattern == null) return null; - + if (pattern instanceof PyKeywordPattern keywordPattern) { if (context.getType(this) instanceof PyClassType classType) { return Ref.deref(getMemberType(classType, keywordPattern.getKeyword(), context)); } return null; } - + final List arguments = getArgumentList().getPatterns(); int index = arguments.indexOf(pattern); if (index < 0) return null; @@ -145,7 +145,7 @@ public class PyClassPatternImpl extends PyElementImpl implements PyClassPattern, if (matchArgs == null) { matchArgs = PyDataclassTypeProvider.Companion.getGeneratedMatchArgs(cls, context); } - + return matchArgs; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDecoratorListImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDecoratorListImpl.java index 3de498b8f1bc..734f8f2ed4b9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDecoratorListImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDecoratorListImpl.java @@ -10,7 +10,7 @@ import com.jetbrains.python.psi.PyElementVisitor; import com.jetbrains.python.psi.stubs.PyDecoratorListStub; import org.jetbrains.annotations.NotNull; -public class PyDecoratorListImpl extends PyBaseElementImpl implements PyDecoratorList{ +public class PyDecoratorListImpl extends PyBaseElementImpl implements PyDecoratorList { public PyDecoratorListImpl(ASTNode astNode) { super(astNode); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDeprecationUtil.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDeprecationUtil.kt index f08caaa97400..5a70f6d055b3 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDeprecationUtil.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDeprecationUtil.kt @@ -15,8 +15,9 @@ fun extractDeprecationMessageFromDecorator(element: PyAstDecoratable): String? { } val decoratorCall = deprecatedDecorator.callee as? PyReferenceExpression ?: return null if (decoratorCall.asQualifiedName()?.toString() !in deprecationDecorators) { - if (!PyResolveUtil.resolveLocally(decoratorCall).mapNotNull { it.parent as? PyFromImportStatement }. - flatMap { it.fullyQualifiedObjectNames }.any { it in deprecationDecorators }) { + if (!PyResolveUtil.resolveLocally( + decoratorCall).mapNotNull { it.parent as? PyFromImportStatement }.flatMap { it.fullyQualifiedObjectNames }.any { it in deprecationDecorators } + ) { return null } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDictCompExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDictCompExpressionImpl.java index eb062334bd15..dfbbe45efda8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDictCompExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyDictCompExpressionImpl.java @@ -26,7 +26,7 @@ public class PyDictCompExpressionImpl extends PyComprehensionElementImpl impleme if (resultExpr instanceof PyKeyValueExpression keyValue && dictionary != null) { final PyType keyType = context.getType(keyValue.getKey()); PyExpression value = keyValue.getValue(); - final PyType valueType = value != null ? context.getType(value) : null; + final PyType valueType = value != null ? context.getType(value) : null; return new PyCollectionTypeImpl(dictionary.getPyClass(), false, new SmartList<>(keyType, valueType)); } return dictionary; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElementGeneratorImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElementGeneratorImpl.java index d3de25a9d8a0..723837d431cf 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElementGeneratorImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElementGeneratorImpl.java @@ -76,9 +76,9 @@ public final class PyElementGeneratorImpl extends PyElementGenerator { @Override protected PyStringLiteralExpression createStringLiteralFromString(@Nullable PsiFile destination, - @NotNull String unescaped, - final boolean preferUTF8, - boolean preferDoubleQuotes) { + @NotNull String unescaped, + final boolean preferUTF8, + boolean preferDoubleQuotes) { boolean useDouble = (!unescaped.contains("\"") && preferDoubleQuotes) || unescaped.contains("'"); boolean useMulti = unescaped.matches(".*(\r|\n).*"); String quotes; @@ -344,7 +344,9 @@ public final class PyElementGeneratorImpl extends PyElementGenerator { } @Override - public @NotNull PyImportStatement createImportStatement(@NotNull LanguageLevel languageLevel, @NotNull String name, @Nullable String alias) { + public @NotNull PyImportStatement createImportStatement(@NotNull LanguageLevel languageLevel, + @NotNull String name, + @Nullable String alias) { final String asClause = StringUtil.isNotEmpty(alias) ? " as " + alias : ""; final String statement = "import " + name + asClause; return createFromText(languageLevel, PyImportStatement.class, statement); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElsePartImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElsePartImpl.java index d2d56428e6ae..9597d04e2dbc 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElsePartImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyElsePartImpl.java @@ -19,7 +19,7 @@ import com.intellij.lang.ASTNode; import com.jetbrains.python.psi.PyElsePart; public class PyElsePartImpl extends PyElementImpl implements PyElsePart { - + public PyElsePartImpl(ASTNode astNode) { super(astNode); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExceptPartNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExceptPartNavigator.java index cdd50fd9ad49..db7b218f433d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExceptPartNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExceptPartNavigator.java @@ -25,13 +25,13 @@ public final class PyExceptPartNavigator { private PyExceptPartNavigator() { } - public static @Nullable PyExceptPart getPyExceptPartByTarget(final PsiElement element){ + public static @Nullable PyExceptPart getPyExceptPartByTarget(final PsiElement element) { final PyExceptPart pyExceptPart = PsiTreeUtil.getParentOfType(element, PyExceptPart.class, false); - if (pyExceptPart == null){ + if (pyExceptPart == null) { return null; } final PyExpression expr = pyExceptPart.getTarget(); - if (expr != null && PsiTreeUtil.isAncestor(expr, element, false)){ + if (expr != null && PsiTreeUtil.isAncestor(expr, element, false)) { return pyExceptPart; } return null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExpressionCodeFragmentImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExpressionCodeFragmentImpl.java index 63fcd56b0029..899bfc739821 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExpressionCodeFragmentImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyExpressionCodeFragmentImpl.java @@ -25,7 +25,7 @@ public class PyExpressionCodeFragmentImpl extends PyFileImpl implements PyExpres public PyExpressionCodeFragmentImpl(Project project, @NonNls String name, CharSequence text, boolean isPhysical) { super(PsiManagerEx.getInstanceEx(project).getFileManager().createFileViewProvider( - new LightVirtualFile(name, getFileTypeByFileName(name), text), isPhysical) + new LightVirtualFile(name, getFileTypeByFileName(name), text), isPhysical) ); myPhysical = isPhysical; ((SingleRootFileViewProvider)getViewProvider()).forceCachedPsi(this); @@ -34,7 +34,8 @@ public class PyExpressionCodeFragmentImpl extends PyFileImpl implements PyExpres private static FileType getFileTypeByFileName(String name) { if (name.endsWith(".py")) { return PythonFileType.INSTANCE; - } else { + } + else { throw new IllegalArgumentException("unexpected file type"); } } @@ -45,7 +46,8 @@ public class PyExpressionCodeFragmentImpl extends PyFileImpl implements PyExpres clone.myPhysical = false; clone.myOriginalFile = this; FileManager fileManager = ((PsiManagerEx)getManager()).getFileManager(); - SingleRootFileViewProvider cloneViewProvider = (SingleRootFileViewProvider)fileManager.createFileViewProvider(new LightVirtualFile(getName(), getLanguage(), getText()), false); + SingleRootFileViewProvider cloneViewProvider = + (SingleRootFileViewProvider)fileManager.createFileViewProvider(new LightVirtualFile(getName(), getLanguage(), getText()), false); cloneViewProvider.forceCachedPsi(clone); clone.myViewProvider = cloneViewProvider; return clone; @@ -58,7 +60,7 @@ public class PyExpressionCodeFragmentImpl extends PyFileImpl implements PyExpres @Override public @NotNull FileViewProvider getViewProvider() { - if(myViewProvider != null) return myViewProvider; + if (myViewProvider != null) return myViewProvider; return super.getViewProvider(); } @@ -70,5 +72,4 @@ public class PyExpressionCodeFragmentImpl extends PyFileImpl implements PyExpres public void setContext(PsiElement context) { myContext = context; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyForStatementNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyForStatementNavigator.java index 4c58572d7d60..a8697e90b348 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyForStatementNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyForStatementNavigator.java @@ -26,13 +26,13 @@ public final class PyForStatementNavigator { private PyForStatementNavigator() { } - public static @Nullable PyForStatement getPyForStatementByIterable(final PsiElement element){ + public static @Nullable PyForStatement getPyForStatementByIterable(final PsiElement element) { final PyForStatement forStatement = PsiTreeUtil.getParentOfType(element, PyForStatement.class, false); - if (forStatement == null){ + if (forStatement == null) { return null; } final PyExpression target = forStatement.getForPart().getTarget(); - if (target != null && PsiTreeUtil.isAncestor(target, element, false)){ + if (target != null && PsiTreeUtil.isAncestor(target, element, false)) { return forStatement; } return null; @@ -40,7 +40,7 @@ public final class PyForStatementNavigator { public static @Nullable Object getPyForStatementByBody(final PsiElement element) { final PyForStatement forStatement = PsiTreeUtil.getParentOfType(element, PyForStatement.class, false); - if (forStatement == null){ + if (forStatement == null) { return null; } final PyForPart forPart = forStatement.getForPart(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java index d5ec6206a850..7879047f4af7 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java @@ -32,7 +32,8 @@ import java.util.List; import static com.jetbrains.python.psi.PyUtil.as; -public class PyFromImportStatementImpl extends PyBaseElementImpl implements PyFromImportStatement, PsiListLikeElement{ +public class PyFromImportStatementImpl extends PyBaseElementImpl + implements PyFromImportStatement, PsiListLikeElement { private volatile @Nullable ValueHolder myImportSourceQName; public PyFromImportStatementImpl(ASTNode astNode) { @@ -245,7 +246,7 @@ public class PyFromImportStatementImpl extends PyBaseElementImpl * http://stackoverflow.com/questions/6048786/from-module-import-in-init-py-makes-module-name-visible */ private @Nullable PsiElement resolveImplicitSubModule() { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionBuilder.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionBuilder.java index d33d1aa46383..2db7728b1e1c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionBuilder.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionBuilder.java @@ -49,7 +49,8 @@ public class PyFunctionBuilder { * @param decoratorsToCopyIfExist list of decorator names to be copied to new function. * @return builder configured by this function */ - public static @NotNull PyFunctionBuilder copySignature(final @NotNull PyFunction source, final String @NotNull ... decoratorsToCopyIfExist) { + public static @NotNull PyFunctionBuilder copySignature(final @NotNull PyFunction source, + final String @NotNull ... decoratorsToCopyIfExist) { final String name = source.getName(); final PyFunctionBuilder functionBuilder = new PyFunctionBuilder((name != null) ? name : "", source); for (final PyParameter parameter : source.getParameterList().getParameters()) { @@ -91,6 +92,7 @@ public class PyFunctionBuilder { /** * Adds param and its type to doc + * * @param name param name * @param type param type */ diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionImpl.java index ddbefd0d82dc..431776ad54e6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyFunctionImpl.java @@ -740,7 +740,8 @@ public class PyFunctionImpl extends PyBaseElementImpl implements if (decos.length > 0) { for (int i = decos.length - 1; i >= 0; i -= 1) { PyDecorator deco = decos[i]; - List knownDecorators = PyKnownDecoratorUtil.asKnownDecorators(deco, TypeEvalContext.codeInsightFallback(getProject())); + List knownDecorators = + PyKnownDecoratorUtil.asKnownDecorators(deco, TypeEvalContext.codeInsightFallback(getProject())); for (PyKnownDecorator decorator : knownDecorators) { if (decorator.isClassMethod() || decorator.isStaticMethod()) { return decorator; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGeneratorExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGeneratorExpressionImpl.java index ad784bea2f21..3876bc084728 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGeneratorExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGeneratorExpressionImpl.java @@ -40,7 +40,8 @@ public class PyGeneratorExpressionImpl extends PyComprehensionElementImpl implem public @Nullable PyType getType(@NotNull TypeEvalContext context, @NotNull TypeEvalContext.Key key) { final PyExpression resultExpr = getResultExpression(); if (resultExpr != null) { - return PyTypingTypeProvider.wrapInGeneratorType(context.getType(resultExpr), null, PyBuiltinCache.getInstance(this).getNoneType(), this); + return PyTypingTypeProvider.wrapInGeneratorType(context.getType(resultExpr), null, PyBuiltinCache.getInstance(this).getNoneType(), + this); } return null; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGlobalStatementNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGlobalStatementNavigator.java index fe66a9b940f8..e96095241c9f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGlobalStatementNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGlobalStatementNavigator.java @@ -24,9 +24,9 @@ public final class PyGlobalStatementNavigator { private PyGlobalStatementNavigator() { } - public static @Nullable PyGlobalStatement getByArgument(final PsiElement element){ + public static @Nullable PyGlobalStatement getByArgument(final PsiElement element) { final PsiElement parent = element.getParent(); - if (parent instanceof PyGlobalStatement statement){ + if (parent instanceof PyGlobalStatement statement) { return ArrayUtil.find(statement.getGlobals(), element) != -1 ? statement : null; } return null; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.kt index 9be363b93a09..979fff4264c5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.kt @@ -18,13 +18,11 @@ package com.jetbrains.python.psi.impl import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandlerBase import com.intellij.openapi.editor.Editor import com.intellij.psi.PsiElement -import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.resolve.FileContextUtil import com.jetbrains.python.PyUserInitiatedResolvableReference import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyQualifiedExpression import com.jetbrains.python.psi.PyReferenceOwner -import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.PyResolveUtil import com.jetbrains.python.psi.types.TypeEvalContext @@ -55,23 +53,23 @@ class PyGotoDeclarationHandler : GotoDeclarationHandlerBase() { val referenceOwner = sourceElement as? PyReferenceOwner ?: parent as? PyReferenceOwner if (referenceOwner != null) { val results = PyResolveUtil.multiResolveDeclaration(referenceOwner.getReference(context), context) - .map { - if (PyiUtil.isInsideStub(it) && !PyiUtil.isInsideStub(FileContextUtil.getContextFile(sourceElement)!!)) { - PyiUtil.getOriginalElement(it as PyElement) ?: it - } - else it - } - .filter { it !== referenceOwner } - .groupBy { it.containingFile } - .flatMap { (containingFile, declarations) -> - if (containingFile != sourceElement.containingFile) - declarations.take(1) - // if it's a qualified expression, then it could be a union, so go to the different declarations - // otherwise go to the most recent assignment - else if ((referenceOwner as? PyQualifiedExpression)?.isQualified == true) - declarations - else declarations.takeLast(1) + .map { + if (PyiUtil.isInsideStub(it) && !PyiUtil.isInsideStub(FileContextUtil.getContextFile(sourceElement)!!)) { + PyiUtil.getOriginalElement(it as PyElement) ?: it } + else it + } + .filter { it !== referenceOwner } + .groupBy { it.containingFile } + .flatMap { (containingFile, declarations) -> + if (containingFile != sourceElement.containingFile) + declarations.take(1) + // if it's a qualified expression, then it could be a union, so go to the different declarations + // otherwise go to the most recent assignment + else if ((referenceOwner as? PyQualifiedExpression)?.isQualified == true) + declarations + else declarations.takeLast(1) + } if (results.isNotEmpty()) { return results.toTypedArray() } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyIfPartIfImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyIfPartIfImpl.java index 1ca42b291603..93698de05614 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyIfPartIfImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyIfPartIfImpl.java @@ -12,5 +12,4 @@ public class PyIfPartIfImpl extends PyConditionalStatementPartImpl implements Py public PyIfPartIfImpl(ASTNode astNode) { super(astNode); } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportStatementNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportStatementNavigator.java index 31ccf7102a49..5f6da9438b7c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportStatementNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportStatementNavigator.java @@ -25,13 +25,13 @@ public final class PyImportStatementNavigator { private PyImportStatementNavigator() { } - public static @Nullable PyImportStatementBase getImportStatementByElement(final PsiElement element){ + public static @Nullable PyImportStatementBase getImportStatementByElement(final PsiElement element) { final PyImportStatementBase statement = PsiTreeUtil.getParentOfType(element, PyImportStatementBase.class, false); if (statement == null) { return null; } for (PyImportElement importElement : statement.getImportElements()) { - if (element == importElement || element == importElement.getImportReferenceExpression()){ + if (element == importElement || element == importElement.getImportReferenceExpression()) { return statement; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportedModule.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportedModule.java index 198cba3cb552..559b216ab23b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportedModule.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyImportedModule.java @@ -121,7 +121,7 @@ public class PyImportedModule extends LightElement implements PyTypedElement { else { final ResolveResultList resList = new ResolveResultList(); ResolveImportUtil.multiResolveModuleInRoots(myImportedPrefix, myContainingFile) - .forEach(res -> resList.poke(res, RatedResolveResult.RATE_NORMAL)); + .forEach(res -> resList.poke(res, RatedResolveResult.RATE_NORMAL)); results = resList; } return ContainerUtil.map(results, this::tryReplaceDirWithPackage); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyKeywordArgumentManipulator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyKeywordArgumentManipulator.java index 6ab6a6183fe0..e21194cf31a5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyKeywordArgumentManipulator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyKeywordArgumentManipulator.java @@ -28,12 +28,14 @@ import org.jetbrains.annotations.NotNull; public final class PyKeywordArgumentManipulator extends AbstractElementManipulator { @Override - public PyKeywordArgument handleContentChange(@NotNull PyKeywordArgument element, @NotNull TextRange range, String newContent) throws IncorrectOperationException { + public PyKeywordArgument handleContentChange(@NotNull PyKeywordArgument element, @NotNull TextRange range, String newContent) + throws IncorrectOperationException { final ASTNode keywordNode = element.getKeywordNode(); if (keywordNode != null && keywordNode.getPsi().getTextRangeInParent().equals(range)) { final LanguageLevel langLevel = LanguageLevel.forElement(element); final PyElementGenerator generator = PyElementGenerator.getInstance(element.getProject()); - final PyCallExpression callExpression = (PyCallExpression) generator.createExpressionFromText(langLevel, "foo(" + newContent + "=None)"); + final PyCallExpression callExpression = + (PyCallExpression)generator.createExpressionFromText(langLevel, "foo(" + newContent + "=None)"); final PyKeywordArgument kwArg = callExpression.getArgumentList().getKeywordArgument(newContent); element.getKeywordNode().getPsi().replace(kwArg.getKeywordNode().getPsi()); return element; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyLambdaExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyLambdaExpressionImpl.java index 233c130a80e5..a5c9a6ff8ee0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyLambdaExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyLambdaExpressionImpl.java @@ -42,7 +42,6 @@ public class PyLambdaExpressionImpl extends PyElementImpl implements PyLambdaExp } - @Override public @NotNull List getParameters(@NotNull TypeEvalContext context) { return Optional @@ -57,13 +56,13 @@ public class PyLambdaExpressionImpl extends PyElementImpl implements PyLambdaExp public @Nullable PyType getReturnType(@NotNull TypeEvalContext context, @NotNull TypeEvalContext.Key key) { final PyExpression body = getBody(); if (body == null) return null; - + final PyFunctionImpl.YieldCollector visitor = new PyFunctionImpl.YieldCollector(); body.accept(visitor); - + final List yieldTypes = map(visitor.getYieldExpressions(), it -> it.getYieldType(context)); final List sendTypes = map(visitor.getYieldExpressions(), it -> it.getSendType(context)); - + if (!yieldTypes.isEmpty()) { return PyTypingTypeProvider.wrapInGeneratorType( PyUnionType.union(yieldTypes), PyUnionType.union(sendTypes), context.getType(body), this); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyListCompExpressionNavigator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyListCompExpressionNavigator.java index e49c6c5f8614..17d09703c168 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyListCompExpressionNavigator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyListCompExpressionNavigator.java @@ -26,14 +26,14 @@ public final class PyListCompExpressionNavigator { private PyListCompExpressionNavigator() { } - public static @Nullable PyListCompExpression getPyListCompExpressionByVariable(final PsiElement element){ + public static @Nullable PyListCompExpression getPyListCompExpressionByVariable(final PsiElement element) { final PyListCompExpression listCompExpression = PsiTreeUtil.getParentOfType(element, PyListCompExpression.class, false); - if (listCompExpression == null){ + if (listCompExpression == null) { return null; } for (PyComprehensionForComponent component : listCompExpression.getForComponents()) { final PyExpression variable = component.getIteratorVariable(); - if (variable != null && PsiTreeUtil.isAncestor(variable, element, false)){ + if (variable != null && PsiTreeUtil.isAncestor(variable, element, false)) { return listCompExpression; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyMappingPatternImpl.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyMappingPatternImpl.kt index 65d4decc4fa1..bf0ff5278b8e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyMappingPatternImpl.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyMappingPatternImpl.kt @@ -32,8 +32,8 @@ class PyMappingPatternImpl(astNode: ASTNode?) : PyElementImpl(astNode), PyMappin val filteredType = PyCaptureContext.getCaptureType(this, context).toList().filter { captureType: PyType? -> val mappingType = PyTypeUtil.convertToType(captureType, "typing.Mapping", this, context) ?: return@filter false PyTypeChecker.match(mappingType, patternMappingType, context) - }.let { - PyUnionType.union(it) + }.let { + PyUnionType.union(it) } return filteredType ?: patternMappingType @@ -49,9 +49,9 @@ class PyMappingPatternImpl(astNode: ASTNode?) : PyElementImpl(astNode), PyMappin } return null } - + if (sequenceMember !is PyKeyValuePattern) return null - + return PyCaptureContext.getCaptureType(this, context).toList() .map { possibleMapping -> possibleMapping.getValueType(sequenceMember, context) } .let { PyUnionType.union(it) } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java index 2d94a71e6707..ace28eb5afe1 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyNamedParameterImpl.java @@ -283,10 +283,10 @@ public class PyNamedParameterImpl extends PyBaseElementImpl parameter.getType(context)) - .select(PyStructuralType.class) - .forEach(type -> usedAttributes.addAll(type.getAttributeNames())); + .nonNull() + .map(parameter -> parameter.getType(context)) + .select(PyStructuralType.class) + .forEach(type -> usedAttributes.addAll(type.getAttributeNames())); } } super.visitPyElement(node); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyParameterListImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyParameterListImpl.java index a87cfc3ec9fc..de2b891af56f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyParameterListImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyParameterListImpl.java @@ -81,15 +81,15 @@ public class PyParameterListImpl extends PyBaseElementImpl } final ASTNode previous = PyPsiUtils.getPrevNonWhitespaceSibling(beforeWhat); PyUtil.addListNode(this, param, beforeWhat, !isLast || params.length == 0 || - previous.getElementType() == PyTokenTypes.COMMA, isLast, - beforeWhat.getElementType() != PyTokenTypes.RPAR); + previous.getElementType() == PyTokenTypes.COMMA, isLast, + beforeWhat.getElementType() != PyTokenTypes.RPAR); } } @Override public boolean hasPositionalContainer() { - for (PyParameter parameter: getParameters()) { - if (parameter instanceof PyNamedParameter && ((PyNamedParameter) parameter).isPositionalContainer()) { + for (PyParameter parameter : getParameters()) { + if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isPositionalContainer()) { return true; } } @@ -98,8 +98,8 @@ public class PyParameterListImpl extends PyBaseElementImpl @Override public boolean hasKeywordContainer() { - for (PyParameter parameter: getParameters()) { - if (parameter instanceof PyNamedParameter && ((PyNamedParameter) parameter).isKeywordContainer()) { + for (PyParameter parameter : getParameters()) { + if (parameter instanceof PyNamedParameter && ((PyNamedParameter)parameter).isKeywordContainer()) { return true; } } @@ -128,7 +128,7 @@ public class PyParameterListImpl extends PyBaseElementImpl @Override public @Nullable PyFunction getContainingFunction() { final PsiElement parent = getParentByStub(); - return parent instanceof PyFunction ? (PyFunction) parent : null; + return parent instanceof PyFunction ? (PyFunction)parent : null; } @Override diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPathEvaluator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPathEvaluator.java index bc985ba245fb..5a9ebd53a133 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPathEvaluator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPathEvaluator.java @@ -40,7 +40,7 @@ public class PyPathEvaluator extends PyEvaluator { } VirtualFile vFile = expr.getContainingFile().getVirtualFile(); Object result = new PyPathEvaluator(vFile == null ? null : vFile.getPath()).evaluate(expr); - return result instanceof String ? (String) result : null; + return result instanceof String ? (String)result : null; } @Override @@ -57,7 +57,7 @@ public class PyPathEvaluator extends PyEvaluator { } if (expression.isCalleeText(PyNames.DIRNAME) && args.length == 1) { Object argValue = evaluate(args[0]); - return argValue instanceof String ? Paths.get((String) argValue).getParent().toFile().getPath() : null; + return argValue instanceof String ? Paths.get((String)argValue).getParent().toFile().getPath() : null; } else if (expression.isCalleeText(PyNames.JOIN) && args.length >= 1) { return evaluatePathInJoin(args, args.length); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintStatementImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintStatementImpl.java index e73c3c56b6d7..962d50c16d57 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintStatementImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintStatementImpl.java @@ -26,7 +26,7 @@ public class PyPrintStatementImpl extends PyElementImpl implements PyPrintStatem } @Override - protected void acceptPyVisitor(final PyElementVisitor pyVisitor) { + protected void acceptPyVisitor(final PyElementVisitor pyVisitor) { pyVisitor.visitPyPrintStatement(this); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintTargetImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintTargetImpl.java index cfceb6a3c2cc..8c0e57162a8c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintTargetImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyPrintTargetImpl.java @@ -20,7 +20,7 @@ import com.jetbrains.python.psi.PyPrintTarget; public class PyPrintTargetImpl extends PyElementImpl implements PyPrintTarget { - public PyPrintTargetImpl(ASTNode astNode) { - super(astNode); - } + public PyPrintTargetImpl(ASTNode astNode) { + super(astNode); + } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionImpl.java index d95d60a47d46..e9067842e4ff 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionImpl.java @@ -228,7 +228,7 @@ public class PyReferenceExpressionImpl extends PyElementImpl implements PyRefere final PyExpression qualifier = getQualifier(); if (qualifier == null) return null; - + final String attrName = getName(); if (attrName == null) return null; @@ -236,7 +236,7 @@ public class PyReferenceExpressionImpl extends PyElementImpl implements PyRefere final PyType dunderClassType = getDunderClassType(qualifierType, attrName); if (dunderClassType != null) return Ref.create(dunderClassType); - + final Ref typeOfProperty = getTypeOfProperty(qualifierType, attrName, context); if (typeOfProperty != null) { return typeOfProperty; @@ -259,12 +259,12 @@ public class PyReferenceExpressionImpl extends PyElementImpl implements PyRefere // - PyTypingTypeProvider checks if qualifier's class has a type annotation for 'this_name' // and returns that annotated type if found // - If no providers return a type, falls back to returning the type of the assigned value - + final PyType typeByControlFlow = getQualifiedReferenceTypeByControlFlow(context); if (typeByControlFlow != null) { return Ref.create(typeByControlFlow); } - + return null; } @@ -441,7 +441,7 @@ public class PyReferenceExpressionImpl extends PyElementImpl implements PyRefere if (scopeOwner != null && name != null && (!ScopeUtil.getElementsOfAccessType(name, scopeOwner, ReadWriteInstruction.ACCESS.ASSERTTYPE).isEmpty() - || target instanceof PyTargetExpression || target instanceof PyNamedParameter)) { + || target instanceof PyTargetExpression || target instanceof PyNamedParameter)) { final PyType type = getTypeByControlFlow(name, context, anchor, scopeOwner); if (type != null) { return type; @@ -572,7 +572,8 @@ public class PyReferenceExpressionImpl extends PyElementImpl implements PyRefere myQualifiers = qualifiers; } - public static @NotNull MultiFollowQueueNode create(@Nullable MultiFollowQueueNode previous, @NotNull PyReferenceExpression referenceExpression) { + public static @NotNull MultiFollowQueueNode create(@Nullable MultiFollowQueueNode previous, + @NotNull PyReferenceExpression referenceExpression) { final PyExpression qualifier = referenceExpression.getQualifier(); final List previousQualifiers = previous == null ? Collections.emptyList() : previous.myQualifiers; final List newQualifiers = qualifier == null ? previousQualifiers : ContainerUtil.append(previousQualifiers, qualifier); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionManipulator.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionManipulator.java index 036db7f701ce..e233ff7831af 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionManipulator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyReferenceExpressionManipulator.java @@ -24,7 +24,9 @@ import org.jetbrains.annotations.NotNull; public final class PyReferenceExpressionManipulator extends AbstractElementManipulator { @Override - public PyReferenceExpression handleContentChange(final @NotNull PyReferenceExpression element, final @NotNull TextRange range, final String newContent) + public PyReferenceExpression handleContentChange(final @NotNull PyReferenceExpression element, + final @NotNull TextRange range, + final String newContent) throws IncorrectOperationException { return null; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PySequencePatternImpl.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PySequencePatternImpl.kt index 3893d5c43bde..5e746f28ef30 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PySequencePatternImpl.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PySequencePatternImpl.kt @@ -24,12 +24,12 @@ class PySequencePatternImpl(astNode: ASTNode?) : PyElementImpl(astNode), PySeque else -> listOf(context.getType(pattern)) } } - + val expectedType = when { sequenceCaptureType.isHeterogeneousTuple() -> PyTupleType.create(this, types) else -> wrapInSequenceType(PyUnionType.union(types)) } - + if (sequenceCaptureType == null) return expectedType return sequenceCaptureType.toList() .map { intersect(it, expectedType, context) } @@ -53,9 +53,9 @@ class PySequencePatternImpl(astNode: ASTNode?) : PyElementImpl(astNode), PySeque .let { PyUnionType.union(it) } .let { wrapInListType(it) } } - + val idx = elements.indexOf(sequenceMember) - + return sequenceType.toList() .map { getElementTypeSkippingStar(it, idx, context) } .let { PyUnionType.union(it) } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java index d1e81bb6a145..407ff8cf6570 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java @@ -30,7 +30,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.List; -public class PyStringLiteralExpressionImpl extends PyElementImpl implements PyStringLiteralExpression, PsiLiteralValue, ContributedReferenceHost { +public class PyStringLiteralExpressionImpl extends PyElementImpl + implements PyStringLiteralExpression, PsiLiteralValue, ContributedReferenceHost { private volatile @Nullable String myStringValue; private volatile @Nullable List myValueTextRanges; @@ -184,5 +185,4 @@ public class PyStringLiteralExpressionImpl extends PyElementImpl implements PySt public int valueOffsetToTextOffset(int valueOffset) { return createLiteralTextEscaper().getOffsetInHost(valueOffset, getStringValueTextRange()); } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleExpressionImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleExpressionImpl.java index 319eb8e721f9..e195309e0a39 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleExpressionImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleExpressionImpl.java @@ -30,7 +30,7 @@ public class PyTupleExpressionImpl extends PySequenceExpressionImpl implements P super.deleteChildInternal(child); final PyExpression[] children = getElements(); final PyElementGenerator generator = PyElementGenerator.getInstance(getProject()); - if (children.length == 1 && PyPsiUtils.getNextComma(children[0]) == null ) { + if (children.length == 1 && PyPsiUtils.getNextComma(children[0]) == null) { addAfter(generator.createComma().getPsi(), children[0]); } else if (children.length == 0 && !(getParent() instanceof PyParenthesizedExpression)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleParameterImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleParameterImpl.java index 8bd2b7ace66f..40ba13b6db30 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleParameterImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyTupleParameterImpl.java @@ -30,7 +30,7 @@ import org.jetbrains.annotations.Nullable; * Represents a tuple parameter as stubbed element. */ public class PyTupleParameterImpl extends PyBaseElementImpl implements PyTupleParameter { - + public PyTupleParameterImpl(ASTNode astNode) { super(astNode); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyWhileStatementImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyWhileStatementImpl.java index 320637c680ca..3281b4fa7f56 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyWhileStatementImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/PyWhileStatementImpl.java @@ -11,7 +11,8 @@ public class PyWhileStatementImpl extends PyElementImpl implements PyWhileStatem super(astNode); } - @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { + @Override + protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyWhileStatement(this); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ResolveResultList.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ResolveResultList.java index 64bf274e0ee6..b35712f8cdcd 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ResolveResultList.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/ResolveResultList.java @@ -33,7 +33,7 @@ import java.util.List; public class ResolveResultList extends ArrayList { public static List to(PsiElement element) { - if (element== null) { + if (element == null) { return Collections.emptyList(); } final ResolveResultList list = new ResolveResultList(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyFromImportSourceReference.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyFromImportSourceReference.java index 3cac20db67f7..ab892b1ca956 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyFromImportSourceReference.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyFromImportSourceReference.java @@ -32,7 +32,7 @@ import java.util.List; */ public class PyFromImportSourceReference extends PyImportReference { private final PyFromImportStatement myStatement; - + public PyFromImportSourceReference(PyReferenceExpressionImpl element, PyResolveContext context) { super(element, context); myStatement = PsiTreeUtil.getParentOfType(element, PyFromImportStatement.class); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyImportReference.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyImportReference.java index 45c28ccabba8..b52a6393c5c4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyImportReference.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyImportReference.java @@ -107,7 +107,7 @@ public class PyImportReference extends PyReferenceImpl { } private static void replaceInsertHandler(Object[] variants, final InsertHandler insertHandler) { - for (int i=0; i < variants.length; i+=1) { + for (int i = 0; i < variants.length; i += 1) { Object item = variants[i]; if (hasChildPackages(item)) continue; if (item instanceof LookupElementBuilder) { @@ -127,7 +127,7 @@ public class PyImportReference extends PyReferenceImpl { private static boolean hasChildPackages(Object item) { PsiElement itemElement = null; if (item instanceof PsiElement) { - itemElement = (PsiElement) item; + itemElement = (PsiElement)item; } else if (item instanceof LookupElement lookupElement) { final PsiElement element = lookupElement.getPsiElement(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyKeywordPatternReference.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyKeywordPatternReference.java index 24801439ef21..e84b7a8d563e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyKeywordPatternReference.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyKeywordPatternReference.java @@ -89,7 +89,8 @@ public final class PyKeywordPatternReference extends PsiReferenceBase.Poly resolveToClassTypes(@NotNull PyClassPattern classPattern, @NotNull PyResolveContext resolveContext) { + private static @NotNull List resolveToClassTypes(@NotNull PyClassPattern classPattern, + @NotNull PyResolveContext resolveContext) { List elements = PyUtil.multiResolveTopPriority(classPattern.getClassNameReference(), resolveContext); return StreamEx.of(elements) .select(PyClass.class) diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyReferenceImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyReferenceImpl.java index 5ac1aac711a3..a6e46fe9d519 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyReferenceImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyReferenceImpl.java @@ -161,8 +161,8 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference } private static @NotNull RatedResolveResult changePropertyMethodToSameNameGetter(@NotNull RatedResolveResult resolveResult, - @NotNull String name, - @NotNull PsiElement referenceElement) { + @NotNull String name, + @NotNull PsiElement referenceElement) { PyCallExpression propertyCall = PsiTreeUtil.getParentOfType(referenceElement, PyCallExpression.class); if (propertyCall != null) { // Avoid converting function to property getter when the reference we are resolving sits inside a property(...) call (e.g., property(__getX)) @@ -356,7 +356,7 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference } private static @Nullable PyClass outermostNestedClass(@NotNull ScopeOwner referenceOwner, @NotNull ScopeOwner resolvedOwner) { - PyClass current = PyUtil.as(referenceOwner, PyClass.class); + PyClass current = PyUtil.as(referenceOwner, PyClass.class); ScopeOwner outer = ScopeUtil.getScopeOwner(current); while (outer != resolvedOwner) { @@ -479,8 +479,8 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference return null; } - @Override - public boolean isReferenceTo(@NotNull PsiElement element) { + @Override + public boolean isReferenceTo(@NotNull PsiElement element) { if (element instanceof PsiFileSystemItem) { // may be import via alias, so don't check if names match, do simple resolve check instead PsiElement resolveResult = resolve(); @@ -558,7 +558,7 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference } if (PsiTreeUtil.isAncestor(theirContainer, ourContainer, true)) { if (ourContainer instanceof PyComprehensionElement && containsDeclaration((PyComprehensionElement)ourContainer, elementName)) { - return false; + return false; } ScopeOwner owner = ourScopeOwner; @@ -633,10 +633,12 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference } protected boolean resolvesToWrapper(PsiElement element, PsiElement resolveResult) { - if (element instanceof PyFunction && ((PyFunction) element).getContainingClass() != null && resolveResult instanceof PyTargetExpression) { + if (element instanceof PyFunction && + ((PyFunction)element).getContainingClass() != null && + resolveResult instanceof PyTargetExpression) { final PyExpression assignedValue = ((PyTargetExpression)resolveResult).findAssignedValue(); if (assignedValue instanceof PyCallExpression call) { - final Pair functionPair = PyCallExpressionHelper.interpretAsModifierWrappingCall(call); + final Pair functionPair = PyCallExpressionHelper.interpretAsModifierWrappingCall(call); if (functionPair != null && functionPair.second == element) { return true; } @@ -702,7 +704,8 @@ public class PyReferenceImpl implements PsiReferenceEx, PsiPolyVariantReference // if we're a normal module, add module's attrs if (PyPsiUtils.getRealContext(element).getContainingFile() instanceof PyFile) { for (String name : PyModuleType.getPossibleInstanceMembers()) { - ret.add(LookupElementBuilder.create(name).withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Field))); + ret.add( + LookupElementBuilder.create(name).withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Field))); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyTargetReference.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyTargetReference.java index e75caf7f39e0..b448c95aeafc 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyTargetReference.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/references/PyTargetReference.java @@ -40,7 +40,7 @@ public class PyTargetReference extends PyReferenceImpl { } } // resolve to self if no other target found - return new ResolveResult[] { new PsiElementResolveResult(myElement) }; + return new ResolveResult[]{new PsiElementResolveResult(myElement)}; } @Override diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java index 50d0db257347..d78927fce3b3 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java @@ -44,12 +44,12 @@ public class PyAnnotationElementType extends PyStubElementType implements PyFileStu @Override public @NotNull IStubFileElementType getType() { - return (IStubFileElementType) LanguageParserDefinitions.INSTANCE.forLanguage(PythonLanguage.getInstance()).getFileNodeType(); + return (IStubFileElementType)LanguageParserDefinitions.INSTANCE.forLanguage(PythonLanguage.getInstance()).getFileNodeType(); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java index ccae13cbcf83..53344b0e2567 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java @@ -66,7 +66,7 @@ public class PyNamedParameterElementType extends PyStubElementType resolveTupleFields(@NotNull PyCallExpression callExpression, @NotNull NamedTupleModule module) { + private static @Nullable LinkedHashMap resolveTupleFields(@NotNull PyCallExpression callExpression, + @NotNull NamedTupleModule module) { return switch (module) { case TYPING -> resolveTypingNTFields(callExpression); case COLLECTIONS -> resolveCollectionsNTFields(callExpression); }; } - private static @NotNull LinkedHashMap deserializeFields(@NotNull StubInputStream stream, int fieldsSize) + private static @NotNull LinkedHashMap deserializeFields(@NotNull StubInputStream stream, int fieldsSize) throws IOException { - final LinkedHashMap fields = new LinkedHashMap<>(fieldsSize); + final LinkedHashMap fields = new LinkedHashMap<>(fieldsSize); for (int i = 0; i < fieldsSize; i++) { final String name = stream.readNameString(); @@ -207,8 +208,8 @@ public final class PyNamedTupleStubImpl implements PyNamedTupleStub { final PyExpression defaults = getDefaultsArgumentValue(callExpression); final PyExpression resolvedDefaults = defaults instanceof PyReferenceExpression - ? PyResolveUtil.fullResolveLocally((PyReferenceExpression)defaults) - : defaults; + ? PyResolveUtil.fullResolveLocally((PyReferenceExpression)defaults) + : defaults; int defaultStart = fieldNames.size(); if (resolvedDefaults instanceof PySequenceExpression seq) { defaultStart -= seq.getElements().length; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java index af5c0b43b726..c5dcabfad66a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java @@ -44,12 +44,12 @@ public class PyParameterListElementType extends PyStubElementType implements PyTupleParameterStub { +public class PyTupleParameterStubImpl extends StubBase implements PyTupleParameterStub { private final @Nullable String myDefaultValueText; protected PyTupleParameterStubImpl(@Nullable String defaultValueText, StubElement parent) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypedDictStubImpl.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypedDictStubImpl.kt index 2e61e39a4257..6ceb33f4c376 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypedDictStubImpl.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypedDictStubImpl.kt @@ -15,10 +15,12 @@ import com.jetbrains.python.psi.types.PyTypedDictType.Companion.TYPED_DICT_TOTAL import java.io.IOException import java.util.* -class PyTypedDictStubImpl private constructor(private val myCalleeName: QualifiedName, - override val name: String, - override val fields: List, - override val isRequired: Boolean = true) : PyTypedDictStub { +class PyTypedDictStubImpl private constructor( + private val myCalleeName: QualifiedName, + override val name: String, + override val fields: List, + override val isRequired: Boolean = true, +) : PyTypedDictStub { override fun getTypeClass(): Class { return PyTypedDictStubType::class.java @@ -97,7 +99,7 @@ class PyTypedDictStubImpl private constructor(private val myCalleeName: Qualifie @Throws(IOException::class) private fun deserializeFields(stream: StubInputStream, fieldsCount: Int): List { - val fields = ArrayList(fieldsCount) + val fields = ArrayList(fieldsCount) for (i in 0 until fieldsCount) { val name = stream.readNameString() diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypingTypeAliasStubImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypingTypeAliasStubImpl.java index faa9dcf999d4..8fe10b889c43 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypingTypeAliasStubImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyTypingTypeAliasStubImpl.java @@ -55,6 +55,6 @@ public class PyTypingTypeAliasStubImpl implements PyTypingAliasStub { @Override public String toString() { - return "PyTypingAliasStub(text='" + getText() +"')"; + return "PyTypingAliasStub(text='" + getText() + "')"; } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java index 827f8aafaf27..aa2a1dd8fd7f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/CompletionVariantsProcessor.java @@ -67,7 +67,7 @@ public class CompletionVariantsProcessor extends VariantsProcessor { final TypeEvalContext context = TypeEvalContext.codeCompletion(project, myContext != null ? myContext.getContainingFile() : null); if (myContext != null && PyParameterizedTypeInsertHandler.isCompletingParameterizedType(element, myContext, context)) { - item = item.withInsertHandler(PyParameterizedTypeInsertHandler.INSTANCE); + item = item.withInsertHandler(PyParameterizedTypeInsertHandler.INSTANCE); } else if (!mySuppressParentheses && element instanceof PyFunction && ((PyFunction)element).getProperty() == null && diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyForwardReferenceResolveProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyForwardReferenceResolveProvider.kt index 322f5d0dd0aa..1132b2b7633f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyForwardReferenceResolveProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyForwardReferenceResolveProvider.kt @@ -24,7 +24,8 @@ class PyForwardReferenceResolveProvider : PyReferenceResolveProvider { return if (originalOwner != null) { PyResolveUtil.resolveLocally(originalOwner, referencedName) .map { RatedResolveResult(RatedResolveResult.RATE_NORMAL, it) } - } else emptyList() + } + else emptyList() } override fun allowsForwardOutgoingReferencesInClass(element: PyQualifiedExpression): Boolean { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyIPythonBuiltinReferenceResolveProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyIPythonBuiltinReferenceResolveProvider.kt index 3eea1d84dbcf..dcb93cca7bb6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyIPythonBuiltinReferenceResolveProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyIPythonBuiltinReferenceResolveProvider.kt @@ -30,18 +30,19 @@ class PyIPythonBuiltinReferenceResolveProvider : PyReferenceResolveProvider { IPythonBuiltinConstants.TRIPLE_UNDERSCORE -> return resolveOut(element, context) } - if (name in IPythonBuiltinConstants.MAGICS_LIST - && element.parent is PyExpressionStatement - && isAutomagicOn(element)) { + if (name in IPythonBuiltinConstants.MAGICS_LIST + && element.parent is PyExpressionStatement + && isAutomagicOn(element) + ) { return resolveMagics(element, context) } return emptyList() } /** - We resolve IPython built-ins in two cases: - 1) in PyCharm PRO in Jupyter files only - 2) in DataSpell in Python files and Jupyter files + We resolve IPython built-ins in two cases: + 1) in PyCharm PRO in Jupyter files only + 2) in DataSpell in Python files and Jupyter files */ private fun needToResolve(context: TypeEvalContext): Boolean { val psiFile = context.origin ?: return false @@ -71,14 +72,14 @@ class PyIPythonBuiltinReferenceResolveProvider : PyReferenceResolveProvider { private fun resolveIn(element: PyQualifiedExpression, context: TypeEvalContext): List { val historyClass = getPyClassByDottedPath(IPythonBuiltinConstants.HISTORY_MANAGER_DOTTED_PATH, - fromFoothold(element)) ?: return emptyList() + fromFoothold(element)) ?: return emptyList() val inHistDictPsi = historyClass.findClassAttribute(IPythonBuiltinConstants.IN_HIST_DICT, false, context) return ResolveResultList.to(inHistDictPsi) } private fun resolveOut(element: PyQualifiedExpression, context: TypeEvalContext): List { val historyClass = getPyClassByDottedPath(IPythonBuiltinConstants.HISTORY_MANAGER_DOTTED_PATH, - fromFoothold(element)) ?: return emptyList() + fromFoothold(element)) ?: return emptyList() val outHistDictPsi = historyClass.findClassAttribute(IPythonBuiltinConstants.OUT_HIST_DICT, false, context) return ResolveResultList.to(outHistDictPsi) } @@ -126,11 +127,11 @@ class PyIPythonBuiltinReferenceResolveProvider : PyReferenceResolveProvider { if (sib is PyExpressionStatement && sib.nextSibling is PsiWhiteSpace && sib.children.let { - it.size == 2 && it.first() is PyReferenceExpression && it.last() is PsiErrorElement && it.first().text == "automagic" - } + it.size == 2 && it.first() is PyReferenceExpression && it.last() is PsiErrorElement && it.first().text == "automagic" + } && sib.nextSibling.nextSibling.let { - it is PyExpressionStatement && it.children.singleOrNull() is PyNumericLiteralExpression - } + it is PyExpressionStatement && it.children.singleOrNull() is PyNumericLiteralExpression + } ) { if (sib.nextSibling.nextSibling.text == "1") { return true diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyNamespacePackageUtil.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyNamespacePackageUtil.kt index 1ecf92334eec..c731c6529d4c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyNamespacePackageUtil.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyNamespacePackageUtil.kt @@ -1,4 +1,5 @@ @file:JvmName("PyNamespacePackageUtil") + package com.jetbrains.python.psi.resolve import com.intellij.psi.PsiDirectory diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContextImpl.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContextImpl.kt index 0b5d4c6219d1..a3ec69c837e8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContextImpl.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyQualifiedNameResolveContextImpl.kt @@ -26,14 +26,16 @@ import com.jetbrains.python.PyNames import com.jetbrains.python.PythonRuntimeService import com.jetbrains.python.psi.impl.PyExpressionCodeFragmentImpl -data class PyQualifiedNameResolveContextImpl(private val psiManager: PsiManager, private val module: Module?, - private val foothold: PsiElement?, private val sdk: Sdk?, - private val relativeLevel : Int = -1, - private val withoutRoots : Boolean = false, - private val withoutForeign: Boolean = false, - private val withMembers : Boolean = false, - private val withPlainDirectories : Boolean = false, - private val withoutStubs: Boolean = false) : PyQualifiedNameResolveContext { +data class PyQualifiedNameResolveContextImpl( + private val psiManager: PsiManager, private val module: Module?, + private val foothold: PsiElement?, private val sdk: Sdk?, + private val relativeLevel: Int = -1, + private val withoutRoots: Boolean = false, + private val withoutForeign: Boolean = false, + private val withMembers: Boolean = false, + private val withPlainDirectories: Boolean = false, + private val withoutStubs: Boolean = false, +) : PyQualifiedNameResolveContext { override fun getFoothold(): PsiElement? = foothold override fun getRelativeLevel(): Int = relativeLevel @@ -56,7 +58,8 @@ data class PyQualifiedNameResolveContextImpl(private val psiManager: PsiManager, override fun getWithoutStubs(): Boolean = withoutStubs - override fun getEffectiveSdk(): Sdk? = if (visitAllModules && foothold != null) PythonRuntimeService.getInstance().getConsoleSdk(foothold) else sdk + override fun getEffectiveSdk(): Sdk? = + if (visitAllModules && foothold != null) PythonRuntimeService.getInstance().getConsoleSdk(foothold) else sdk override fun isValid(): Boolean = footholdFile?.isValid ?: true @@ -66,7 +69,7 @@ data class PyQualifiedNameResolveContextImpl(private val psiManager: PsiManager, override fun copyWithPlainDirectories(): PyQualifiedNameResolveContextImpl = copy(withPlainDirectories = true) - override fun copyWithRelative(relativeLevel : Int): PyQualifiedNameResolveContextImpl = copy(relativeLevel = relativeLevel) + override fun copyWithRelative(relativeLevel: Int): PyQualifiedNameResolveContextImpl = copy(relativeLevel = relativeLevel) override fun copyWithoutRoots(): PyQualifiedNameResolveContextImpl = copy(withoutRoots = true) diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt index 7a27e2eccd3f..34079f629586 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt @@ -277,16 +277,19 @@ private fun resultsFromRoots(name: QualifiedName, context: PyQualifiedNameResolv val results = if (isModuleSource) moduleResults else sdkResults val effectiveSdk = sdk ?: context.effectiveSdk if (!root.isValid || - effectiveSdk != null && PyTypeShed.isInside(root) && !PyTypeShed.maySearchForStubInRoot(name, root, effectiveSdk)) { + effectiveSdk != null && PyTypeShed.isInside(root) && !PyTypeShed.maySearchForStubInRoot(name, root, effectiveSdk) + ) { return@RootVisitor true } if (withoutStubs && (PyTypeShed.isInside(root) || - PsiManager.getInstance(context.project).findDirectory(root)?.let { isInStubPackage(it) } == true)) { + PsiManager.getInstance(context.project).findDirectory(root)?.let { isInStubPackage(it) } == true) + ) { return@RootVisitor true } results.addAll(resolveInRoot(name, root, context)) if (isAcceptRootAsTopLevelPackage(context) && name.matchesPrefix( - QualifiedName.fromDottedString(root.name))) { + QualifiedName.fromDottedString(root.name)) + ) { //TODO[akniazev]: resolving from parent root. Is it still a thing for Django? results.addAll(resolveInRoot(name, root.parent, context)) } @@ -365,8 +368,10 @@ private fun isSameDirectoryResult(element: PsiElement, context: PyQualifiedNameR } } -private fun isSameDirectoryOrRelativeImportResult(name: QualifiedName, directory: PsiDirectory, result: PsiElement, - context: PyQualifiedNameResolveContext): Boolean { +private fun isSameDirectoryOrRelativeImportResult( + name: QualifiedName, directory: PsiDirectory, result: PsiElement, + context: PyQualifiedNameResolveContext, +): Boolean { if (context.relativeLevel > 0) { return true } @@ -379,9 +384,11 @@ private fun checkAccess() { Preconditions.checkState(ApplicationManager.getApplication().isReadAccessAllowed, "This method requires read access") } -private fun filterTopPriorityResultsWithFallback(primaryResults: List, fallbackResults: List, - foreignResults: List, name: QualifiedName, - context: PyQualifiedNameResolveContext): List { +private fun filterTopPriorityResultsWithFallback( + primaryResults: List, fallbackResults: List, + foreignResults: List, name: QualifiedName, + context: PyQualifiedNameResolveContext, +): List { val allResults = primaryResults + fallbackResults + foreignResults if (name.componentCount <= 0) return allResults val filteredPrimaryResults = filterTopPriorityResults(primaryResults, context.module) @@ -402,7 +409,7 @@ private fun filterTopPriorityResults(resolved: List, module: Module? if (groupedResults.topResultIs(Priority.NAMESPACE_PACKAGE)) return groupedResults[Priority.NAMESPACE_PACKAGE]!! + skeletons groupedResults.remove(Priority.NAMESPACE_PACKAGE) - val priorityResults = when { + val priorityResults = when { groupedResults.isEmpty() -> emptyList() // stub packages can be partial groupedResults.topResultIs(Priority.STUB_PACKAGE) -> firstResultWithFallback(groupedResults, Priority.STUB_PACKAGE) diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java index 9f6846e92b9e..455eb6097cf2 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java @@ -233,7 +233,7 @@ public final class PyResolveUtil { /** * Resolve a symbol by its qualified name, climbing up from the specified scope until the first component * of the qualified is resolved and then following the chain of type members. - *

+ *

* This type of resolve is stub-safe, i.e. it's not supposed to cause any un-stubbing of external files unless it is explicitly * allowed by the given type evaluation context. * @@ -393,7 +393,7 @@ public final class PyResolveUtil { * Note: the returned stream could contain null values. */ private static @NotNull StreamEx fullMultiResolveLocally(@NotNull PyReferenceExpression referenceExpression, - @NotNull Set visited) { + @NotNull Set visited) { return StreamEx .of(resolveLocally(referenceExpression)) .flatMap( @@ -520,7 +520,8 @@ public final class PyResolveUtil { return rate; } - public static @NotNull List<@NotNull PsiElement> multiResolveDeclaration(@NotNull PsiReference reference, @NotNull PyResolveContext resolveContext) { + public static @NotNull List<@NotNull PsiElement> multiResolveDeclaration(@NotNull PsiReference reference, + @NotNull PyResolveContext resolveContext) { final PsiElement element = reference.getElement(); final var context = resolveContext.getTypeEvalContext(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonModulePathCache.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonModulePathCache.java index 5f19dfc007de..8520cfe2e8fa 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonModulePathCache.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonModulePathCache.java @@ -90,5 +90,5 @@ public final class PythonModulePathCache extends PythonPathCache implements Disp @Override public void dispose() { - } + } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonPathCache.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonPathCache.java index 67bcbbcd67a3..300a96108217 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonPathCache.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/PythonPathCache.java @@ -47,7 +47,7 @@ public abstract class PythonPathCache { return null; } final List elements = references.get(); - if(elements != null && ! elements.stream().allMatch(PsiElement::isValid)) { + if (elements != null && !elements.stream().allMatch(PsiElement::isValid)) { // At least one element is invalid return null; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java index c03ca30091f5..71a4848f3503 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java @@ -95,7 +95,8 @@ public final class ResolveImportUtil { return !resultList.isEmpty() ? resultList.get(0).getElement() : null; } - public static @NotNull List multiResolveImportElement(PyImportElement importElement, final @NotNull QualifiedName qName) { + public static @NotNull List multiResolveImportElement(PyImportElement importElement, + final @NotNull QualifiedName qName) { PyUtil.verboseOnly(() -> PyPsiUtils.assertValid(importElement)); final PyStatement importStatement = importElement.getContainingImportStatement(); if (importStatement instanceof PyFromImportStatement) { @@ -106,14 +107,16 @@ public final class ResolveImportUtil { } } - public static @NotNull List resolveNameInImportStatement(PyImportElement importElement, @NotNull QualifiedName qName) { + public static @NotNull List resolveNameInImportStatement(PyImportElement importElement, + @NotNull QualifiedName qName) { final PsiFile file = importElement.getContainingFile().getOriginalFile(); boolean absoluteImportEnabled = isAbsoluteImportEnabledFor(importElement); final List modules = resolveModule(qName, file, absoluteImportEnabled, 0); return rateResults(modules); } - public static @NotNull List resolveNameInFromImport(PyFromImportStatement importStatement, @NotNull QualifiedName qName) { + public static @NotNull List resolveNameInFromImport(PyFromImportStatement importStatement, + @NotNull QualifiedName qName) { PsiFile file = importStatement.getContainingFile().getOriginalFile(); String name = qName.getComponents().get(0); @@ -152,7 +155,7 @@ public final class ResolveImportUtil { * @return list of possible candidates */ public static @NotNull List resolveModule(@Nullable QualifiedName qualifiedName, @Nullable PsiFile sourceFile, - boolean importIsAbsolute, int relativeLevel) { + boolean importIsAbsolute, int relativeLevel) { if (qualifiedName == null || sourceFile == null) { return Collections.emptyList(); } @@ -182,7 +185,8 @@ public final class ResolveImportUtil { ); } - public static @NotNull List multiResolveModuleInRoots(@NotNull QualifiedName moduleQualifiedName, @Nullable PsiElement foothold) { + public static @NotNull List multiResolveModuleInRoots(@NotNull QualifiedName moduleQualifiedName, + @Nullable PsiElement foothold) { if (foothold == null) return Collections.emptyList(); return PyResolveImportUtil.resolveQualifiedName(moduleQualifiedName, PyResolveImportUtil.fromFoothold(foothold)); @@ -218,11 +222,11 @@ public final class ResolveImportUtil { */ @Deprecated(forRemoval = true) public static @Nullable PsiElement resolveChild(final @Nullable PsiElement parent, - final @NotNull String referencedName, - final @Nullable PsiFile containingFile, - boolean fileOnly, - boolean checkForPackage, - boolean withoutStubs) { + final @NotNull String referencedName, + final @Nullable PsiFile containingFile, + boolean fileOnly, + boolean checkForPackage, + boolean withoutStubs) { final List results = resolveChildren(parent, referencedName, containingFile, fileOnly, checkForPackage, withoutStubs, false); return results.isEmpty() ? null : RatedResolveResult.sorted(results).get(0).getElement(); @@ -240,12 +244,12 @@ public final class ResolveImportUtil { * @return the element the referencedName resolves to */ public static @NotNull List resolveChildren(@Nullable PsiElement parent, - @NotNull String referencedName, - @Nullable PsiFile containingFile, - boolean fileOnly, - boolean checkForPackage, - boolean withoutStubs, - boolean withoutForeign) { + @NotNull String referencedName, + @Nullable PsiFile containingFile, + boolean fileOnly, + boolean checkForPackage, + boolean withoutStubs, + boolean withoutForeign) { if (parent == null) { return Collections.emptyList(); } @@ -261,9 +265,13 @@ public final class ResolveImportUtil { } } - private static @NotNull List resolveInPackageModule(@NotNull PyFile parent, @NotNull String referencedName, - @Nullable PsiFile containingFile, boolean fileOnly, - boolean checkForPackage, boolean withoutStubs, boolean withoutForeign) { + private static @NotNull List resolveInPackageModule(@NotNull PyFile parent, + @NotNull String referencedName, + @Nullable PsiFile containingFile, + boolean fileOnly, + boolean checkForPackage, + boolean withoutStubs, + boolean withoutForeign) { final List moduleMembers = resolveModuleMember(parent, referencedName); final List resolvedInModule = new ArrayList<>(); final List results = new ArrayList<>(); @@ -306,9 +314,13 @@ public final class ResolveImportUtil { return Lists.newArrayList(results); } - private static @NotNull List resolveInPackageDirectory(@NotNull PsiFileSystemItem parent, @NotNull String referencedName, - @Nullable PsiFile containingFile, boolean fileOnly, - boolean checkForPackage, boolean withoutStubs, boolean withoutForeign) { + private static @NotNull List resolveInPackageDirectory(@NotNull PsiFileSystemItem parent, + @NotNull String referencedName, + @Nullable PsiFile containingFile, + boolean fileOnly, + boolean checkForPackage, + boolean withoutStubs, + boolean withoutForeign) { final PsiElement parentDir = PyUtil.turnInitIntoDir(parent); if (parentDir instanceof PsiDirectory) { final List resolved = resolveInDirectory(referencedName, containingFile, (PsiDirectory)parentDir, fileOnly, @@ -377,7 +389,8 @@ public final class ResolveImportUtil { final Ref refType = PyReferenceExpressionImpl.getReferenceTypeFromProviders(parent, context, null); if (refType != null && !refType.isNull()) { final PyResolveContext resolveContext = PyResolveContext.defaultContext(context); - final List result = refType.get().resolveMember(referencedName, null, AccessDirection.READ, resolveContext); + final List result = + refType.get().resolveMember(referencedName, null, AccessDirection.READ, resolveContext); if (result != null) { return Lists.newArrayList(result); } @@ -430,7 +443,7 @@ public final class ResolveImportUtil { if (!withoutStubs) { final var stub = dir.findFile(referencedName + PyNames.DOT_PYI); if (!PyiStubSuppressor.isIgnoredStub(stub)) { - file = stub; + file = stub; } } if (file == null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitor.java index b5daa9e67e92..1af8247c49cf 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitor.java @@ -21,12 +21,12 @@ import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.Nullable; /** -* Simple visitor to use with ResolveImportUtil. -* User: dcheryasov -*/ + * Simple visitor to use with ResolveImportUtil. + * User: dcheryasov + */ public interface RootVisitor { /** - * @param root what we're visiting. + * @param root what we're visiting. * @param module the module to which the root belongs, or null * @param sdk the SDK to which the root belongs, or null * @param isModuleSource true iff the root belongs to the module in case both module and sdk are present diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java index 1476b5c68f6e..6ff67e28787e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/resolve/RootVisitorHost.java @@ -131,8 +131,8 @@ public final class RootVisitorHost { Set allRoots = new LinkedHashSet<>(); Collections.addAll(allRoots, entry.getFiles(OrderRootType.SOURCES)); Collections.addAll(allRoots, entry.getFiles(OrderRootType.CLASSES)); - Module module = entry instanceof ModuleOrderEntry ? ((ModuleOrderEntry) entry).getModule() : null; - Sdk sdk = entry instanceof JdkOrderEntry ? ((JdkOrderEntry) entry).getJdk() : null; + Module module = entry instanceof ModuleOrderEntry ? ((ModuleOrderEntry)entry).getModule() : null; + Sdk sdk = entry instanceof JdkOrderEntry ? ((JdkOrderEntry)entry).getJdk() : null; for (VirtualFile root : allRoots) { if (!visitor.visitRoot(root, module, sdk, false)) { return false; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java index df71215c4cf1..16b9f604ec4e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyClassInheritorsSearchExecutor.java @@ -25,13 +25,14 @@ public final class PyClassInheritorsSearchExecutor implements QueryExecutor IGNORED_BASES = ImmutableSet.of("object", "BaseException", "Exception"); @Override - public boolean execute(final @NotNull PyClassInheritorsSearch.SearchParameters queryParameters, final @NotNull Processor consumer) { + public boolean execute(final @NotNull PyClassInheritorsSearch.SearchParameters queryParameters, + final @NotNull Processor consumer) { Set processed = new HashSet<>(); return processDirectInheritors(queryParameters.getSuperClass(), consumer, queryParameters.isCheckDeepInheritance(), processed); } private static boolean processDirectInheritors( - final PyClass superClass, final Processor consumer, final boolean checkDeep, final Set processed + final PyClass superClass, final Processor consumer, final boolean checkDeep, final Set processed ) { return ReadAction.compute(() -> { final String superClassName = superClass.getName(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java index 32a95ab8a85f..3347e8866409 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PyKeywordArgumentSearchExecutor.java @@ -16,7 +16,8 @@ import org.jetbrains.annotations.NotNull; public final class PyKeywordArgumentSearchExecutor extends QueryExecutorBase { @Override - public void processQuery(final @NotNull ReferencesSearch.SearchParameters queryParameters, final @NotNull Processor consumer) { + public void processQuery(final @NotNull ReferencesSearch.SearchParameters queryParameters, + final @NotNull Processor consumer) { final PsiElement element = queryParameters.getElementToSearch(); if (!(element instanceof PyNamedParameter)) { return; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PySuperMethodsSearch.java b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PySuperMethodsSearch.java index f94800b9bb70..e27e7bf0074f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/search/PySuperMethodsSearch.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/search/PySuperMethodsSearch.java @@ -31,15 +31,16 @@ public final class PySuperMethodsSearch extends ExtensibleQueryFactory superMethods, - PyClass containingClass) { + PyClass containingClass) { for (PyClass ancestor : containingClass.getAncestorClasses(null)) { for (PsiElement method : superMethods) { - if (ancestor.equals(((PyFunction)method).getContainingClass())) + if (ancestor.equals(((PyFunction)method).getContainingClass())) { return (PyFunction)method; + } } } - return (PyFunction) superMethods.get(superMethods.size()-1); + return (PyFunction)superMethods.get(superMethods.size() - 1); } public static PyFunction findDeepestSuperMethod(PyFunction function) { @@ -85,7 +86,9 @@ public final class PySuperMethodsSearch extends ExtensibleQueryFactory search(final PyFunction derivedMethod, final boolean deepSearch, final @Nullable TypeEvalContext context) { + public static Query search(final PyFunction derivedMethod, + final boolean deepSearch, + final @Nullable TypeEvalContext context) { final SearchParameters parameters = new SearchParameters(derivedMethod, deepSearch, context); return INSTANCE.createUniqueResultsQuery(parameters); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PropertyStubStorage.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PropertyStubStorage.java index 94e4fc288987..b66c33e8a7a8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PropertyStubStorage.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PropertyStubStorage.java @@ -37,8 +37,12 @@ public class PropertyStubStorage extends PropertyBunch implements Custom private static final String IMPOSSIBLE_NAME = "#"; private static void writeOne(Maybe what, StubOutputStream stream) throws IOException { - if (what.isDefined()) stream.writeName(what.value()); - else stream.writeName(IMPOSSIBLE_NAME); + if (what.isDefined()) { + stream.writeName(what.value()); + } + else { + stream.writeName(IMPOSSIBLE_NAME); + } } @Override @@ -71,8 +75,8 @@ public class PropertyStubStorage extends PropertyBunch implements Custom public static PropertyStubStorage deserialize(StubInputStream stream) throws IOException { PropertyStubStorage me = new PropertyStubStorage(); - me.myGetter = readOne(stream); - me.mySetter = readOne(stream); + me.myGetter = readOne(stream); + me.mySetter = readOne(stream); me.myDeleter = readOne(stream); // me.myDoc = stream.readNameString(); @@ -84,17 +88,22 @@ public class PropertyStubStorage extends PropertyBunch implements Custom private static @Nullable Maybe readOne(StubInputStream stream) throws IOException { String s = stream.readNameString(); - if (s == null) return none; + if (s == null) { + return none; + } else { - if (IMPOSSIBLE_NAME.equals(s)) return unknown; - else return new Maybe<>(s); + if (IMPOSSIBLE_NAME.equals(s)) { + return unknown; + } + else { + return new Maybe<>(s); + } } } public static @Nullable PropertyStubStorage fromCall(@Nullable PyExpression expr) { final PropertyStubStorage prop = new PropertyStubStorage(); final boolean success = fillFromCall(expr, prop); - return success? prop : null; + return success ? prop : null; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java index 7cdc8692ff5a..4e3eb74c838c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassAttributesIndex.java @@ -33,7 +33,6 @@ public final class PyClassAttributesIndex extends StringStubIndexExtension findClassAndInstanceAttributes( @NotNull String name, @NotNull Project project, @@ -47,7 +46,7 @@ public final class PyClassAttributesIndex extends StringStubIndexExtension getAllDeclaredAttributeNames(@NotNull PyClass pyClass) { List members = ContainerUtil.concat(pyClass.getInstanceAttributes(), - pyClass.getClassAttributes(), - Arrays.asList(pyClass.getMethods())); + pyClass.getClassAttributes(), + Arrays.asList(pyClass.getMethods())); return ContainerUtil.mapNotNull(members, expression -> expression.getName()); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndex.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndex.java index 77a70605e953..547095aed13d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndex.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndex.java @@ -37,8 +37,8 @@ public final class PyClassNameIndex extends StringStubIndexExtension { public static @NotNull List findByQualifiedName(@NotNull QualifiedName qName, - @NotNull Project project, - @NotNull GlobalSearchScope scope) { + @NotNull Project project, + @NotNull GlobalSearchScope scope) { String shortName = qName.getLastComponent(); if (shortName == null) return Collections.emptyList(); String qNameString = qName.toString(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndexInsensitive.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndexInsensitive.java index cbca8f1780ae..6fd75fd47b9b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndexInsensitive.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyClassNameIndexInsensitive.java @@ -28,7 +28,7 @@ import java.util.Collection; public final class PyClassNameIndexInsensitive extends StringStubIndexExtension { - public static final StubIndexKey KEY = StubIndexKey.createIndexKey("Py.class.shortNameInsensitive"); + public static final StubIndexKey KEY = StubIndexKey.createIndexKey("Py.class.shortNameInsensitive"); @Override public @NotNull StubIndexKey getKey() { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyModuleNameIndex.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyModuleNameIndex.java index ee159294a104..0582bc0c9984 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyModuleNameIndex.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyModuleNameIndex.java @@ -93,7 +93,9 @@ public final class PyModuleNameIndex extends ScalarIndexExtension { * @param project project where the search is performed * @param scope search scope, limiting applicable virtual files */ - public static @NotNull List findByShortName(@NotNull String shortName, @NotNull Project project, @NotNull GlobalSearchScope scope) { + public static @NotNull List findByShortName(@NotNull String shortName, + @NotNull Project project, + @NotNull GlobalSearchScope scope) { final List results = new ArrayList<>(); final Collection files = FileBasedIndex.getInstance().getContainingFiles(NAME, shortName, scope); for (VirtualFile virtualFile : files) { @@ -118,7 +120,9 @@ public final class PyModuleNameIndex extends ScalarIndexExtension { * @param scope search scope, limiting applicable virtual files * @see QualifiedNameFinder#findImportableQNames(PsiElement, VirtualFile) */ - public static @NotNull List findByQualifiedName(@NotNull QualifiedName qName, @NotNull Project project, @NotNull GlobalSearchScope scope) { + public static @NotNull List findByQualifiedName(@NotNull QualifiedName qName, + @NotNull Project project, + @NotNull GlobalSearchScope scope) { String shortName = qName.getLastComponent(); if (shortName == null) return Collections.emptyList(); return ContainerUtil.filter(findByShortName(shortName, project, scope), file -> { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyNamedTupleStub.java b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyNamedTupleStub.java index 6bdbf40ef3fe..828953164295 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyNamedTupleStub.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/stubs/PyNamedTupleStub.java @@ -36,5 +36,6 @@ public interface PyNamedTupleStub extends CustomTargetExpressionStub { @NotNull LinkedHashMap getFields(); - record FieldTypeAndHasDefault(@Nullable String type, boolean hasDefault) {} + record FieldTypeAndHasDefault(@Nullable String type, boolean hasDefault) { + } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyABCUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyABCUtil.java index c2c211ee59c2..f35441356164 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyABCUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyABCUtil.java @@ -15,7 +15,6 @@ */ package com.jetbrains.python.psi.types; -import com.intellij.openapi.util.registry.Registry; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.PyClass; import org.jetbrains.annotations.NotNull; @@ -37,7 +36,10 @@ public final class PyABCUtil { return isSubclass(subClass, superClassName, true, context); } - public static boolean isSubclass(@NotNull PyClass subClass, @NotNull String superClassName, boolean inherited, @Nullable TypeEvalContext context) { + public static boolean isSubclass(@NotNull PyClass subClass, + @NotNull String superClassName, + boolean inherited, + @Nullable TypeEvalContext context) { if (PyNames.CALLABLE.equals(superClassName)) { return hasMethod(subClass, PyNames.CALL, inherited, context); } @@ -51,7 +53,8 @@ public final class PyABCUtil { } if (PyNames.ITERATOR.equals(superClassName)) { return (hasIter && (hasMethod(subClass, PyNames.NEXT, inherited, context) || hasMethod(subClass, - PyNames.DUNDER_NEXT, inherited, context))) || hasGetItem; + PyNames.DUNDER_NEXT, inherited, context))) || + hasGetItem; } final boolean isSized = hasMethod(subClass, PyNames.LEN, inherited, context); if (PyNames.SIZED.equals(superClassName)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableParameterImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableParameterImpl.java index ad4a8f5f0a5d..d6eb90bd4e33 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableParameterImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableParameterImpl.java @@ -174,7 +174,9 @@ public final class PyCallableParameterImpl implements PyCallableParameter { } @Override - public @NotNull String getPresentableText(boolean includeDefaultValue, @Nullable TypeEvalContext context, @NotNull Predicate typeFilter) { + public @NotNull String getPresentableText(boolean includeDefaultValue, + @Nullable TypeEvalContext context, + @NotNull Predicate typeFilter) { if (myElement instanceof PyNamedParameter || myElement == null) { final StringBuilder sb = new StringBuilder(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java index 1f3e94fba640..d7ee347dda0d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyCallableTypeImpl.java @@ -29,6 +29,7 @@ public class PyCallableTypeImpl implements PyCallableType { public PyCallableTypeImpl(@Nullable List parameters, @Nullable PyType returnType) { this(parameters, returnType, null, null, 0); } + public PyCallableTypeImpl(@Nullable List parameters, @Nullable PyType returnType, @Nullable PyCallable callable, diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java index 488873c02174..830a1b201d52 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyClassTypeImpl.java @@ -142,7 +142,8 @@ public class PyClassTypeImpl extends UserDataHolderBase implements PyClassType { boolean inherited) { final TypeEvalContext context = resolveContext.getTypeEvalContext(); PsiElement classMember = - resolveByOverridingMembersProviders(this, name, location, resolveContext); //overriding members provers have priority to normal resolve + resolveByOverridingMembersProviders(this, name, location, + resolveContext); //overriding members provers have priority to normal resolve if (classMember != null) { return ResolveResultList.to(classMember); } @@ -903,7 +904,8 @@ public class PyClassTypeImpl extends UserDataHolderBase implements PyClassType { return p1 != p2; } - private static @Nullable PyStatementPart findIfStatementPartByElement(@NotNull PsiElement element, @NotNull List parts) { + private static @Nullable PyStatementPart findIfStatementPartByElement(@NotNull PsiElement element, + @NotNull List parts) { return ContainerUtil.find(parts, part -> PsiTreeUtil.isAncestor(part, element, true)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyDescriptorTypeUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyDescriptorTypeUtil.java index 8cc28acde218..760667fb7406 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyDescriptorTypeUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyDescriptorTypeUtil.java @@ -71,7 +71,7 @@ public final class PyDescriptorTypeUtil { instanceTypeArgument = noneType; } List argumentTypes = List.of(instanceArgumentType, instanceTypeArgument); - PyType type = PySyntheticCallHelper.getCallTypeByFunctionName(PyNames.DUNDER_GET, receiverType, argumentTypes, context); + PyType type = PySyntheticCallHelper.getCallTypeByFunctionName(PyNames.DUNDER_GET, receiverType, argumentTypes, context); return Ref.create(type); } } @@ -119,5 +119,4 @@ public final class PyDescriptorTypeUtil { } return null; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyGenericType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyGenericType.java index 5355336941d4..619ce3815511 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyGenericType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyGenericType.java @@ -181,7 +181,8 @@ public class PyGenericType implements PyTypeVarType { } public @NotNull PyGenericType withScopeOwner(@Nullable PyQualifiedNameOwner scopeOwner) { - return new PyTypeVarTypeImpl(getName(), getConstraints(), getBound(), getDefaultType(), getVariance(), isDefinition(), getDeclarationElement(), scopeOwner); + return new PyTypeVarTypeImpl(getName(), getConstraints(), getBound(), getDefaultType(), getVariance(), isDefinition(), + getDeclarationElement(), scopeOwner); } public @NotNull PyGenericType withTargetExpression(@Nullable PyTargetExpression targetExpression) { @@ -189,16 +190,20 @@ public class PyGenericType implements PyTypeVarType { } public @NotNull PyGenericType withDeclarationElement(@Nullable PyQualifiedNameOwner declarationElement) { - return new PyTypeVarTypeImpl(getName(), getConstraints(), getBound(), getDefaultType(), getVariance(), isDefinition(), declarationElement, getScopeOwner()); + return new PyTypeVarTypeImpl(getName(), getConstraints(), getBound(), getDefaultType(), getVariance(), isDefinition(), + declarationElement, getScopeOwner()); } @Override public @NotNull PyGenericType toInstance() { - return myIsDefinition ? new PyTypeVarTypeImpl(myName, myConstraints, myBound, myDefaultType, myVariance, false, myDeclarationElement, myScopeOwner) : this; + return myIsDefinition ? new PyTypeVarTypeImpl(myName, myConstraints, myBound, myDefaultType, myVariance, false, myDeclarationElement, + myScopeOwner) : this; } @Override public @NotNull PyGenericType toClass() { - return myIsDefinition ? this : new PyTypeVarTypeImpl(myName, myConstraints, myBound, myDefaultType, myVariance, true, myDeclarationElement, myScopeOwner); + return myIsDefinition + ? this + : new PyTypeVarTypeImpl(myName, myConstraints, myBound, myDefaultType, myVariance, true, myDeclarationElement, myScopeOwner); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt index 11f77b07037b..e5229d98eb46 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt @@ -27,12 +27,12 @@ class PyLiteralType private constructor(cls: PyClass, val expression: PyExpressi } override fun hashCode(): Int = 31 * pyClass.hashCode() - + override fun acceptTypeVisitor(visitor: PyTypeVisitor): T? { if (visitor is PyTypeVisitorExt) { return visitor.visitPyLiteralType(this) } - return visitor.visitPyClassType(this) + return visitor.visitPyClassType(this) } companion object { @@ -114,7 +114,7 @@ class PyLiteralType private constructor(cls: PyClass, val expression: PyExpressi private fun promoteDictLiteralOrDictComprehension( expectedType: PyType?, anchor: PyElement, - elements: Collection + elements: Collection, ): PyType? { val (expectedKeyType, expectedValueType) = if (expectedType is PyCollectionType && expectedType.classQName == PyNames.DICT) { expectedType.elementTypes[0] to expectedType.elementTypes[1] @@ -160,7 +160,7 @@ class PyLiteralType private constructor(cls: PyClass, val expression: PyExpressi return expected.expression.name == actual.expression.name } return PyEvaluator.evaluateNoResolve(expected.expression, Any::class.java) == - PyEvaluator.evaluateNoResolve(actual.expression, Any::class.java) + PyEvaluator.evaluateNoResolve(actual.expression, Any::class.java) } /** @@ -168,10 +168,12 @@ class PyLiteralType private constructor(cls: PyClass, val expression: PyExpressi * then tries to infer `typing.Literal[...]` for [expression], * otherwise returns type inferred by [context]. */ - fun promoteToLiteral(expression: PyExpression, - expected: PyType?, - context: TypeEvalContext, - substitutions: PyTypeChecker.GenericSubstitutions?): PyType? { + fun promoteToLiteral( + expression: PyExpression, + expected: PyType?, + context: TypeEvalContext, + substitutions: PyTypeChecker.GenericSubstitutions?, + ): PyType? { val substitution = if (substitutions != null) PyTypeChecker.substitute(expected, substitutions, context) else expected val substitutionOrBound = if (substitution is PyTypeVarType) PyTypeUtil.getEffectiveBound(substitution) else substitution if (substitutionOrBound == null) return null diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyModuleType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyModuleType.java index 2de00493ec60..8d322f66e22d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyModuleType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyModuleType.java @@ -518,7 +518,8 @@ public class PyModuleType implements PyType { // Modules don't descend from obje return ContainerUtil.mapNotNull(elements, element -> { if (element instanceof PsiFileSystemItem) { - return buildFileLookupElement(location.getContainingFile(), (PsiFileSystemItem)element, existingNames); + return buildFileLookupElement(location.getContainingFile(), (PsiFileSystemItem)element, + existingNames); } else if (element instanceof PsiNamedElement) { return LookupElementBuilder.createWithIcon((PsiNamedElement)element); @@ -552,7 +553,9 @@ public class PyModuleType implements PyType { // Modules don't descend from obje return result; } - public static @Nullable LookupElementBuilder buildFileLookupElement(PsiFile file, PsiFileSystemItem item, @Nullable Set existingNames) { + public static @Nullable LookupElementBuilder buildFileLookupElement(PsiFile file, + PsiFileSystemItem item, + @Nullable Set existingNames) { final String s = FileUtilRt.getNameWithoutExtension(item.getName()); if (!PyNames.isIdentifier(s)) return null; if (existingNames != null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyNamedTupleType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyNamedTupleType.java index 684b26932c02..c63a7f5f5e69 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyNamedTupleType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyNamedTupleType.java @@ -20,12 +20,16 @@ import java.util.*; public class PyNamedTupleType extends PyTupleType implements PyCallableType { - private static final ImmutableSet PYTHON_2_ATTRIBUTES = ImmutableSet.of("_make", "_asdict", "_replace", "_fields", "_field_defaults", "_field_types"); - private static final ImmutableSet PYTHON_3_ATTRIBUTES = ImmutableSet.of("_make", "_asdict", "_replace", "_fields", "_field_defaults"); + private static final ImmutableSet PYTHON_2_ATTRIBUTES = + ImmutableSet.of("_make", "_asdict", "_replace", "_fields", "_field_defaults", "_field_types"); + private static final ImmutableSet PYTHON_3_ATTRIBUTES = + ImmutableSet.of("_make", "_asdict", "_replace", "_fields", "_field_defaults"); + public static @NotNull Set getSpecialAttributes(LanguageLevel level) { if (level.isPy3K()) { return PYTHON_3_ATTRIBUTES; - } else { + } + else { return PYTHON_2_ATTRIBUTES; } } @@ -66,7 +70,8 @@ public class PyNamedTupleType extends PyTupleType implements PyCallableType { Collections.addAll(result, super.getCompletionVariants(completionPrefix, location, context)); for (String field : myFields.keySet()) { - result.add(LookupElementBuilder.create(field).withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Field))); + result.add( + LookupElementBuilder.create(field).withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Field))); } if (completionPrefix == null) { @@ -203,7 +208,8 @@ public class PyNamedTupleType extends PyTupleType implements PyCallableType { return toInstance(); } - private static @NotNull PyCallableParameter fieldToCallableParameter(@NotNull String name, @NotNull FieldTypeAndDefaultValue typeAndDefaultValue) { + private static @NotNull PyCallableParameter fieldToCallableParameter(@NotNull String name, + @NotNull FieldTypeAndDefaultValue typeAndDefaultValue) { return PyCallableParameterImpl.nonPsi(name, typeAndDefaultValue.getType(), typeAndDefaultValue.getDefaultValue()); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PySyntheticCallHelper.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PySyntheticCallHelper.java index 8858ebb8a20b..6ff3c7f714b2 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PySyntheticCallHelper.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PySyntheticCallHelper.java @@ -79,9 +79,9 @@ public final class PySyntheticCallHelper { static @NotNull List resolveFunctionsByArgumentTypes(@NotNull String functionName, - @NotNull List argumentTypes, - @Nullable PyType receiverType, - @NotNull TypeEvalContext context) { + @NotNull List argumentTypes, + @Nullable PyType receiverType, + @NotNull TypeEvalContext context) { return matchOverloadsByArgumentTypes(resolveFunctionsByName(functionName, receiverType, context), argumentTypes, receiverType, context); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTupleType.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTupleType.java index edc365f4614d..57827b530d1f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTupleType.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTupleType.java @@ -39,7 +39,10 @@ public class PyTupleType extends PyClassTypeImpl implements PyCollectionType { this(tupleClass, elementTypes, homogeneous, false); } - protected PyTupleType(@NotNull PyClass tupleClass, @NotNull List elementTypes, boolean homogeneous, boolean isDefinition) { + protected PyTupleType(@NotNull PyClass tupleClass, + @NotNull List elementTypes, + boolean homogeneous, + boolean isDefinition) { super(tupleClass, isDefinition); myUnpackedTupleType = new PyUnpackedTupleTypeImpl(elementTypes, homogeneous); } @@ -106,13 +109,14 @@ public class PyTupleType extends PyClassTypeImpl implements PyCollectionType { public @Nullable PyType getIteratedItemType() { List types = myUnpackedTupleType.getElementTypes(); List unpackedTypes = ContainerUtil.map(types, type -> { - if (type instanceof PyUnpackedTupleType unpackedTupleType) { - assert unpackedTupleType.isUnbound(); - return unpackedTupleType.getElementTypes().get(0); - } else { - return type; - } - }); + if (type instanceof PyUnpackedTupleType unpackedTupleType) { + assert unpackedTupleType.isUnbound(); + return unpackedTupleType.getElementTypes().get(0); + } + else { + return type; + } + }); return PyUnionType.unionOrNever(unpackedTypes); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java index e2e1ecb1a1bf..8f78910a12eb 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeChecker.java @@ -1253,7 +1253,8 @@ public final class PyTypeChecker { PyType substitution = Ref.deref(substitutionRef); if (substitutionRef == null) { final PyInstantiableType invertedTypeVar = invert(typeVarType); - final PyInstantiableType invertedSubstitution = as(Ref.deref(substitutions.typeVars.get(invertedTypeVar)), PyInstantiableType.class); + final PyInstantiableType invertedSubstitution = + as(Ref.deref(substitutions.typeVars.get(invertedTypeVar)), PyInstantiableType.class); if (invertedSubstitution != null) { substitution = invert(invertedSubstitution); } @@ -1832,7 +1833,7 @@ public final class PyTypeChecker { @ApiStatus.Experimental public static class GenericSubstitutions { - + // Nullable-Nullable because of com.jetbrains.python.psi.types.PyTypeChecker.collectTypeSubstitutions private final @NotNull Map> typeVars; diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeCheckerExtension.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeCheckerExtension.java index 1e467ff04f97..867518bb6655 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeCheckerExtension.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeCheckerExtension.java @@ -39,9 +39,9 @@ public interface PyTypeCheckerExtension { */ @Deprecated(forRemoval = true) default @NotNull Optional match(@Nullable PyType expected, - @Nullable PyType actual, - @NotNull TypeEvalContext context, - @NotNull Map substitutions) { + @Nullable PyType actual, + @NotNull TypeEvalContext context, + @NotNull Map substitutions) { throw new UnsupportedOperationException(); } } \ No newline at end of file diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParameterMapping.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParameterMapping.java index 0d455286a1f5..6dd665a10027 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParameterMapping.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParameterMapping.java @@ -256,7 +256,7 @@ public final class PyTypeParameterMapping { // See https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes private static @NotNull List replaceExpectedTypesWithParameterList(@NotNull List expectedTypes, @NotNull List actualTypes) { - if (ContainerUtil.getOnlyItem(expectedTypes) instanceof PyParamSpecType && + if (ContainerUtil.getOnlyItem(expectedTypes) instanceof PyParamSpecType && !actualTypes.isEmpty() && !ContainerUtil.exists(actualTypes, o -> o instanceof PyVariadicType)) { PyCallableParameterListType callableParameterListType = new PyCallableParameterListTypeImpl(ContainerUtil.map(actualTypes, PyCallableParameterImpl::nonPsi)); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParser.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParser.java index 6607eea69917..f06c4b18b533 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParser.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeParser.java @@ -162,7 +162,10 @@ public final class PyTypeParser { * @param context type evaluation context * @param fqnOnly if true, resolves names using only fully-qualified lookup (ignores local scope/imported aliases) */ - public static @NotNull ParseResult parse(@NotNull PsiElement anchor, @NotNull String type, @NotNull TypeEvalContext context, boolean fqnOnly) { + public static @NotNull ParseResult parse(@NotNull PsiElement anchor, + @NotNull String type, + @NotNull TypeEvalContext context, + boolean fqnOnly) { PyPsiUtils.assertValid(anchor); final ForwardDeclaration typeExpr = ForwardDeclaration.create(); @@ -427,12 +430,13 @@ public final class PyTypeParser { final Token firstToken = tokens.get(0); final String firstText = firstToken.getText().toString(); final TextRange firstRange = firstToken.getRange(); - + final List resolveResults; if (myFqnOnly) { // First, try to resolve from "typing" for unqualified names (e.g., Literal, Any) final var qNameContext = PyResolveImportUtil.fromFoothold(myAnchor); - final PsiElement typingMember = PyResolveImportUtil.resolveTopLevelMember(QualifiedName.fromDottedString("typing." + firstText), qNameContext); + final PsiElement typingMember = + PyResolveImportUtil.resolveTopLevelMember(QualifiedName.fromDottedString("typing." + firstText), qNameContext); if (typingMember != null) { resolveResults = Collections.singletonList(new RatedResolveResult(RatedResolveResult.RATE_NORMAL, typingMember)); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeTokenTypes.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeTokenTypes.java index 23d10869b8dc..0438a465ae6d 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeTokenTypes.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeTokenTypes.java @@ -18,7 +18,7 @@ package com.jetbrains.python.psi.types; import com.jetbrains.python.psi.PyElementType; public final class PyTypeTokenTypes { - private PyTypeTokenTypes() {} + private PyTypeTokenTypes() { } public static final PyElementType NL = new PyElementType("NL"); public static final PyElementType SPACE = new PyElementType("SPACE"); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeUtil.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeUtil.java index c3737433e39d..410f2067a3c8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypeUtil.java @@ -85,9 +85,9 @@ public final class PyTypeUtil { * Returns members of certain type from {@link PyClassLikeType}. */ public static @NotNull List getMembersOfType(final @NotNull PyClassLikeType type, - final @NotNull Class expectedMemberType, - boolean inherited, - final @NotNull TypeEvalContext context) { + final @NotNull Class expectedMemberType, + boolean inherited, + final @NotNull TypeEvalContext context) { final List result = new ArrayList<>(); type.visitMembers(t -> { @@ -104,9 +104,10 @@ public final class PyTypeUtil { /** * Search for data in dataholder or members of union recursively + * * @param type start point - * @param key key to search - * @param result tyoe + * @param key key to search + * @param result tyoe * @return data or null if not found */ public static @Nullable T findData(final @NotNull PyType type, final @NotNull Key key) { @@ -184,7 +185,7 @@ public final class PyTypeUtil { public static @NotNull Collector, ?, Ref> toUnionFromRef(@Nullable PyType streamSource) { return toUnionFromRef(streamSource instanceof PyUnsafeUnionType ? PyUnsafeUnionType::unsafeUnion : PyUnionType::union); } - + private static @NotNull Collector, ?, Ref> toUnionFromRef(@NotNull BinaryOperator unionReduction) { return Collectors.reducing(null, (accType, hintType) -> { if (hintType == null) { @@ -247,7 +248,7 @@ public final class PyTypeUtil { new PyClassTypeImpl(superClass, false)); return PyTypeChecker.convertToType(type, superClassType, context); } - + public static boolean inheritsAny(@NotNull PyType type, @NotNull TypeEvalContext context) { return type instanceof PyClassLikeType classLikeType && classLikeType.getAncestorTypes(context).contains(null); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt index bef897d6cca0..300465eb3a7b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt @@ -14,13 +14,13 @@ import java.util.* class PyTypedDictType @JvmOverloads constructor( private val name: String, val fields: Map, - + private val dictClass: PyClass, private val definitionLevel: DefinitionLevel, private val ancestors: List, private val declaration: PyQualifiedNameOwner? = null, ) : - PyClassTypeImpl(dictClass, definitionLevel != DefinitionLevel.INSTANCE){ + PyClassTypeImpl(dictClass, definitionLevel != DefinitionLevel.INSTANCE) { fun getElementType(key: String): PyType? { return fields[key]?.type } @@ -112,7 +112,11 @@ class PyTypedDictType @JvmOverloads constructor( */ data class TypedDictFieldQualifiers(val isRequired: Boolean? = true, val isReadOnly: Boolean = false) - data class FieldTypeAndTotality(val value: PyExpression?, val type: PyType?, val qualifiers: TypedDictFieldQualifiers = TypedDictFieldQualifiers()) { + data class FieldTypeAndTotality( + val value: PyExpression?, + val type: PyType?, + val qualifiers: TypedDictFieldQualifiers = TypedDictFieldQualifiers(), + ) { val isRequired: Boolean get() = qualifiers.isRequired ?: true val isReadOnly: Boolean get() = qualifiers.isReadOnly } diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypingNewType.kt b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypingNewType.kt index 9ec4d735ea8b..fc6dd24cc09b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypingNewType.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypingNewType.kt @@ -6,9 +6,11 @@ import com.jetbrains.python.psi.* import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.RatedResolveResult -class PyTypingNewType(private val classType: PyClassType, - private val name: String, - private val declaration: PyTargetExpression?) : PyClassType by classType { +class PyTypingNewType( + private val classType: PyClassType, + private val name: String, + private val declaration: PyTargetExpression?, +) : PyClassType by classType { override fun getName(): String = name diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyUnpackedTupleTypeImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyUnpackedTupleTypeImpl.java index b0122e23c27f..5b2b07d8e790 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyUnpackedTupleTypeImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/PyUnpackedTupleTypeImpl.java @@ -27,7 +27,8 @@ public final class PyUnpackedTupleTypeImpl implements PyUnpackedTupleType { throw new IllegalArgumentException("Unbounded unpacked tuple type of a TypeVarTuple or another unpacked tuple type is now allowed"); } myElementTypes = new ArrayList<>(elementTypes); - } else { + } + else { myElementTypes = unpackElementTypes(elementTypes).toList(); } myIsHomogeneous = isUnbound; @@ -37,7 +38,8 @@ public final class PyUnpackedTupleTypeImpl implements PyUnpackedTupleType { return types.stream().flatMap(type -> { if (type instanceof PyUnpackedTupleType unpackedTupleType && !unpackedTupleType.isUnbound()) { return unpackElementTypes(unpackedTupleType.getElementTypes()); - } else { + } + else { return Stream.of(type); } }); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/TypeEvalContextCacheImpl.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/TypeEvalContextCacheImpl.java index d4047ac432b8..41ab792af1c7 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/TypeEvalContextCacheImpl.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/TypeEvalContextCacheImpl.java @@ -43,7 +43,8 @@ final class TypeEvalContextCacheImpl implements TypeEvalContextCache { // This method is called if cache is empty. Create new map for it. // Concurrent map allows several threads to call get and put, so it is thread safe but not atomic final ConcurrentMap map = ContainerUtil.createConcurrentSoftValueMap(); - return new CachedValueProvider.Result<>(map, PyLibraryModificationTracker.Companion.getInstance(project), myLowMemoryModificationTracker); + return new CachedValueProvider.Result<>(map, PyLibraryModificationTracker.Companion.getInstance(project), + myLowMemoryModificationTracker); } }); diff --git a/python/python-psi-impl/src/com/jetbrains/python/psi/types/functionalParser/FunctionalParserBase.java b/python/python-psi-impl/src/com/jetbrains/python/psi/types/functionalParser/FunctionalParserBase.java index 8f9606ca0541..6f72ab2b9fe1 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/psi/types/functionalParser/FunctionalParserBase.java +++ b/python/python-psi-impl/src/com/jetbrains/python/psi/types/functionalParser/FunctionalParserBase.java @@ -193,8 +193,8 @@ public abstract class FunctionalParserBase implements FunctionalParser extends FunctionalParserBase { - private final @NotNull FunctionalParserBase myFirst; - private final @NotNull FunctionalParser mySecond; + private final @NotNull FunctionalParserBase myFirst; + private final @NotNull FunctionalParser mySecond; OrParser(@NotNull FunctionalParserBase first, @NotNull FunctionalParser second) { myFirst = first; diff --git a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiClassMembersProvider.java b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiClassMembersProvider.java index a3d25becfd4f..824d23a86f5e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiClassMembersProvider.java +++ b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiClassMembersProvider.java @@ -22,7 +22,9 @@ import java.util.List; public final class PyiClassMembersProvider extends PyClassMembersProviderBase implements PyOverridingAncestorsClassMembersProvider { @Override - public @NotNull Collection getMembers(@NotNull PyClassType classType, PsiElement location, @NotNull TypeEvalContext context) { + public @NotNull Collection getMembers(@NotNull PyClassType classType, + PsiElement location, + @NotNull TypeEvalContext context) { final PyClass cls = classType.getPyClass(); final PsiElement pythonStub = PyiUtil.getPythonStub(cls); if (pythonStub instanceof PyClass) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt index 21e85dca1c7e..6cbc96a5e4c2 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiFile.kt @@ -49,10 +49,12 @@ class PyiFile(viewProvider: FileViewProvider) : PyFileImpl(viewProvider, PyiLang baseResults } - override fun processDeclarations(processor: PsiScopeProcessor, - resolveState: ResolveState, - lastParent: PsiElement?, - place: PsiElement): Boolean { + override fun processDeclarations( + processor: PsiScopeProcessor, + resolveState: ResolveState, + lastParent: PsiElement?, + place: PsiElement, + ): Boolean { val dunderAll = dunderAll ?: emptyList() val completingInPyiStub = PyiUtil.isInsideStub(place) val wrapper = object : DelegatingScopeProcessor(processor) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiUtil.java b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiUtil.java index 059f6e49f78b..1d33f8033b8a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/pyi/PyiUtil.java @@ -39,7 +39,7 @@ import java.util.Comparator; import java.util.List; public final class PyiUtil { - private PyiUtil() {} + private PyiUtil() { } public static boolean isInsideStub(@NotNull PsiElement element) { return PyiUtilCore.isInsideStub(element); @@ -79,7 +79,7 @@ public final class PyiUtil { if (originalFile == null) return null; PsiElement result = findSimilarElement(element, originalFile); - + // If a name is defined in a .pyi stub and the corresponding .py module in a different manner, e.g. // it's exported through an assignment to a top-level attribute in a .pyi stub, but though a regular // "from" import in .py file, we might end up in another stub file again. It happens because resolving @@ -155,10 +155,10 @@ public final class PyiUtil { } final PyQualifiedNameResolveContext context = PyResolveImportUtil.fromFoothold(file); return PyUtil.as(PyResolveImportUtil.resolveQualifiedName(name, context) - .stream() - .findFirst() - .map(PyUtil::turnDirIntoInitPyi) - .orElse(null), PyiFile.class); + .stream() + .findFirst() + .map(PyUtil::turnDirIntoInitPyi) + .orElse(null), PyiFile.class); } private static @Nullable PyFile getOriginalFile(@NotNull PyiFile file) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyDefUseUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyDefUseUtil.java index 542f2930fd07..ec77ef9536a6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyDefUseUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyDefUseUtil.java @@ -70,7 +70,7 @@ public final class PyDefUseUtil { if (startNum < 0) { return Collections.emptyList(); } - + QualifiedName varQname = QualifiedName.fromDottedString(varName); LanguageLevel languageLevel = PyLanguageFacadeKt.getEffectiveLanguageLevel(anchor.getContainingFile()); @@ -100,7 +100,8 @@ public final class PyDefUseUtil { } if (instruction.num() < startNum && acceptTypeAssertions && instruction instanceof ConditionalInstruction conditionalInstruction) { - if (conditionalInstruction.getCondition() instanceof PyTypedElement typedElement && context.getOrigin() == typedElement.getContainingFile()) { + if (conditionalInstruction.getCondition() instanceof PyTypedElement typedElement && + context.getOrigin() == typedElement.getContainingFile()) { var newContext = (MAX_CONTROL_FLOW_SIZE > instructions.length) ? TypeEvalContext.codeAnalysis(context.getOrigin().getProject(), context.getOrigin()) : TypeEvalContext.codeInsightFallback(context.getOrigin().getProject()); @@ -125,14 +126,14 @@ public final class PyDefUseUtil { acceptTypeAssertions && access.isAssertTypeAccess() && instruction.num() < startNum) { final String name = rwInstruction.getName(); - + if (name != null && isQualifiedBy(varQname, name)) { - if (isReachableWithVersionChecks(rwInstruction, languageLevel)){ + if (isReachableWithVersionChecks(rwInstruction, languageLevel)) { foundPrefixWrite.set(true); return ControlFlowUtil.Operation.BREAK; } } - + if (Comparing.strEqual(name, varName)) { if (isReachableWithVersionChecks(rwInstruction, languageLevel)) { result.add(rwInstruction); @@ -284,7 +285,8 @@ public final class PyDefUseUtil { ControlFlowUtil.iteratePrev(index, instructions, instruction -> { if (instruction.getElement() == searched) { boolean isImport = searched instanceof PyImportedNameDefiner; - boolean isWriteAccess = instruction instanceof ReadWriteInstruction && ((ReadWriteInstruction)instruction).getAccess().isWriteAccess(); + boolean isWriteAccess = + instruction instanceof ReadWriteInstruction && ((ReadWriteInstruction)instruction).getAccess().isWriteAccess(); if (isImport || isWriteAccess) { definedBefore.set(true); return ControlFlowUtil.Operation.BREAK; diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyPsiRefactoringUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyPsiRefactoringUtil.java index 8cd4545d19a4..52245dd490b8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyPsiRefactoringUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyPsiRefactoringUtil.java @@ -82,22 +82,22 @@ public final class PyPsiRefactoringUtil { * @return actually inserted element as for {@link PsiElement#add(PsiElement)} */ public static @NotNull PsiElement addElementToStatementList(@NotNull PsiElement element, - @NotNull PyStatementList statementList, - boolean toTheBeginning) { + @NotNull PyStatementList statementList, + boolean toTheBeginning) { final PsiElement prevElem = PyPsiUtils.getPrevNonWhitespaceSibling(statementList); // If statement list is on the same line as previous element (supposedly colon), move its only statement on the next line if (prevElem != null && PyUtilCore.onSameLine(statementList, prevElem)) { - final PsiDocumentManager manager = PsiDocumentManager.getInstance(statementList.getProject()); - final Document document = statementList.getContainingFile().getFileDocument(); - final PyStatementListContainer container = (PyStatementListContainer)statementList.getParent(); - manager.doPostponedOperationsAndUnblockDocument(document); - final String indentation = "\n" + PyIndentUtil.getElementIndent(statementList); - // If statement list was empty initially, we need to add some anchor statement ("pass"), so that preceding new line was not - // parsed as following entire StatementListContainer (e.g. function). It's going to be replaced anyway. - final String text = statementList.getStatements().length == 0 ? indentation + PyNames.PASS : indentation; - document.insertString(statementList.getTextRange().getStartOffset(), text); - manager.commitDocument(document); - statementList = container.getStatementList(); + final PsiDocumentManager manager = PsiDocumentManager.getInstance(statementList.getProject()); + final Document document = statementList.getContainingFile().getFileDocument(); + final PyStatementListContainer container = (PyStatementListContainer)statementList.getParent(); + manager.doPostponedOperationsAndUnblockDocument(document); + final String indentation = "\n" + PyIndentUtil.getElementIndent(statementList); + // If statement list was empty initially, we need to add some anchor statement ("pass"), so that preceding new line was not + // parsed as following entire StatementListContainer (e.g. function). It's going to be replaced anyway. + final String text = statementList.getStatements().length == 0 ? indentation + PyNames.PASS : indentation; + document.insertString(statementList.getTextRange().getStartOffset(), text); + manager.commitDocument(document); + statementList = container.getStatementList(); } final PsiElement firstChild = statementList.getFirstChild(); if (firstChild == statementList.getLastChild() && firstChild instanceof PyPassStatement) { @@ -171,7 +171,8 @@ public final class PyPsiRefactoringUtil { for (PyFunction function : PyTypeUtil.getMembersOfType(type, PyFunction.class, false, context)) { final String name = function.getName(); if (name != null) { - if (!functions.containsKey(name) || PyiUtil.isOverload(functions.get(name), context) && !PyiUtil.isOverload(function, context)) { + if (!functions.containsKey(name) || + PyiUtil.isOverload(functions.get(name), context) && !PyiUtil.isOverload(function, context)) { functions.put(name, function); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUiService.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUiService.java index 4b6eb7777f9a..29d8e6cb1f12 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUiService.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUiService.java @@ -29,7 +29,9 @@ import java.util.function.Consumer; public class PyRefactoringUiService { public void performIntroduceWithDialog(IntroduceOperation operation, @NlsContexts.DialogTitle String dialogTitle, - IntroduceValidator validator, String id, Consumer performRefactoringCallback) { + IntroduceValidator validator, + String id, + Consumer performRefactoringCallback) { } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java index 6ae259e892e4..3836e3a3a1a8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyRefactoringUtil.java @@ -50,7 +50,8 @@ public final class PyRefactoringUtil { if (text != null && expr.getStringNodes().size() == 1) { final int start = text.indexOf(substring); if (start >= 0) { - element.putUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE, Pair.create(element, TextRange.from(start, substring.length()))); + element.putUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE, + Pair.create(element, TextRange.from(start, substring.length()))); occurrences.add(element); return; } @@ -85,15 +86,15 @@ public final class PyRefactoringUtil { } // If it is PyIfPart for example, parent if statement, we should deny - if (!(parent instanceof PyExpression)){ + if (!(parent instanceof PyExpression)) { return null; } // We cannot extract anything within import statements - if (PsiTreeUtil.getParentOfType(parent, PyImportStatement.class, PyFromImportStatement.class) != null){ + if (PsiTreeUtil.getParentOfType(parent, PyImportStatement.class, PyFromImportStatement.class) != null) { return null; } if ((element1 == PsiTreeUtil.getDeepestFirst(parent)) && (element2 == PsiTreeUtil.getDeepestLast(parent))) { - return (PyExpression) parent; + return (PyExpression)parent; } // Check if selection breaks AST node in binary expression @@ -282,11 +283,16 @@ public final class PyRefactoringUtil { return selectUniqueName(templateName, false, scopeAnchor, PyRefactoringUtil::isValidNewName); } - public static @NotNull String selectUniqueName(@NotNull String templateName, @NotNull PsiElement scopeAnchor, @NotNull BiPredicate isValid) { + public static @NotNull String selectUniqueName(@NotNull String templateName, + @NotNull PsiElement scopeAnchor, + @NotNull BiPredicate isValid) { return selectUniqueName(templateName, false, scopeAnchor, isValid); } - private static @NotNull String selectUniqueName(@NotNull String templateName, boolean templateIsType, @NotNull PsiElement scopeAnchor, @NotNull BiPredicate isValid) { + private static @NotNull String selectUniqueName(@NotNull String templateName, + boolean templateIsType, + @NotNull PsiElement scopeAnchor, + @NotNull BiPredicate isValid) { final Collection suggestions; if (templateIsType) { suggestions = NameSuggesterUtil.generateNamesByType(templateName); @@ -309,10 +315,12 @@ public final class PyRefactoringUtil { * * @param name initial name * @param scopeAnchor PSI element used to determine correct scope - * @param predicate used to test if suggested name is valid + * @param predicate used to test if suggested name is valid * @return unique name in the scope probably with number suffix appended */ - public static @NotNull String appendNumberUntilValid(@NotNull String name, @NotNull PsiElement scopeAnchor, @NotNull BiPredicate predicate) { + public static @NotNull String appendNumberUntilValid(@NotNull String name, + @NotNull PsiElement scopeAnchor, + @NotNull BiPredicate predicate) { int counter = 1; String candidate = name; while (!predicate.test(candidate, scopeAnchor)) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java index ed056b09b41f..26755a1cc77f 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/PyReplaceExpressionUtil.java @@ -54,7 +54,7 @@ public final class PyReplaceExpressionUtil implements PyElementTypes { public static final Key> SELECTION_BREAKS_AST_NODE = new Key<>("python.selection.breaks.ast.node"); - private PyReplaceExpressionUtil() {} + private PyReplaceExpressionUtil() { } /** * @param oldExpr old expression that will be substituted @@ -433,7 +433,9 @@ public final class PyReplaceExpressionUtil implements PyElementTypes { int priority = 0; if (expr instanceof PyReferenceExpression || expr instanceof PySubscriptionExpression || - expr instanceof PyCallExpression) priority = 1; + expr instanceof PyCallExpression) { + priority = 1; + } else if (expr instanceof PyPrefixExpression) { final IElementType opType = getOperationType(expr); if (opType == AWAIT_KEYWORD) priority = 2; @@ -442,9 +444,9 @@ public final class PyReplaceExpressionUtil implements PyElementTypes { } else if (expr instanceof PyBinaryExpression) { final IElementType opType = getOperationType(expr); - if (opType == EXP) priority = 4; - if (opType == MULT || opType == AT || opType == DIV || opType == PERC || opType == FLOORDIV) priority = 5; - if (opType == PLUS || opType == MINUS) priority = 6; + if (opType == EXP) priority = 4; + if (opType == MULT || opType == AT || opType == DIV || opType == PERC || opType == FLOORDIV) priority = 5; + if (opType == PLUS || opType == MINUS) priority = 6; if (opType == LTLT || opType == GTGT) priority = 7; if (opType == AND) priority = 8; if (opType == XOR) priority = 9; @@ -453,8 +455,12 @@ public final class PyReplaceExpressionUtil implements PyElementTypes { if (opType == AND_KEYWORD) priority = 13; if (opType == OR_KEYWORD) priority = 14; } - else if (expr instanceof PyConditionalExpression) priority = 15; - else if (expr instanceof PyLambdaExpression) priority = 16; + else if (expr instanceof PyConditionalExpression) { + priority = 15; + } + else if (expr instanceof PyLambdaExpression) { + priority = 16; + } else if (expr instanceof PyAssignmentExpression) priority = 17; return -priority; diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java index f502225a0af7..671dab69813a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java @@ -58,15 +58,15 @@ public final class PyClassRefactoringUtil { /** * Copies class field declarations to some other place * - * @param assignmentStatements list of class fields - * @param dequalifyIfDeclaredInClass If not null method will check if field declared in this class. - * If declared -- qualifier will be removed. - * For example: MyClass.Foo will become Foo it this param is MyClass. + * @param assignmentStatements list of class fields + * @param dequalifyIfDeclaredInClass If not null method will check if field declared in this class. + * If declared -- qualifier will be removed. + * For example: MyClass.Foo will become Foo it this param is MyClass. * @return new (copied) fields */ public static @NotNull List copyFieldDeclarationToStatement(final @NotNull Collection assignmentStatements, - final @NotNull PyStatementList superClassStatement, - final @Nullable PyClass dequalifyIfDeclaredInClass) { + final @NotNull PyStatementList superClassStatement, + final @Nullable PyClass dequalifyIfDeclaredInClass) { final List declarations = new ArrayList<>(assignmentStatements.size()); for (final PyAssignmentStatement pyAssignmentStatement : assignmentStatements) { @@ -77,7 +77,6 @@ public final class PyClassRefactoringUtil { final String newValue = getNewValueToAssign((PyReferenceExpression)value, dequalifyIfDeclaredInClass); setNewAssigneeValue(newDeclaration, newValue); - } declarations.add(PyPsiRefactoringUtil.addElementToStatementList(newDeclaration, superClassStatement)); @@ -88,27 +87,32 @@ public final class PyClassRefactoringUtil { /** * Sets new value to assignment statement. + * * @param assignmentStatement statement to change - * @param newValue new value + * @param newValue new value */ private static void setNewAssigneeValue(final @NotNull PyAssignmentStatement assignmentStatement, final @NotNull String newValue) { final PyExpression oldValue = assignmentStatement.getAssignedValue(); final PyExpression newExpression = - PyElementGenerator.getInstance(assignmentStatement.getProject()).createExpressionFromText(LanguageLevel.forElement(assignmentStatement), newValue); + PyElementGenerator.getInstance(assignmentStatement.getProject()) + .createExpressionFromText(LanguageLevel.forElement(assignmentStatement), newValue); if (oldValue != null) { oldValue.replace(newExpression); - } else { + } + else { assignmentStatement.add(newExpression); } } /** * Checks if current value declared in provided class and removes class qualifier if true - * @param currentValue current value - * @param dequalifyIfDeclaredInClass class to check + * + * @param currentValue current value + * @param dequalifyIfDeclaredInClass class to check * @return value as string */ - private static @NotNull String getNewValueToAssign(final @NotNull PyReferenceExpression currentValue, final @NotNull PyClass dequalifyIfDeclaredInClass) { + private static @NotNull String getNewValueToAssign(final @NotNull PyReferenceExpression currentValue, + final @NotNull PyClass dequalifyIfDeclaredInClass) { final PyExpression qualifier = currentValue.getQualifier(); if ((qualifier instanceof PyReferenceExpression) && ((PyReferenceExpression)qualifier).getReference().isReferenceTo(dequalifyIfDeclaredInClass)) { @@ -126,7 +130,9 @@ public final class PyClassRefactoringUtil { * @param skipIfExist do not add anything if method already exists * @return newly added methods or existing one (if skipIfExists is true and method already exists) */ - public static @NotNull List addMethods(final @NotNull PyClass destination, final boolean skipIfExist, final PyFunction @NotNull ... methods) { + public static @NotNull List addMethods(final @NotNull PyClass destination, + final boolean skipIfExist, + final PyFunction @NotNull ... methods) { final PyStatementList destStatementList = destination.getStatementList(); final List result = new ArrayList<>(methods.length); @@ -197,7 +203,7 @@ public final class PyClassRefactoringUtil { newElement.putCopyableUserData(ENCODED_FROM_FUTURE_IMPORTS, null); PsiFile destFile = newElement.getContainingFile(); if (fromFutureImports != null & destFile != null) { - for (FutureFeature futureFeature: fromFutureImports) { + for (FutureFeature futureFeature : fromFutureImports) { AddImportHelper.addOrUpdateFromImportStatement(destFile, PyNames.FUTURE_MODULE, futureFeature.toString(), null, AddImportHelper.ImportPriority.FUTURE, null); } @@ -364,7 +370,7 @@ public final class PyClassRefactoringUtil { private static @NotNull Set collectFromFutureImports(@NotNull PyFile file) { EnumSet result = EnumSet.noneOf(FutureFeature.class); - for (FutureFeature feature: FutureFeature.values()) { + for (FutureFeature feature : FutureFeature.values()) { if (file.hasImportFromFuture(feature)) { result.add(feature); } @@ -431,7 +437,8 @@ public final class PyClassRefactoringUtil { /** * Forces the use of 'import as' when restoring references (i.e. if there are name clashes) - * @param node with encoded import + * + * @param node with encoded import * @param asName new alias for import */ public static void forceAsName(@NotNull PyReferenceExpression node, @NotNull String asName) { @@ -462,7 +469,7 @@ public final class PyClassRefactoringUtil { * * @param importStatement parent import statement that contains reference to given element * @param element PSI element reference to which should be updated - * @return whether import statement was actually updated + * @return whether import statement was actually updated */ public static boolean updateUnqualifiedImportOfElement(@NotNull PyImportStatementBase importStatement, @NotNull PsiNamedElement element) { final String name = PyPsiRefactoringUtil.getOriginalName(element); @@ -514,7 +521,8 @@ public final class PyClassRefactoringUtil { } - public static PsiFile placeFile(@NotNull Project project, @NotNull String path, @NotNull String filename, boolean isNamespace) throws IOException { + public static PsiFile placeFile(@NotNull Project project, @NotNull String path, @NotNull String filename, boolean isNamespace) + throws IOException { return placeFile(project, path, filename, null, isNamespace); } @@ -523,7 +531,11 @@ public final class PyClassRefactoringUtil { * * @return the placed file */ - public static PsiFile placeFile(@NotNull Project project, @NotNull String path, @NotNull String filename, @Nullable String content, boolean isNamespace) throws IOException { + public static PsiFile placeFile(@NotNull Project project, + @NotNull String path, + @NotNull String filename, + @Nullable String content, + boolean isNamespace) throws IOException { PsiDirectory psiDir = createDirectories(project, path, isNamespace); LOG.assertTrue(psiDir != null); PsiFile psiFile = psiDir.findFile(filename); @@ -544,10 +556,11 @@ public final class PyClassRefactoringUtil { /** * Create all intermediate dirs with inits from one of roots up to target dir. * - * @param target a full path to target dir + * @param target a full path to target dir * @return deepest child directory, or null if target is not in roots or process fails at some point. */ - private static @Nullable PsiDirectory createDirectories(@NotNull Project project, @NotNull String target, boolean isNamespace) throws IOException { + private static @Nullable PsiDirectory createDirectories(@NotNull Project project, @NotNull String target, boolean isNamespace) + throws IOException { String relativePath = null; VirtualFile closestRoot = null; @@ -620,13 +633,13 @@ public final class PyClassRefactoringUtil { properties.setProperty("NAME", FileUtilRt.getNameWithoutExtension(file.getName())); final String content = template.getText(properties); psi = PyClassRefactoringUtil.placeFile(project, - StringUtil.notNullize( - file.getParent(), - baseDir != null ? baseDir - .getPath() : "." - ), - file.getName(), - content, isNamespace + StringUtil.notNullize( + file.getParent(), + baseDir != null ? baseDir + .getPath() : "." + ), + file.getName(), + content, isNamespace ); } catch (IOException e) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java index 6de938a32e60..27cf99e0a695 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/extractSuperclass/PyExtractSuperclassHelper.java @@ -58,9 +58,9 @@ public final class PyExtractSuperclassHelper { @ApiStatus.Internal public static void extractSuperclass(final PyClass clazz, - @NotNull Collection> selectedMemberInfos, - final String superBaseName, - final String targetFile) { + @NotNull Collection> selectedMemberInfos, + final String superBaseName, + final String targetFile) { final Project project = clazz.getProject(); //We will need to change it probably while param may be read-only @@ -81,7 +81,8 @@ public final class PyExtractSuperclassHelper { if (objectMember != null) { selectedMemberInfos.remove(objectMember); } - } else { + } + else { // Always add object if < Py3 if (objectMember == null) { final PyMemberInfo object = MembersManager.findMember(clazz, ALLOW_OBJECT); @@ -96,7 +97,7 @@ public final class PyExtractSuperclassHelper { newClass = placeNewClass(project, newClass, clazz, targetFile); MembersManager.moveAllMembers(selectedMemberInfos, clazz, newClass); - if (! newClass.getContainingFile().equals(clazz.getContainingFile())) { + if (!newClass.getContainingFile().equals(clazz.getContainingFile())) { PyClassRefactoringUtil.optimizeImports(clazz.getContainingFile()); // To remove unneeded imports only if user used different file } PyPsiRefactoringUtil.addSuperclasses(project, clazz, null, newClass); @@ -119,8 +120,11 @@ public final class PyExtractSuperclassHelper { return file instanceof BackedVirtualFile && Comparing.equal(((BackedVirtualFile)file).getOriginFile(), targetFile); } - - private static PyClass placeNewClass(final @NotNull Project project, @NotNull PyClass newClass, final @NotNull PyClass clazz, final @NotNull String targetFile) { + + private static PyClass placeNewClass(final @NotNull Project project, + @NotNull PyClass newClass, + final @NotNull PyClass clazz, + final @NotNull String targetFile) { VirtualFile file = VirtualFileManager.getInstance() .findFileByUrl(ApplicationManager.getApplication().isUnitTestMode() ? targetFile : VfsUtilCore.pathToUrl(targetFile)); // file is the same as the source @@ -166,11 +170,7 @@ public final class PyExtractSuperclassHelper { } - - - public static String getRefactoringId() { return "refactoring.python.extract.superclass"; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/FieldsManager.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/FieldsManager.java index eead63391eb0..141f88542196 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/FieldsManager.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/FieldsManager.java @@ -78,7 +78,7 @@ abstract class FieldsManager extends MembersManager { final @NotNull Collection> members, final PyClass @NotNull ... to) { return moveAssignments(from, Collections2 - .filter(Collections2.transform(fetchElements(members), ASSIGNMENT_TRANSFORM), NotNullPredicate.INSTANCE), + .filter(Collections2.transform(fetchElements(members), ASSIGNMENT_TRANSFORM), NotNullPredicate.INSTANCE), to); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/InstanceFieldsManager.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/InstanceFieldsManager.java index b009b96fb05b..2b89ac5f6510 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/InstanceFieldsManager.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/InstanceFieldsManager.java @@ -59,7 +59,7 @@ class InstanceFieldsManager extends FieldsManager { * @return newly created fields */ private static @NotNull List copyInstanceFields(final @NotNull Collection members, - final @NotNull PyClass to) { + final @NotNull PyClass to) { //We need __init__ method, and if there is no any -- we need to create it PyFunction toInitMethod = PyUtil.getInitMethod(to); if (toInitMethod == null) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java index 4c068915ad13..d91e221c92a0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MembersManager.java @@ -71,7 +71,7 @@ public abstract class MembersManager implements Function> transformSafely(final @NotNull PyClass pyClass, - final @NotNull MembersManager manager) { + final @NotNull MembersManager manager) { final List membersCouldBeMoved = manager.getMembersCouldBeMoved(pyClass); manager.checkElementTypes((Iterable)membersCouldBeMoved); return (Collection>)Collections2.transform(membersCouldBeMoved, (Function)manager); @@ -124,7 +124,7 @@ public abstract class MembersManager implements Function findMember(final @NotNull Collection> members, - final @NotNull Predicate> predicate) { + final @NotNull Predicate> predicate) { for (final PyMemberInfo pyMemberInfo : members) { if (predicate.apply(pyMemberInfo)) { return pyMemberInfo; @@ -141,7 +141,7 @@ public abstract class MembersManager implements Function findMember(final @NotNull PyClass pyClass, - final @NotNull Predicate> predicate) { + final @NotNull Predicate> predicate) { return findMember(getAllMembersCouldBeMoved(pyClass), predicate); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java index 9a5c177bb2fd..80dce41cccc9 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/MethodsManager.java @@ -125,13 +125,13 @@ class MethodsManager extends MembersManager { * @param from source * @param methodsToMove what to move * @param to where - * @param skipIfExist skip (do not add) if method already exists + * @param skipIfExist skip (do not add) if method already exists * @return newly added methods */ static List moveMethods(@NotNull PyClass from, @NotNull Collection methodsToMove, boolean skipIfExist, - PyClass @NotNull... to) { + PyClass @NotNull ... to) { if (methodsToMove.isEmpty() || to.length == 0) return Collections.emptyList(); final List result = new ArrayList<>(); for (PyClass destClass : to) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/NamelessFilter.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/NamelessFilter.java index d4cc2d822bb3..7f9163ea95c6 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/NamelessFilter.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/NamelessFilter.java @@ -25,8 +25,8 @@ import org.jetbrains.annotations.NotNull; * that are null or has null name. * You need it sometimes when code has errors (i.e. bad formatted code with annotation may treat annotation as method with null name. * -* @author Ilya.Kazakevich -*/ + * @author Ilya.Kazakevich + */ class NamelessFilter extends NotNullPredicate { @Override diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/SuperClassesManager.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/SuperClassesManager.java index 911ff242222f..362be283c352 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/SuperClassesManager.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/classes/membersManager/SuperClassesManager.java @@ -61,11 +61,13 @@ final class SuperClassesManager extends MembersManager { /** * Returns superclass expressions that are resolved to one or more classes from collection - * @param from class to get superclass expressions from + * + * @param from class to get superclass expressions from * @param classes classes to check superclasses against * @return collection of expressions that are resolved to one or more class from classes param */ - private static @NotNull List getExpressionsBySuperClass(final @NotNull PyClass from, final @NotNull Collection classes) { + private static @NotNull List getExpressionsBySuperClass(final @NotNull PyClass from, + final @NotNull Collection classes) { final List expressionsToDelete = new ArrayList<>(classes.size()); for (final PyExpression expression : from.getSuperClassExpressions()) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodHandler.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodHandler.java index 21e17ea1b8be..e2020d5d53ef 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodHandler.java @@ -152,7 +152,7 @@ public class PyExtractMethodHandler implements RefactoringActionHandler { final PsiElement statement1 = PyPsiUtils.getParentRightBefore(element1, statementList); final PsiElement statement2 = PyPsiUtils.getParentRightBefore(element2, statementList); - if (statement1 == null || statement2 == null){ + if (statement1 == null || statement2 == null) { return null; } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java index 6335351ed01c..5405f508dc2a 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/extractmethod/PyExtractMethodUtil.java @@ -108,7 +108,7 @@ public final class PyExtractMethodUtil { final SimpleDuplicatesFinder finder = new SimpleDuplicatesFinder(statement1, statement2, fragment.getOutputVariables(), variableData); - CommandProcessor.getInstance().executeCommand(project, () -> { + CommandProcessor.getInstance().executeCommand(project, () -> { final RefactoringEventData beforeData = new RefactoringEventData(); beforeData.addElements(new PsiElement[]{statement1, statement2}); project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC) @@ -181,7 +181,8 @@ public final class PyExtractMethodUtil { SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); if (processDuplicates) { - pointers.addAll(ContainerUtil.map(duplicates, p -> pointerManager.createSmartPsiFileRangePointer(file, p.getStartElement().getTextRange()))); + pointers.addAll( + ContainerUtil.map(duplicates, p -> pointerManager.createSmartPsiFileRangePointer(file, p.getStartElement().getTextRange()))); } processDuplicatesAndAddImports(project, editor, processDuplicates, pointers, methodSettings, insertedMethod, @@ -378,7 +379,8 @@ public final class PyExtractMethodUtil { PsiFile file = expression.getContainingFile(); SmartPointerManager pointerManager = SmartPointerManager.getInstance(project); if (processDuplicates) { - pointers.addAll(ContainerUtil.map(duplicates, p -> pointerManager.createSmartPsiFileRangePointer(file, p.getStartElement().getTextRange()))); + pointers.addAll( + ContainerUtil.map(duplicates, p -> pointerManager.createSmartPsiFileRangePointer(file, p.getStartElement().getTextRange()))); } if (callElement != null) { insertedCallElement = WriteAction.compute(() -> PyReplaceExpressionUtil.replaceExpression(expression, callElement)); @@ -716,7 +718,8 @@ public final class PyExtractMethodUtil { if (ApplicationManager.getApplication().isUnitTestMode()) { throw new CommonRefactoringUtil.RefactoringErrorHintException(error); } - if (!MessageDialogBuilder.okCancel(RefactoringBundle.message("warning.title"), error + ". " + RefactoringBundle.message("do.you.wish.to.continue")). + if (!MessageDialogBuilder.okCancel(RefactoringBundle.message("warning.title"), + error + ". " + RefactoringBundle.message("do.you.wish.to.continue")). icon(UIUtil.getWarningIcon()).ask(project)) { throw new CommonRefactoringUtil.RefactoringErrorHintException(error); } @@ -830,5 +833,4 @@ public final class PyExtractMethodUtil { boolean selected = PropertiesComponent.getInstance(project).getBoolean(ADD_TYPE_ANNOTATIONS_VALUE_KEY, ADD_TYPE_ANNOTATIONS_DEFAULT); return selected; } - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt index e4fd076962ce..e0b4f8ece96b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionHandler.kt @@ -37,7 +37,8 @@ class PyInlineFunctionHandler : InlineActionHandler() { override fun canInlineElement(element: PsiElement?): Boolean { if (element is PyFunction) { - val containingFile = if (element.containingFile is PyiFile) PyiUtil.getOriginalElement(element)?.containingFile else element.containingFile + val containingFile = if (element.containingFile is PyiFile) PyiUtil.getOriginalElement(element)?.containingFile + else element.containingFile return containingFile is PyFile } return false @@ -47,8 +48,10 @@ class PyInlineFunctionHandler : InlineActionHandler() { invoke(project, editor, element) } - fun invoke(project: Project?, editor: Editor?, element: PsiElement?, showDialog: Boolean = true, - inlineThisOnly: Boolean = false) { + fun invoke( + project: Project?, editor: Editor?, element: PsiElement?, showDialog: Boolean = true, + inlineThisOnly: Boolean = false, + ) { if (project == null || editor == null || element !is PyFunction) return val functionScope = ControlFlowCache.getScope(element) val error = when { @@ -84,11 +87,12 @@ class PyInlineFunctionHandler : InlineActionHandler() { } private fun isSpecialMethod(function: PyFunction): Boolean { - return function.containingClass != null && function.name != null && + return function.containingClass != null && function.name != null && PyNames.getBuiltinMethods(LanguageLevel.forElement(function)).contains(function.name) } - private fun hasNestedFunction(function: PyFunction): Boolean = SyntaxTraverser.psiTraverser(function.statementList).traverse().any { it is PyFunction } + private fun hasNestedFunction(function: PyFunction): Boolean = + SyntaxTraverser.psiTraverser(function.statementList).traverse().any { it is PyFunction } private fun hasNonExhaustiveIfs(function: PyFunction): Boolean { val returns = mutableListOf() @@ -125,7 +129,7 @@ class PyInlineFunctionHandler : InlineActionHandler() { private fun checkLastStatement(statementList: PyStatementList, cache: MutableSet): Boolean { val statements = statementList.statements if (statements.isEmpty()) return true - when(val last = statements.last()) { + when (val last = statements.last()) { is PyIfStatement -> if (checkInterruptsControlFlow(last, cache)) return true !is PyReturnStatement -> return true } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionProcessor.kt b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionProcessor.kt index c23052e8f978..f19726cbb4fb 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionProcessor.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineFunctionProcessor.kt @@ -38,12 +38,14 @@ import org.jetbrains.annotations.PropertyKey /** * @author Aleksei.Kniazev */ -class PyInlineFunctionProcessor(project: Project, - private val myEditor: Editor, - private val myFunction: PyFunction, - private val myReference: PsiReference?, - private val myInlineThisOnly: Boolean, - removeDeclaration: Boolean) : BaseRefactoringProcessor(project) { +class PyInlineFunctionProcessor( + project: Project, + private val myEditor: Editor, + private val myFunction: PyFunction, + private val myReference: PsiReference?, + private val myInlineThisOnly: Boolean, + removeDeclaration: Boolean, +) : BaseRefactoringProcessor(project) { private val myFunctionClass = myFunction.containingClass private val myGenerator = PyElementGenerator.getInstance(myProject) @@ -67,7 +69,7 @@ class PyInlineFunctionProcessor(project: Project, } else { val callExpression = element.parent as PyCallExpression - if (callExpression.arguments.any { it is PyStarArgument}) { + if (callExpression.arguments.any { it is PyStarArgument }) { if (!handleUsageError(element, "refactoring.inline.function.uses.unpacking", conflicts)) return false return@filter false } @@ -156,8 +158,10 @@ class PyInlineFunctionProcessor(project: Project, val generatedNames = mutableSetOf() - val callSite = PsiTreeUtil.getParentOfType(reference, PyCallExpression::class.java) ?: error("Unable to find call expression for ${reference.name}") - val containingStatement = PsiTreeUtil.getParentOfType(callSite, PyStatement::class.java) ?: error("Unable to find statement for ${reference.name}") + val callSite = PsiTreeUtil.getParentOfType(reference, PyCallExpression::class.java) + ?: error("Unable to find call expression for ${reference.name}") + val containingStatement = PsiTreeUtil.getParentOfType(callSite, PyStatement::class.java) + ?: error("Unable to find statement for ${reference.name}") val scopeAnchor = if (containingStatement is PyFunction) containingStatement else reference val functionCopy = myFunction.copy() as PyFunction @@ -215,7 +219,7 @@ class PyInlineFunctionProcessor(project: Project, override fun visitPyReferenceExpression(node: PyReferenceExpression) { if (!node.isQualified) { val parentLambda = PsiTreeUtil.getParentOfType(node, PyLambdaExpression::class.java) - if (parentLambda == null || parentLambda.parameterList.parameters.none { it.name == node.name }) { + if (parentLambda == null || parentLambda.parameterList.parameters.none { it.name == node.name }) { when (val name = node.name) { in mappedArguments -> argumentReplacements[node] = mappedArguments[name]!! in nameClashes -> nameClashRefs.putValue(name!!, node) @@ -244,11 +248,11 @@ class PyInlineFunctionProcessor(project: Project, nameClashRefs.entrySet().forEach { (name, elements) -> val generated = generateUniqueAssignment(languageLevel, name, generatedNames, scopeAnchor) elements.forEach { - when (it) { - is PyTargetExpression -> it.replace(generated.targets[0]) - is PyReferenceExpression -> it.replace(generated.assignedValue!!) - } + when (it) { + is PyTargetExpression -> it.replace(generated.targets[0]) + is PyReferenceExpression -> it.replace(generated.assignedValue!!) } + } } importAsRefs.entrySet().forEach { (name, elements) -> @@ -286,7 +290,7 @@ class PyInlineFunctionProcessor(project: Project, } } } - else if (returnStatements.isNotEmpty()) { + else if (returnStatements.isNotEmpty()) { val newReturn = generateUniqueAssignment(languageLevel, "result", generatedNames, scopeAnchor) returnStatements.forEach { val copy = newReturn.copy() as PyAssignmentStatement @@ -377,8 +381,10 @@ class PyInlineFunctionProcessor(project: Project, } } - private fun prepareArguments(callSite: PyCallExpression, declarations: MutableList, generatedNames: MutableSet, scopeAnchor: PsiElement, - reference: PyReferenceExpression, languageLevel: LanguageLevel, context: PyResolveContext, selfUsed: Boolean): Map { + private fun prepareArguments( + callSite: PyCallExpression, declarations: MutableList, generatedNames: MutableSet, scopeAnchor: PsiElement, + reference: PyReferenceExpression, languageLevel: LanguageLevel, context: PyResolveContext, selfUsed: Boolean, + ): Map { val mapping = callSite.mapArguments(context).firstOrNull() ?: error("Can't map arguments for ${reference.name}") val mappedParams = mapping.mappedParameters val firstImplicit = mapping.implicitParameters.firstOrNull() @@ -409,16 +415,20 @@ class PyInlineFunctionProcessor(project: Project, return self + passedArguments + defaultValues } - private fun tryExtractDeclaration(paramName: String, arg: PyExpression, declarations: MutableList, generatedNames: MutableSet, - scopeAnchor: PsiElement, languageLevel: LanguageLevel): Pair { + private fun tryExtractDeclaration( + paramName: String, arg: PyExpression, declarations: MutableList, generatedNames: MutableSet, + scopeAnchor: PsiElement, languageLevel: LanguageLevel, + ): Pair { if (arg !is PyReferenceExpression && arg !is PyLiteralExpression) { return extractDeclaration(paramName, arg, declarations, generatedNames, scopeAnchor, languageLevel) } return paramName to arg } - private fun extractDeclaration(paramName: String, arg: PyExpression, declarations: MutableList, generatedNames: MutableSet, - scopeAnchor: PsiElement, languageLevel: LanguageLevel): Pair { + private fun extractDeclaration( + paramName: String, arg: PyExpression, declarations: MutableList, generatedNames: MutableSet, + scopeAnchor: PsiElement, languageLevel: LanguageLevel, + ): Pair { val statement = generateUniqueAssignment(languageLevel, paramName, generatedNames, scopeAnchor) statement.assignedValue!!.replace(arg) declarations.add(statement) diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java index 7baf3ee37951..a3f10ee790d8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/inline/PyInlineLocalHandler.java @@ -240,7 +240,7 @@ public final class PyInlineLocalHandler extends InlineActionHandler { PsiElement[] refsToInline; if (replaceJustOneOccurrence && refExpr != null) { - refsToInline = new PsiElement[] { refExpr }; + refsToInline = new PsiElement[]{refExpr}; } else { refsToInline = PyDefUseUtil.getPostRefs(containerBlock, local, getObject(def)); @@ -276,7 +276,8 @@ public final class PyInlineLocalHandler extends InlineActionHandler { for (final PsiElement ref : refsToInline) { final List elems = new ArrayList<>(); - final List latestDefs = PyDefUseUtil.getLatestDefs(containerBlock, local.getName(), ref, false, false, TypeEvalContext.codeInsightFallback(project)); + final List latestDefs = + PyDefUseUtil.getLatestDefs(containerBlock, local.getName(), ref, false, false, TypeEvalContext.codeInsightFallback(project)); for (Instruction i : latestDefs) { elems.add(i.getElement()); } @@ -384,7 +385,8 @@ public final class PyInlineLocalHandler extends InlineActionHandler { PyTargetExpression local, Project project) { if (expr != null) { try { - final List candidates = PyDefUseUtil.getLatestDefs(containerBlock, local.getName(), expr, true, true, TypeEvalContext.codeInsightFallback(project)); + final List candidates = + PyDefUseUtil.getLatestDefs(containerBlock, local.getName(), expr, true, true, TypeEvalContext.codeInsightFallback(project)); if (candidates.size() == 1) { final PyStatement expression = getAssignmentByLeftPart((PyElement)candidates.get(0).getElement()); return Pair.create(expression, false); diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java index 7a525ec89b14..1b4d0943d8a5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceHandler.java @@ -46,7 +46,10 @@ import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.resolve.PyResolveUtil; -import com.jetbrains.python.psi.types.*; +import com.jetbrains.python.psi.types.PyCallableParameter; +import com.jetbrains.python.psi.types.PyLiteralStringType; +import com.jetbrains.python.psi.types.PyType; +import com.jetbrains.python.psi.types.TypeEvalContext; import com.jetbrains.python.refactoring.NameSuggesterUtil; import com.jetbrains.python.refactoring.PyRefactoringUiService; import com.jetbrains.python.refactoring.PyRefactoringUtil; @@ -474,7 +477,7 @@ public abstract class IntroduceHandler implements RefactoringActionHandler { performActionOnElementOccurrences(operation); } - protected void showCanNotIntroduceErrorHint(@NotNull Project project, @NotNull Editor editor) {} + protected void showCanNotIntroduceErrorHint(@NotNull Project project, @NotNull Editor editor) { } protected void performActionOnElementOccurrences(final IntroduceOperation operation) { final Editor editor = operation.getEditor(); @@ -621,7 +624,7 @@ public abstract class IntroduceHandler implements RefactoringActionHandler { protected abstract String getHelpId(); protected PyAssignmentStatement createDeclaration(Project project, String assignmentText, PsiElement anchor) { - LanguageLevel langLevel = ((PyFile) anchor.getContainingFile()).getLanguageLevel(); + LanguageLevel langLevel = ((PyFile)anchor.getContainingFile()).getLanguageLevel(); return PyElementGenerator.getInstance(project).createFromText(langLevel, PyAssignmentStatement.class, assignmentText); } @@ -701,6 +704,4 @@ public abstract class IntroduceHandler implements RefactoringActionHandler { protected void postRefactoring(PsiElement element) { } - - } diff --git a/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceValidator.java b/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceValidator.java index 51d652c25abc..002b260759ad 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceValidator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/refactoring/introduce/IntroduceValidator.java @@ -49,7 +49,7 @@ public abstract class IntroduceValidator { public static boolean isDefinedInScope(String name, PsiElement psiElement) { if (psiElement.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE) != null) { - final Pair data = psiElement.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); + final Pair data = psiElement.getUserData(PyReplaceExpressionUtil.SELECTION_BREAKS_AST_NODE); psiElement = data.first; } PsiElement context = PsiTreeUtil.getParentOfType(psiElement, PyFunction.class); diff --git a/python/python-psi-impl/src/com/jetbrains/python/sdk/skeleton/PySkeletonUtil.java b/python/python-psi-impl/src/com/jetbrains/python/sdk/skeleton/PySkeletonUtil.java index 7ed32d44b82f..01eeac9e91fa 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/sdk/skeleton/PySkeletonUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/sdk/skeleton/PySkeletonUtil.java @@ -149,7 +149,8 @@ public final class PySkeletonUtil { private static @NotNull String mapToRemote(@NotNull String localRoot, @NotNull Sdk sdk) { return PythonRuntimeService.getInstance().mapToRemote(localRoot, sdk); } - /** + + /** * @return name of builtins skeleton file; for Python 2.x it is '{@code __builtins__.py}'. */ diff --git a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlow.kt b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlow.kt index 84b822ac2302..a9c7b07c78fe 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlow.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlow.kt @@ -19,10 +19,10 @@ private val LAYOUT_PER_VERSION: List>> = "keras" to "keras._tf_keras.keras", // losses, metrics, optimizers, initializers should be covered by the content of // typeshed/stubs/tensorflow/tensorflow/keras - "initializers" to "keras._tf_keras.keras.initializers", - "losses" to "keras._tf_keras.keras.losses", - "metrics" to "keras._tf_keras.keras.metrics", - "optimizers" to "keras._tf_keras.keras.optimizers", + "initializers" to "keras._tf_keras.keras.initializers", + "losses" to "keras._tf_keras.keras.losses", + "metrics" to "keras._tf_keras.keras.metrics", + "optimizers" to "keras._tf_keras.keras.optimizers", "security" to "tensorflow.security", "*" to "tensorflow._api.v2", ), @@ -90,5 +90,6 @@ private data class VersionRange(val minIncluded: String?, val maxExcluded: Strin minIncluded?.let { pyRequirementVersionSpec(PyRequirementRelation.GTE, minIncluded) }, maxExcluded?.let { pyRequirementVersionSpec(PyRequirementRelation.LT, maxExcluded) }, ) + operator fun contains(version: String): Boolean = versionSpecs.all { it.matches(version) } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowImportResolver.kt b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowImportResolver.kt index 33a961911b60..8a2f664976f4 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowImportResolver.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowImportResolver.kt @@ -22,9 +22,11 @@ class PyTensorFlowImportResolver : PyImportResolver { private fun isTensorFlowMember(name: QualifiedName) = name.firstComponent == "tensorflow" && name.componentCount > 1 - private fun resolveImportReference(name: QualifiedName, - context: PyQualifiedNameResolveContext, - pathConfig: Map): PsiElement? { + private fun resolveImportReference( + name: QualifiedName, + context: PyQualifiedNameResolveContext, + pathConfig: Map, + ): PsiElement? { val path = pathConfig[name.components[1]] if (path != null) { return takeFirstResolvedInTensorFlow("$path.${name.removeHead(2)}", context) diff --git a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowModuleMembersProvider.kt b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowModuleMembersProvider.kt index 38e5f03583b6..48394154f218 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowModuleMembersProvider.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/tensorFlow/PyTensorFlowModuleMembersProvider.kt @@ -40,8 +40,10 @@ class PyTensorFlowModuleMembersProvider : PyModuleMembersProvider() { return QualifiedNameFinder.findShortestImportableQName(module).let { it != null && it.matches("tensorflow") } } - private fun getMembers(context: PyQualifiedNameResolveContext, - pathConfig: Map): Collection { + private fun getMembers( + context: PyQualifiedNameResolveContext, + pathConfig: Map, + ): Collection { val result = mutableListOf() pathConfig.filterKeys { it != "*" }.mapNotNullTo(result) { (module, path) -> @@ -58,9 +60,11 @@ class PyTensorFlowModuleMembersProvider : PyModuleMembersProvider() { return result } - private fun resolveMember(name: String, - context: PyQualifiedNameResolveContext, - pathConfig: Map): PsiElement? { + private fun resolveMember( + name: String, + context: PyQualifiedNameResolveContext, + pathConfig: Map, + ): PsiElement? { if (name in pathConfig) { return takeFirstResolvedInTensorFlow(pathConfig.getValue(name), context) } diff --git a/python/python-psi-impl/src/com/jetbrains/python/testing/PythonUnitTestDetectors.kt b/python/python-psi-impl/src/com/jetbrains/python/testing/PythonUnitTestDetectors.kt index 50cdf6c3dfb1..1f020601ec3e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/testing/PythonUnitTestDetectors.kt +++ b/python/python-psi-impl/src/com/jetbrains/python/testing/PythonUnitTestDetectors.kt @@ -37,7 +37,8 @@ fun isTestFunction(function: PyFunction): Boolean { * Inheritor of TestCase class is always test for unittest and could also be launched with pytest. * See `PythonUnitTestDetectorsBasedOnSettings.isTestFunction`. */ -fun isUnitTestCaseClass(clazz: PyClass, context: TypeEvalContext): Boolean = clazz.inherits(context, "unittest.TestCase", "unittest.case.TestCase") +fun isUnitTestCaseClass(clazz: PyClass, context: TypeEvalContext): Boolean = + clazz.inherits(context, "unittest.TestCase", "unittest.case.TestCase") /** * Checks if class [isUnitTestCaseClass] or both conditions are true: it's name starts/ends with "Test" and it has at least one @@ -70,8 +71,10 @@ fun isTestClass(clazz: PyClass, context: TypeEvalContext): Boolean { } } -fun isTestFile(file: PyFile, - context: TypeEvalContext): Boolean { +fun isTestFile( + file: PyFile, + context: TypeEvalContext, +): Boolean { return if (file.topLevelClasses.any { o: PyClass -> isTestClass(o, context) }) { diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyAnnotator.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyAnnotator.java index e971cda8729d..60f865ddeaf0 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyAnnotator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyAnnotator.java @@ -60,8 +60,8 @@ public abstract class PyAnnotator extends PyElementVisitor { } protected void addHighlightingAnnotation(@NotNull PsiElement target, - @NotNull TextAttributesKey key, - @NotNull HighlightSeverity severity) { + @NotNull TextAttributesKey key, + @NotNull HighlightSeverity severity) { _holder.addHighlightingAnnotation(target, key, severity); } diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyAssignTargetAnnotatorVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyAssignTargetAnnotatorVisitor.java index b4ae6d0079ee..1f8f41836dc8 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyAssignTargetAnnotatorVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyAssignTargetAnnotatorVisitor.java @@ -112,7 +112,8 @@ public class PyAssignTargetAnnotatorVisitor extends PyElementVisitor { @Override public void visitPyAssignmentExpression(@NotNull PyAssignmentExpression node) { - final PyComprehensionElement comprehensionElement = PsiTreeUtil.getParentOfType(node, PyComprehensionElement.class, true, ScopeOwner.class); + final PyComprehensionElement comprehensionElement = + PsiTreeUtil.getParentOfType(node, PyComprehensionElement.class, true, ScopeOwner.class); if (ScopeUtil.getScopeOwner(comprehensionElement) instanceof PyClass) { getHolder().newAnnotation(HighlightSeverity.ERROR, message("ANN.assignment.expressions.within.a.comprehension.cannot.be.used.in.a.class.body")).create(); @@ -250,12 +251,14 @@ public class PyAssignTargetAnnotatorVisitor extends PyElementVisitor { @Override public void visitPyDictCompExpression(@NotNull PyDictCompExpression node) { - getHolder().markError(node, message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.dict.comprh" : "ANN.cant.assign.to.dict.comprh")); + getHolder().markError(node, + message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.dict.comprh" : "ANN.cant.assign.to.dict.comprh")); } @Override public void visitPySetCompExpression(@NotNull PySetCompExpression node) { - getHolder().markError(node, message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.set.comprh" : "ANN.cant.assign.to.set.comprh")); + getHolder().markError(node, + message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.set.comprh" : "ANN.cant.assign.to.set.comprh")); } @Override @@ -287,7 +290,9 @@ public class PyAssignTargetAnnotatorVisitor extends PyElementVisitor { } private void checkLiteral(@NotNull PsiElement node) { - getHolder().newAnnotation(HighlightSeverity.ERROR, message(myOp == Operation.Delete ? "ANN.cant.delete.literal" : "ANN.cant.assign.to.literal")).range(node).create(); + getHolder().newAnnotation(HighlightSeverity.ERROR, + message(myOp == Operation.Delete ? "ANN.cant.delete.literal" : "ANN.cant.assign.to.literal")).range(node) + .create(); } @Override diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyCompatibilityVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyCompatibilityVisitor.java index 2e451a0bc0be..dc06cdd85028 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyCompatibilityVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyCompatibilityVisitor.java @@ -49,7 +49,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { private static final @NotNull Set PYTHON36_PREFIXES = Sets.newHashSet("R", "U", "B", "BR", "RB", "F", "FR", "RF"); - private static final @NotNull Set PYTHON314_PREFIXES = Sets.newHashSet("R", "U", "B", "BR", "RB", "F", "FR", "RF", "T", "TR", "RT"); + private static final @NotNull Set PYTHON314_PREFIXES = + Sets.newHashSet("R", "U", "B", "BR", "RB", "F", "FR", "RF", "T", "TR", "RT"); protected final @NotNull List myVersionsToProcess; @@ -79,10 +80,11 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { } if (element != null && ",".equals(element.getText())) { - registerForAllMatchingVersions(level -> level.isPy3K() && level.isOlderThan(LanguageLevel.PYTHON314) && registerForLanguageLevel(level), - PyPsiBundle.message("INSP.compatibility.feature.support.this.syntax"), - node, - new ReplaceExceptPartQuickFix()); + registerForAllMatchingVersions( + level -> level.isPy3K() && level.isOlderThan(LanguageLevel.PYTHON314) && registerForLanguageLevel(level), + PyPsiBundle.message("INSP.compatibility.feature.support.this.syntax"), + node, + new ReplaceExceptPartQuickFix()); } } PsiElement star = PyPsiUtils.getFirstChildOfType(node, PyTokenTypes.MULT); @@ -141,7 +143,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { registerForAllMatchingVersions(level -> level.isAtLeast(LanguageLevel.PYTHON35) && level.isOlderThan(LanguageLevel.PYTHON38) && registerForLanguageLevel(level), - PyPsiBundle.message("INSP.compatibility.feature.support.unpacking.without.parentheses.in.return.statements"), + PyPsiBundle.message( + "INSP.compatibility.feature.support.unpacking.without.parentheses.in.return.statements"), node); } @@ -149,7 +152,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { registerForAllMatchingVersions(level -> level.isAtLeast(LanguageLevel.PYTHON35) && level.isOlderThan(LanguageLevel.PYTHON38) && registerForLanguageLevel(level), - PyPsiBundle.message("INSP.compatibility.feature.support.unpacking.without.parentheses.in.yield.statements"), + PyPsiBundle.message( + "INSP.compatibility.feature.support.unpacking.without.parentheses.in.yield.statements"), node); } @@ -545,7 +549,7 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { LocalQuickFix @NotNull ... fixes) { final List levels = ContainerUtil.filter(myVersionsToProcess, levelPredicate::test); if (!levels.isEmpty()) { - @NlsSafe String versions = StringUtil.join(levels,", "); + @NlsSafe String versions = StringUtil.join(levels, ", "); @InspectionMessage String message = PyPsiBundle.message("INSP.compatibility.inspection.unsupported.feature.prefix", levels.size(), versions, suffix); registerProblem(node, range, message, asError, fixes); @@ -555,7 +559,7 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { protected void registerForAllMatchingVersions(@NotNull Predicate levelPredicate, @NotNull @Nls String suffix, @NotNull PsiElement node, - LocalQuickFix @NotNull... fixes) { + LocalQuickFix @NotNull ... fixes) { registerForAllMatchingVersions(levelPredicate, suffix, node, node.getTextRange(), true, fixes); } @@ -612,7 +616,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { } else { if (seenKeywordArgument) { - registerProblem(argument, PyPsiBundle.message("INSP.compatibility.positional.argument.after.keyword.argument"), new PyRemoveArgumentQuickFix()); + registerProblem(argument, PyPsiBundle.message("INSP.compatibility.positional.argument.after.keyword.argument"), + new PyRemoveArgumentQuickFix()); } else if (seenPositionalContainer) { registerForAllMatchingVersions(level -> level.isOlderThan(LanguageLevel.PYTHON35) && registerForLanguageLevel(level), @@ -621,7 +626,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { new PyRemoveArgumentQuickFix()); } else if (seenKeywordContainer) { - registerProblem(argument, PyPsiBundle.message("INSP.compatibility.positional.argument.after.kwargs"), new PyRemoveArgumentQuickFix()); + registerProblem(argument, PyPsiBundle.message("INSP.compatibility.positional.argument.after.kwargs"), + new PyRemoveArgumentQuickFix()); } } } @@ -784,7 +790,8 @@ public abstract class PyCompatibilityVisitor extends PyElementVisitor { super.visitPyDecorator(decorator); if (PsiTreeUtil.getChildOfType(decorator, PsiErrorElement.class) == null && decorator.getQualifiedName() == null) { registerForAllMatchingVersions(level -> level.isOlderThan(LanguageLevel.PYTHON39) && registerForLanguageLevel(level), - PyPsiBundle.message("INSP.compatibility.feature.support.arbitrary.expressions.as.decorator"), decorator); + PyPsiBundle.message("INSP.compatibility.feature.support.arbitrary.expressions.as.decorator"), + decorator); } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyGlobalAnnotatorVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyGlobalAnnotatorVisitor.java index da20bc01a4ff..ad955775710e 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyGlobalAnnotatorVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyGlobalAnnotatorVisitor.java @@ -55,7 +55,8 @@ public class PyGlobalAnnotatorVisitor extends PyElementVisitor { for (PyTargetExpression expr : node.getGlobals()) { final String expr_name = expr.getReferencedName(); if (paramNames.contains(expr_name)) { - myHolder.newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.name.used.both.as.global.and.param", expr_name)).range(expr).create(); + myHolder.newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.name.used.both.as.global.and.param", expr_name)) + .range(expr).create(); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyParameterListAnnotatorVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyParameterListAnnotatorVisitor.java index b65d43f96179..1dcb9932154b 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyParameterListAnnotatorVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyParameterListAnnotatorVisitor.java @@ -50,6 +50,7 @@ public class PyParameterListAnnotatorVisitor extends PyElementVisitor { boolean hadSingleStar = false; boolean hadParamsAfterSingleStar = false; int inTuple = 0; + @Override public void visitNamedParameter(PyNamedParameter parameter, boolean first, boolean last) { final var name = parameter.getName(); diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyReturnYieldAnnotatorVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyReturnYieldAnnotatorVisitor.java index f175f643f351..90f0bd96da35 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyReturnYieldAnnotatorVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyReturnYieldAnnotatorVisitor.java @@ -39,7 +39,7 @@ public class PyReturnYieldAnnotatorVisitor extends PyElementVisitor { if (function.isAsync() && function.isAsyncAllowed()) { myHolder.newAnnotation(HighlightSeverity.ERROR, - PyPsiBundle.message("ANN.python.does.not.support.yield.from.inside.async.functions")).create(); + PyPsiBundle.message("ANN.python.does.not.support.yield.from.inside.async.functions")).create(); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/PyTypeAnnotationTargetAnnotatorVisitor.java b/python/python-psi-impl/src/com/jetbrains/python/validation/PyTypeAnnotationTargetAnnotatorVisitor.java index ac3eabcaf6a7..f1da15f2514c 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/PyTypeAnnotationTargetAnnotatorVisitor.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/PyTypeAnnotationTargetAnnotatorVisitor.java @@ -54,10 +54,12 @@ public class PyTypeAnnotationTargetAnnotatorVisitor extends PyElementVisitor { final PyExpression innerExpr = PyPsiUtils.flattenParens(expression); if (innerExpr instanceof PyTupleExpression || innerExpr instanceof PyListLiteralExpression) { myHolder.newAnnotation(HighlightSeverity.ERROR, - PyPsiBundle.message("ANN.variable.annotation.cannot.be.combined.with.tuple.unpacking")).range(innerExpr).create(); + PyPsiBundle.message("ANN.variable.annotation.cannot.be.combined.with.tuple.unpacking")).range(innerExpr) + .create(); } else if (innerExpr != null && !(innerExpr instanceof PyTargetExpression || innerExpr instanceof PySubscriptionExpression)) { - myHolder.newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.illegal.target.for.variable.annotation")).range(innerExpr).create(); + myHolder.newAnnotation(HighlightSeverity.ERROR, PyPsiBundle.message("ANN.illegal.target.for.variable.annotation")).range(innerExpr) + .create(); } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/validation/UnsupportedFeaturesUtil.java b/python/python-psi-impl/src/com/jetbrains/python/validation/UnsupportedFeaturesUtil.java index 41b8541a817a..8ea6f71abcf5 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/validation/UnsupportedFeaturesUtil.java +++ b/python/python-psi-impl/src/com/jetbrains/python/validation/UnsupportedFeaturesUtil.java @@ -143,7 +143,7 @@ public final class UnsupportedFeaturesUtil { MODULES.put(LanguageLevel.fromPythonVersion(attr.getValue("version")), new HashSet<>()); myCurrentLevel = LanguageLevel.fromPythonVersion(attr.getValue("version")); } - } + } @Override public void endElement(String namespaceURI, @@ -159,7 +159,7 @@ public final class UnsupportedFeaturesUtil { @Override public void characters(char[] ch, int start, int length) - throws SAXException { + throws SAXException { myContent.write(ch, start, length); } } @@ -179,15 +179,15 @@ public final class UnsupportedFeaturesUtil { myClassName = attr.getValue("name"); if (!CLASS_METHODS.containsKey(myClassName)) { CLASS_METHODS.put(myClassName, new HashMap<>()); - } } if (localName.equals("python")) { myCurrentLevel = LanguageLevel.fromPythonVersion(attr.getValue("version")); if (myClassName != null) { final Map> map = CLASS_METHODS.get(myClassName); - if (map != null) + if (map != null) { map.put(myCurrentLevel, new HashSet<>()); + } } } } @@ -200,8 +200,9 @@ public final class UnsupportedFeaturesUtil { Map> levelSetMap = CLASS_METHODS.get(myClassName); if (levelSetMap != null) { final Set set = levelSetMap.get(myCurrentLevel); - if (set != null) + if (set != null) { set.add(myContent.toString()); + } } } } diff --git a/python/python-psi-impl/src/com/jetbrains/python/vp/Creator.java b/python/python-psi-impl/src/com/jetbrains/python/vp/Creator.java index d0dabe3e4954..0d8429fc9392 100644 --- a/python/python-psi-impl/src/com/jetbrains/python/vp/Creator.java +++ b/python/python-psi-impl/src/com/jetbrains/python/vp/Creator.java @@ -22,9 +22,9 @@ import org.jetbrains.annotations.NotNull; * Creates view and presenter allowing them to have links to each other. * Implement it and pass to {@link ViewPresenterUtils#linkViewWithPresenterAndLaunch(Class, Class, Creator)} * - * @author Ilya.Kazakevich * @param view interface * @param

presenter interface + * @author Ilya.Kazakevich */ public interface Creator { @@ -45,5 +45,4 @@ public interface Creator { */ @NotNull V createView(@NotNull P presenter); - }