From 25f23b30ffe66fef7afa2611e167a0b07ed7bd8f Mon Sep 17 00:00:00 2001 From: UNV Date: Wed, 22 Jul 2026 20:10:50 +0300 Subject: [PATCH] Adding missing @Override annotations. Adding RRA/RWA/RUI annotations. Some localization and refactoring. --- .../debugger/pydev/ChangeVariableCommand.java | 7 +- .../pydev/ClientModeMultiProcessDebugger.java | 26 ++-- .../pydev/transport/BaseDebuggerReader.java | 18 +-- .../ClientModeDebuggerTransport.java | 3 +- .../com/jetbrains/python/impl/PyBundle.java | 7 +- .../config/BuildoutCfgColorsPage.java | 9 +- .../buildout/config/BuildoutCfgFileType.java | 9 +- .../config/BuildoutCfgParserDefinition.java | 9 +- .../config/BuildoutCfgSyntaxHighlighter.java | 7 +- .../config/lexer/_BuildoutCfgFlexLexer.java | 34 ++--- .../config/psi/impl/BuildoutCfgFile.java | 6 +- .../psi/impl/BuildoutCfgSectionHeader.java | 5 +- .../config/ref/BuildoutPartReference.java | 8 +- .../imports/AutoImportQuickFix.java | 19 +-- .../imports/ImportCandidateHolder.java | 1 + .../imports/ImportFromExistingAction.java | 85 ++++++++----- ...onvertFormatOperatorToMethodIntention.java | 25 ++-- .../ConvertVariadicParamIntention.java | 59 ++++----- .../testIntegration/CreateTestAction.java | 23 ++-- .../testIntegration/CreateTestDialog.java | 26 ++-- .../AbstractLineBreakpointHandler.java | 3 +- .../array/ArrayTableCellRenderer.java | 6 +- .../debugger/array/AsyncArrayTableModel.java | 12 +- .../debugger/dataframe/DataFrameTable.java | 63 +++++----- .../dataframe/DataFrameTableCellRenderer.java | 118 ++++++++---------- .../docstrings/DocStringTypeReference.java | 71 ++++++----- .../docstrings/EpydocString.java | 4 +- .../quickfix/AddEncodingQuickFix.java | 7 +- .../quickfix/AddFieldQuickFix.java | 44 ++++--- .../quickfix/AddFunctionQuickFix.java | 46 +++---- .../quickfix/AddGlobalQuickFix.java | 10 +- .../quickfix/AddMethodQuickFix.java | 38 +++--- .../inspections/quickfix/AddSelfQuickFix.java | 12 +- .../quickfix/AugmentedAssignmentQuickFix.java | 25 ++-- .../quickfix/ChainedComparisonsQuickFix.java | 106 ++++++++-------- .../quickfix/ComparisonWithNoneQuickFix.java | 8 +- .../CompatibilityPrintCallQuickFix.java | 10 +- .../quickfix/ConvertDocstringQuickFix.java | 6 +- .../quickfix/CreateClassQuickFix.java | 8 +- .../quickfix/DocstringQuickFix.java | 3 + .../python/impl/lexer/_PythonLexer.java | 57 ++++----- .../com/jetbrains/python/impl/psi/PyUtil.java | 16 +++ .../python/impl/psi/types/_PyTypeLexer.java | 38 +++--- .../introduce/constant/ConstantValidator.java | 16 +-- .../run/AbstractPythonRunConfiguration.java | 66 ++++++---- .../AbstractPythonTestRunConfiguration.java | 51 +++++--- .../python/impl/toolbox/ChainIterable.java | 18 ++- .../python/impl/toolbox/ChainIterator.java | 14 ++- .../jetbrains/python/impl/ui/IdeaDialog.java | 12 +- .../validation/AssignTargetAnnotator.java | 98 ++++++++++----- 50 files changed, 758 insertions(+), 614 deletions(-) diff --git a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ChangeVariableCommand.java b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ChangeVariableCommand.java index bf76e8fa..ca3468b9 100644 --- a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ChangeVariableCommand.java +++ b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ChangeVariableCommand.java @@ -1,26 +1,22 @@ package com.jetbrains.python.debugger.pydev; - import com.jetbrains.python.debugger.IPyDebugProcess; import com.jetbrains.python.debugger.PyDebugValue; import com.jetbrains.python.debugger.PyDebuggerException; public class ChangeVariableCommand extends AbstractFrameCommand { - private final String myVariableName; private final String myValue; private PyDebugValue myNewValue = null; private final IPyDebugProcess myDebugProcess; - public ChangeVariableCommand(RemoteDebugger debugger, String threadId, String frameId, String variableName, - String value) { + public ChangeVariableCommand(RemoteDebugger debugger, String threadId, String frameId, String variableName, String value) { super(debugger, CHANGE_VARIABLE, threadId, frameId); myVariableName = variableName; myValue = value; myDebugProcess = debugger.getDebugProcess(); } - @Override protected void buildPayload(Payload payload) { super.buildPayload(payload); @@ -32,6 +28,7 @@ public boolean isResponseExpected() { return true; } + @Override protected void processResponse(ProtocolFrame response) throws PyDebuggerException { super.processResponse(response); myNewValue = ProtocolParser.parseValue(response.getPayload(), myDebugProcess).setName(myVariableName); diff --git a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ClientModeMultiProcessDebugger.java b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ClientModeMultiProcessDebugger.java index 7db8e80b..78ddc71b 100644 --- a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ClientModeMultiProcessDebugger.java +++ b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/ClientModeMultiProcessDebugger.java @@ -1,6 +1,5 @@ package com.jetbrains.python.debugger.pydev; -import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; @@ -10,8 +9,8 @@ import consulo.execution.debug.breakpoint.SuspendPolicy; import consulo.execution.debug.frame.XValueChildrenList; import consulo.logging.Logger; - import org.jspecify.annotations.Nullable; + import java.util.*; /** @@ -163,7 +162,8 @@ public XValueChildrenList loadVariable(String threadId, String frameId, PyDebugV return debugger(threadId).loadVariable(threadId, frameId, var); } - public ArrayChunk loadArrayItems(String threadId, String frameId, PyDebugValue var, int rowOffset, int colOffset, int rows, int cols, String format) throws PyDebuggerException + @Override + public ArrayChunk loadArrayItems(String threadId, String frameId, PyDebugValue var, int rowOffset, int colOffset, int rows, int cols, String format) throws PyDebuggerException { return debugger(threadId).loadArrayItems(threadId, frameId, var, rowOffset, colOffset, rows, cols, format); } @@ -250,17 +250,12 @@ public Collection getThreads() if(!isOtherDebuggersEmpty()) { //here we add process id to thread name in case there are more then one process - return Collections.unmodifiableCollection(Collections2.transform(threads, new Function() - { - @Override - public PyThreadInfo apply(PyThreadInfo t) - { - String threadName = ThreadRegistry.threadName(t.getName(), t.getId()); - PyThreadInfo newThread = new PyThreadInfo(t.getId(), threadName, t.getFrames(), t.getStopReason(), t.getMessage()); - newThread.updateState(t.getState(), t.getFrames()); - return newThread; - } - })); + return Collections.unmodifiableCollection(Collections2.transform(threads, t -> { + String threadName = ThreadRegistry.threadName(t.getName(), t.getId()); + PyThreadInfo newThread = new PyThreadInfo(t.getId(), threadName, t.getFrames(), t.getStopReason(), t.getMessage()); + newThread.updateState(t.getState(), t.getFrames()); + return newThread; + })); } else { @@ -439,7 +434,8 @@ private void addDebugger(RemoteDebugger debugger) } } - public void addCloseListener(RemoteDebuggerCloseListener listener) + @Override + public void addCloseListener(RemoteDebuggerCloseListener listener) { myMainDebugger.addCloseListener(listener); } diff --git a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/BaseDebuggerReader.java b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/BaseDebuggerReader.java index c8652584..b3ff5c72 100644 --- a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/BaseDebuggerReader.java +++ b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/BaseDebuggerReader.java @@ -1,18 +1,17 @@ package com.jetbrains.python.debugger.pydev.transport; +import com.jetbrains.python.debugger.pydev.RemoteDebugger; +import consulo.application.Application; +import consulo.logging.Logger; +import consulo.process.io.BaseOutputReader; +import consulo.util.lang.TimeoutUtil; + import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Arrays; import java.util.concurrent.Future; - -import consulo.application.ApplicationManager; -import consulo.logging.Logger; -import consulo.util.lang.TimeoutUtil; -import consulo.process.io.BaseOutputReader; -import com.jetbrains.python.debugger.pydev.RemoteDebugger; - /** * @author Alexander Koshevoy */ @@ -34,7 +33,8 @@ protected RemoteDebugger getDebugger() return myDebugger; } - protected void doRun() + @Override + protected void doRun() { try { @@ -73,7 +73,7 @@ protected void doRun() @Override protected Future executeOnPooledThread(Runnable runnable) { - return ApplicationManager.getApplication().executeOnPooledThread(runnable); + return Application.get().executeOnPooledThread(runnable); } @Override diff --git a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/ClientModeDebuggerTransport.java b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/ClientModeDebuggerTransport.java index 6451a197..9a419c7b 100644 --- a/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/ClientModeDebuggerTransport.java +++ b/python-debugger/src/main/java/com/jetbrains/python/debugger/pydev/transport/ClientModeDebuggerTransport.java @@ -303,7 +303,8 @@ public DebuggerReader(RemoteDebugger debugger, InputStream stream) throws IOExce start(getClass().getName()); } - protected void onCommunicationError() + @Override + protected void onCommunicationError() { if(myState == State.APPROVED) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/PyBundle.java b/python-impl/src/main/java/com/jetbrains/python/impl/PyBundle.java index d12146cc..000411c0 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/PyBundle.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/PyBundle.java @@ -13,12 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl; +import consulo.annotation.DeprecationInfo; +import consulo.annotation.internal.MigratedExtensionsTo; import consulo.component.util.localize.AbstractBundle; +import consulo.python.impl.localize.PyLocalize; import org.jetbrains.annotations.PropertyKey; +@Deprecated +@DeprecationInfo("Use PyLocalize") +@MigratedExtensionsTo(PyLocalize.class) public class PyBundle extends AbstractBundle { private static final String BUNDLE = "com.jetbrains.python.impl.PyBundle"; private static final PyBundle ourInstance = new PyBundle(); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgColorsPage.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgColorsPage.java index 15befc69..7961f71d 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgColorsPage.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgColorsPage.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config; import consulo.annotation.component.ExtensionImpl; @@ -41,30 +40,35 @@ public class BuildoutCfgColorsPage implements ColorSettingsPage { new AttributesDescriptor("Comment", BuildoutCfgSyntaxHighlighter.BUILDOUT_COMMENT) }; - private static final HashMap ourTagToDescriptorMap = new HashMap(); + private static final HashMap ourTagToDescriptorMap = new HashMap<>(); static { //ourTagToDescriptorMap.put("comment", DjangoTemplateHighlighterColors.DJANGO_COMMENT); } + @Override public LocalizeValue getDisplayName() { return LocalizeValue.localizeTODO("Buildout config"); } + @Override public AttributesDescriptor[] getAttributeDescriptors() { return ATTRS; } + @Override public ColorDescriptor[] getColorDescriptors() { return ColorDescriptor.EMPTY_ARRAY; } + @Override public SyntaxHighlighter getHighlighter() { SyntaxHighlighter highlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(BuildoutCfgFileType.INSTANCE, null, null); assert highlighter != null; return highlighter; } + @Override public String getDemoText() { return "; Buildout config\n" + @@ -79,6 +83,7 @@ public String getDemoText() { "eggs = ${buildout:eggs}"; } + @Override public Map getAdditionalHighlightingTagToDescriptorMap() { return ourTagToDescriptorMap; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgFileType.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgFileType.java index 22dc1c24..97f52104 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgFileType.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgFileType.java @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config; import consulo.language.file.LanguageFileType; import consulo.localize.LocalizeValue; +import consulo.python.impl.icon.PythonImplIconGroup; import consulo.ui.image.Image; -import com.jetbrains.python.impl.PythonIcons; import org.jspecify.annotations.Nullable; @@ -34,21 +33,25 @@ private BuildoutCfgFileType() { super(BuildoutCfgLanguage.INSTANCE); } + @Override public String getId() { return "BuildoutCfg"; } + @Override public LocalizeValue getDescription() { return LocalizeValue.localizeTODO("Buildout config files"); } + @Override public String getDefaultExtension() { return DEFAULT_EXTENSION; } @Nullable + @Override public Image getIcon() { - return PythonIcons.Python.Buildout.Buildout; + return PythonImplIconGroup.pythonBuildoutBuildout(); } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgParserDefinition.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgParserDefinition.java index 01ea9482..cc1b215c 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgParserDefinition.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgParserDefinition.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config; import com.jetbrains.python.impl.buildout.config.lexer.BuildoutCfgFlexLexer; @@ -46,35 +45,43 @@ public Language getLanguage() { return BuildoutCfgLanguage.INSTANCE; } + @Override public Lexer createLexer(LanguageVersion languageVersion) { return new BuildoutCfgFlexLexer(); } @Nullable + @Override public PsiParser createParser(LanguageVersion languageVersion) { return new BuildoutCfgParser(); } + @Override public IFileElementType getFileNodeType() { return FILE; } + @Override public TokenSet getWhitespaceTokens(LanguageVersion languageVersion) { return TokenSet.create(WHITESPACE); } + @Override public TokenSet getCommentTokens(LanguageVersion languageVersion) { return TokenSet.create(COMMENT); } + @Override public TokenSet getStringLiteralElements(LanguageVersion languageVersion) { return TokenSet.create(TEXT); } + @Override public PsiElement createElement(ASTNode node) { return astFactory.create(node); } + @Override public PsiFile createFile(FileViewProvider viewProvider) { return new BuildoutCfgFile(viewProvider); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgSyntaxHighlighter.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgSyntaxHighlighter.java index fdf74745..dca9613e 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgSyntaxHighlighter.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/BuildoutCfgSyntaxHighlighter.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config; import com.google.common.collect.Maps; @@ -27,14 +26,13 @@ import java.util.Map; /** - * @author: traff + * @author traff */ public class BuildoutCfgSyntaxHighlighter extends SyntaxHighlighterBase implements BuildoutCfgTokenTypes { static final String COMMENT_ID = "BUILDOUT_COMMENT"; static final String TEXT_ID = "BUILDOUT_TEXT"; static final String BRACKETS_ID = "BUILDOUT_BRACKETS"; - public static final TextAttributesKey BUILDOUT_SECTION_NAME = TextAttributesKey.createTextAttributesKey( "BUILDOUT.SECTION_NAME", DefaultLanguageHighlighterColors.NUMBER @@ -79,11 +77,12 @@ public class BuildoutCfgSyntaxHighlighter extends SyntaxHighlighterBase implemen ATTRIBUTES.put(VALUE_CHARACTERS, BUILDOUT_VALUE); } - + @Override public TextAttributesKey[] getTokenHighlights(IElementType tokenType) { return SyntaxHighlighterBase.pack(ATTRIBUTES.get(tokenType)); } + @Override public Lexer getHighlightingLexer() { return new BuildoutCfgFlexLexer(); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/lexer/_BuildoutCfgFlexLexer.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/lexer/_BuildoutCfgFlexLexer.java index 6f6daab2..1577f3a3 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/lexer/_BuildoutCfgFlexLexer.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/lexer/_BuildoutCfgFlexLexer.java @@ -15,7 +15,6 @@ */ /* The following code was generated by JFlex 1.4.3 on 8/26/10 7:31 PM */ - package com.jetbrains.python.impl.buildout.config.lexer; import com.jetbrains.python.impl.buildout.config.BuildoutCfgTokenTypes; @@ -92,8 +91,7 @@ private static int zzUnpackAction(String packed, int offset, int [] result) { return j; } - - /** + /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); @@ -159,7 +157,6 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { return j; } - /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; @@ -170,7 +167,7 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { - "Unkown internal scanner error", + "Unknown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; @@ -243,7 +240,6 @@ the source of the yytext() string */ /** denotes if the user-EOF-code has already been executed */ private boolean zzEOFDone; - public _BuildoutCfgFlexLexer(java.io.Reader in) { this.zzReader = in; } @@ -276,15 +272,18 @@ public _BuildoutCfgFlexLexer(java.io.InputStream in) { return map; } + @Override public final int getTokenStart(){ return zzStartRead; } + @Override public final int getTokenEnd(){ return getTokenStart() + yylength(); } - public void reset(CharSequence buffer, int start, int end,int initialState){ + @Override + public void reset(CharSequence buffer, int start, int end, int initialState){ zzBuffer = buffer; zzBufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; @@ -306,25 +305,24 @@ private boolean zzRefill() throws java.io.IOException { return true; } - /** * Returns the current lexical state. */ + @Override public final int yystate() { return zzLexicalState; } - /** * Enters a new lexical state * * @param newState the new lexical state */ + @Override public final void yybegin(int newState) { zzLexicalState = newState; } - /** * Returns the text matched by the current regular expression. */ @@ -332,7 +330,6 @@ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } - /** * Returns the character at position pos from the * matched text. @@ -348,7 +345,6 @@ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } - /** * Returns the length of the matched text region. */ @@ -356,11 +352,10 @@ public final int yylength() { return zzMarkedPos-zzStartRead; } - /** - * Reports an error that occured while scanning. + * Reports an error that occurred while scanning. * - * In a wellformed scanner (no or only correct usage of + * In a well-formed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong @@ -369,7 +364,7 @@ public final int yylength() { * Usual syntax/scanner level error handling should be done * in error fallback rules. * - * @param errorCode the code of the errormessage to display + * @param errorCode the code of the error-message to display */ private void zzScanError(int errorCode) { String message; @@ -383,7 +378,6 @@ private void zzScanError(int errorCode) { throw new Error(message); } - /** * Pushes the specified amount of characters back into the input stream. * @@ -399,7 +393,6 @@ public void yypushback(int number) { zzMarkedPos -= number; } - /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached @@ -411,7 +404,6 @@ private void zzDoEOF() { } } - /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. @@ -419,6 +411,7 @@ private void zzDoEOF() { * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ + @Override public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; @@ -447,7 +440,6 @@ public IElementType advance() throws java.io.IOException { zzForAction: { while (true) { - if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++]:zzBufferL.charAt(zzCurrentPosL++); else if (zzAtEOF) { @@ -554,6 +546,4 @@ else if (zzAtEOF) { } } } - - } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgFile.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgFile.java index 055e9f1e..7888af18 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgFile.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgFile.java @@ -13,10 +13,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config.psi.impl; import com.google.common.collect.Lists; +import consulo.annotation.access.RequiredReadAction; import consulo.language.impl.psi.PsiFileBase; import consulo.virtualFileSystem.fileType.FileType; import consulo.util.lang.StringUtil; @@ -40,6 +40,7 @@ public BuildoutCfgFile(FileViewProvider viewProvider) { super(viewProvider, BuildoutCfgLanguage.INSTANCE); } + @Override public FileType getFileType() { return BuildoutCfgFileType.INSTANCE; } @@ -49,11 +50,13 @@ public String toString() { return "buildout.cfg file"; } + @RequiredReadAction public Collection getSections() { return PsiTreeUtil.collectElementsOfType(this, BuildoutCfgSection.class); } @Nullable + @RequiredReadAction public BuildoutCfgSection findSectionByName(String name) { Collection sections = getSections(); for (BuildoutCfgSection section : sections) { @@ -64,6 +67,7 @@ public BuildoutCfgSection findSectionByName(String name) { return null; } + @RequiredReadAction public List getParts() { BuildoutCfgSection buildoutSection = findSectionByName("buildout"); if (buildoutSection == null) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgSectionHeader.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgSectionHeader.java index 3a5f7dc1..105e2b87 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgSectionHeader.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/psi/impl/BuildoutCfgSectionHeader.java @@ -13,9 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config.psi.impl; +import consulo.annotation.access.RequiredReadAction; import consulo.language.ast.ASTNode; import org.jspecify.annotations.Nullable; @@ -28,6 +28,8 @@ public BuildoutCfgSectionHeader(ASTNode node) { } @Nullable + @Override + @RequiredReadAction public String getName() { String name = getText().trim(); if (name.startsWith("[") && name.endsWith("]")) { @@ -37,6 +39,7 @@ public String getName() { } @Override + @RequiredReadAction public String toString() { return "BuildoutCfgSectionHeader:" + getNode().getElementType().toString(); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/ref/BuildoutPartReference.java b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/ref/BuildoutPartReference.java index e03e4de2..8ede601b 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/ref/BuildoutPartReference.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/buildout/config/ref/BuildoutPartReference.java @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.buildout.config.ref; import com.google.common.collect.Lists; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.document.util.TextRange; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiReferenceBase; @@ -46,6 +47,8 @@ public TextRange getRangeInElement() { return TextRange.from(myOffsetInElement, myPartName.length()); } + @Override + @RequiredReadAction public PsiElement resolve() { BuildoutCfgFile file = PsiTreeUtil.getParentOfType(myElement, BuildoutCfgFile.class); if (file != null) { @@ -54,6 +57,8 @@ public PsiElement resolve() { return null; } + @Override + @RequiredReadAction public Object[] getVariants() { List res = Lists.newArrayList(); BuildoutCfgFile file = PsiTreeUtil.getParentOfType(myElement, BuildoutCfgFile.class); @@ -70,6 +75,7 @@ public Object[] getVariants() { } @Override + @RequiredWriteAction public PsiElement handleElementRename(String newElementName) { String fullName = PythonStringUtil.replaceLastSuffix(getElement().getText(), "/", newElementName); return myElement.replace(PyElementGenerator.getInstance(myElement.getProject()).createStringLiteralAlreadyEscaped(fullName)); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/AutoImportQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/AutoImportQuickFix.java index a2d4886e..bf0ea561 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/AutoImportQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/AutoImportQuickFix.java @@ -15,13 +15,13 @@ */ package com.jetbrains.python.impl.codeInsight.imports; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.impl.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyImportElement; import com.jetbrains.python.psi.PyQualifiedExpression; import com.jetbrains.python.psi.impl.PyPsiUtils; +import consulo.annotation.access.RequiredReadAction; import consulo.codeEditor.Editor; import consulo.language.editor.AutoImportHelper; import consulo.language.editor.FileModificationService; @@ -35,9 +35,9 @@ import consulo.module.content.ProjectFileIndex; import consulo.project.Project; import consulo.python.impl.localize.PyLocalize; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.collection.ContainerUtil; import consulo.virtualFileSystem.VirtualFile; - import org.jspecify.annotations.Nullable; import java.util.ArrayList; @@ -49,7 +49,7 @@ /** * The object contains a list of import candidates and serves only to show the initial hint; - * the actual work is done in ImportFromExistingAction.. + * the actual work is done in ImportFromExistingAction. * * @author dcheryasov */ @@ -135,6 +135,7 @@ else if (myImports.size() == 1) { } } + @RequiredUIAccess public boolean showHint(Editor editor) { if (!PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP || HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true) || @@ -163,8 +164,7 @@ public boolean showHint(Editor editor) { ImportCandidateHolder.getQualifiedName( myInitialName, myImports.get(0).getPath(), - myImports.get(0).getImportElement - () + myImports.get(0).getImportElement() ) ); ImportFromExistingAction action = @@ -174,6 +174,8 @@ public boolean showHint(Editor editor) { return true; } + @Override + @RequiredReadAction public boolean isAvailable() { PsiElement element = getStartElement(); if (element == null) { @@ -184,10 +186,12 @@ public boolean isAvailable() { } @Override + @RequiredUIAccess public void invoke(Project project, PsiFile file, PsiElement startElement, PsiElement endElement) { invoke(getStartElement().getContainingFile()); } + @RequiredUIAccess public void invoke(PsiFile file) throws IncorrectOperationException { // make sure file is committed, writable, etc PsiElement startElement = getStartElement(); @@ -258,9 +262,10 @@ public String getNameToImport() { return myInitialName; } + @RequiredReadAction private static boolean isResolved(PsiReference reference) { - if (reference instanceof PsiPolyVariantReference) { - return ((PsiPolyVariantReference) reference).multiResolve(false).length > 0; + if (reference instanceof PsiPolyVariantReference polyRef) { + return polyRef.multiResolve(false).length > 0; } return reference.resolve() != null; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportCandidateHolder.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportCandidateHolder.java index 06c4ae07..15f23fdd 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportCandidateHolder.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportCandidateHolder.java @@ -162,6 +162,7 @@ else if (myImportable instanceof PyClass) { return sb.toString(); } + @Override public int compareTo(ImportCandidateHolder other) { int lRelevance = getRelevance(); int rRelevance = other.getRelevance(); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportFromExistingAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportFromExistingAction.java index 8014e2fe..5c7d4b12 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportFromExistingAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/imports/ImportFromExistingAction.java @@ -15,31 +15,34 @@ */ package com.jetbrains.python.impl.codeInsight.imports; -import consulo.language.editor.hint.QuestionAction; -import consulo.dataContext.DataManager; -import consulo.language.inject.InjectedLanguageManager; -import consulo.application.ApplicationManager; +import com.jetbrains.python.psi.*; +import com.jetbrains.python.psi.impl.PyPsiUtils; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; +import consulo.application.Application; import consulo.application.Result; -import consulo.language.editor.WriteCommandAction; import consulo.colorScheme.EditorColorsManager; import consulo.colorScheme.EditorColorsScheme; -import consulo.project.Project; -import consulo.module.content.ProjectFileIndex; +import consulo.dataContext.DataManager; import consulo.ide.impl.ui.impl.PopupChooserBuilder; -import consulo.util.lang.Comparing; -import consulo.virtualFileSystem.VirtualFile; +import consulo.language.editor.WriteCommandAction; +import consulo.language.editor.hint.QuestionAction; +import consulo.language.icon.IconDescriptorUpdaters; +import consulo.language.inject.InjectedLanguageManager; import consulo.language.psi.PsiDocumentManager; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.PsiFileSystemItem; import consulo.language.psi.util.QualifiedName; -import consulo.ui.ex.awt.SimpleColoredComponent; +import consulo.module.content.ProjectFileIndex; +import consulo.project.Project; +import consulo.python.impl.localize.PyLocalize; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.SimpleTextAttributes; import consulo.ui.ex.awt.JBList; -import com.jetbrains.python.impl.PyBundle; -import com.jetbrains.python.psi.*; -import com.jetbrains.python.psi.impl.PyPsiUtils; -import consulo.language.icon.IconDescriptorUpdaters; +import consulo.ui.ex.awt.SimpleColoredComponent; +import consulo.util.lang.Comparing; +import consulo.virtualFileSystem.VirtualFile; import javax.swing.*; import java.awt.*; @@ -63,7 +66,7 @@ public class ImportFromExistingAction implements QuestionAction * @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 useQualified if True, use qualified "import modulename" instead of "from modulename import ...". + * @param useQualified if True, use qualified "import moduleName" instead of "from moduleName import ...". */ public ImportFromExistingAction(PsiElement target, List sources, String name, boolean useQualified, boolean importLocally) { @@ -86,7 +89,9 @@ public void onDone(Runnable callback) * * @return true if action succeeded */ - public boolean execute() + @Override + @RequiredUIAccess + public boolean execute() { // check if the tree is sane PsiDocumentManager.getInstance(myTarget.getProject()).commitAllDocuments(); @@ -110,7 +115,7 @@ public boolean execute() return false; } // act - if(mySources.size() == 1 || ApplicationManager.getApplication().isUnitTestMode()) + if(mySources.size() == 1 || Application.get().isUnitTestMode()) { doWriteAction(mySources.get(0)); } @@ -125,9 +130,10 @@ private void selectSourceAndDo() { // GUI part ImportCandidateHolder[] items = mySources.toArray(new ImportCandidateHolder[mySources.size()]); // silly JList can't handle modern collections - JList list = new JBList(items); + JList list = new JBList<>(items); list.setCellRenderer(new CellRenderer(myName)); + @RequiredWriteAction Runnable runnable = () -> { Object selected = list.getSelectedValue(); if(selected instanceof ImportCandidateHolder) @@ -138,10 +144,18 @@ private void selectSourceAndDo() } }; - DataManager.getInstance().getDataContextFromFocus().doWhenDone(dataContext -> new PopupChooserBuilder(list).setTitle(myUseQualifiedImport ? PyBundle.message("ACT.qualify.with.module") : PyBundle.message("ACT.from.some.module.import")).setItemChoosenCallback(runnable).setFilteringEnabled(o -> ((ImportCandidateHolder) o).getPresentableText(myName)).createPopup().showInBestPositionFor(dataContext)); + DataManager.getInstance().getDataContextFromFocus().doWhenDone( + dataContext -> new PopupChooserBuilder(list) + .setTitle(myUseQualifiedImport ? PyLocalize.actQualifyWithModule().get() : PyLocalize.actFromSomeModuleImport().get()) + .setItemChoosenCallback(runnable) + .setFilteringEnabled(o -> ((ImportCandidateHolder) o).getPresentableText(myName)) + .createPopup() + .showInBestPositionFor(dataContext) + ); } - private void doIt(ImportCandidateHolder item) + @RequiredWriteAction + private void doIt(ImportCandidateHolder item) { PyImportElement src = item.getImportElement(); if(src != null) @@ -154,7 +168,8 @@ private void doIt(ImportCandidateHolder item) } } - private void addImportStatement(ImportCandidateHolder item) + @RequiredWriteAction + private void addImportStatement(ImportCandidateHolder item) { Project project = myTarget.getProject(); PyElementGenerator gen = PyElementGenerator.getInstance(project); @@ -212,8 +227,8 @@ private void addImportStatement(ImportCandidateHolder item) } } - - private void addToExistingImport(PyImportElement src) + @RequiredWriteAction + private void addToExistingImport(PyImportElement src) { PyElementGenerator gen = PyElementGenerator.getInstance(myTarget.getProject()); // did user choose 'import' or 'from import'? @@ -231,12 +246,14 @@ private void addToExistingImport(PyImportElement src) } } - private void doWriteAction(final ImportCandidateHolder item) + @RequiredUIAccess + private void doWriteAction(final ImportCandidateHolder item) { PsiElement src = item.getImportable(); - new WriteCommandAction(src.getProject(), PyBundle.message("ACT.CMD.use.import"), myTarget.getContainingFile()) + new WriteCommandAction(src.getProject(), PyLocalize.actCmdUseImport().get(), myTarget.getContainingFile()) { - @Override + @Override + @RequiredWriteAction protected void run(Result result) throws Throwable { doIt(item); @@ -260,7 +277,9 @@ public static boolean isRoot(PsiFileSystemItem directory) return true; } ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(directory.getProject()); - return Comparing.equal(fileIndex.getClassRootForFile(vFile), vFile) || Comparing.equal(fileIndex.getContentRootForFile(vFile), vFile) || Comparing.equal(fileIndex.getSourceRootForFile(vFile), vFile); + return Comparing.equal(fileIndex.getClassRootForFile(vFile), vFile) + || Comparing.equal(fileIndex.getContentRootForFile(vFile), vFile) + || Comparing.equal(fileIndex.getSourceRootForFile(vFile), vFile); } // Stolen from FQNameCellRenderer @@ -278,9 +297,15 @@ public CellRenderer(String name) } // value is a QualifiedHolder - public Component getListCellRendererComponent(JList list, Object value, // expected to be - int index, boolean isSelected, boolean cellHasFocus) - { + @Override + @RequiredReadAction + public Component getListCellRendererComponent( + JList list, + Object value, // expected to be + int index, + boolean isSelected, + boolean cellHasFocus + ) { clear(); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java index 86827b7e..ba969c7d 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertFormatOperatorToMethodIntention.java @@ -23,6 +23,8 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.python.impl.localize.PyLocalize; import org.jspecify.annotations.Nullable; @@ -106,6 +108,7 @@ private static void appendDoublingBraces(CharSequence source, StringBuilder targ * * @return a pair of string builder with resulting string expression and a flag which is true if formats inside use mapping by name. */ + @RequiredReadAction private static Pair convertFormat(PyStringLiteralExpression stringLiteralExpression, String prefix) { // python string may be made of several literals, all different List constants = new ArrayList<>(); @@ -154,7 +157,7 @@ private static Pair convertFormat(PyStringLiteralExpress } else { sure(fConversion); - sure(!"%".equals(fConversion)); // a padded percent literal; can't bother to autoconvert, and in 3k % is different. + sure(!"%".equals(fConversion)); // a padded percent literal; can't bother to auto-convert, and in 3k % is different. out.append("{"); if (f_key != null) { out.append(f_key); @@ -253,6 +256,8 @@ private static boolean has(String where, char what) { return where.indexOf(what) >= 0; } + @Override + @RequiredReadAction public boolean isAvailable(Project project, Editor editor, PsiFile file) { if (!(file instanceof PyFile)) { return false; @@ -291,6 +296,7 @@ public boolean isAvailable(Project project, Editor editor, PsiFile file) { } @Override + @RequiredWriteAction public void doInvoke(Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PsiElement elementAt = file.findElementAt(editor.getCaretModel().getOffset()); PyBinaryExpression element = PsiTreeUtil.getParentOfType(elementAt, PyBinaryExpression.class, false); @@ -350,22 +356,20 @@ else if (rhsType instanceof PyCollectionType && "dict".equals(rhsType.getName()) element.replace(sure(((PyParenthesizedExpression) parenthesized).getContainedExpression())); } + @RequiredReadAction private static boolean isDictCall(PyExpression callee, PyClassType classType) { PyClassType dictType = PyBuiltinCache.getInstance(callee.getContainingFile()).getDictType(); - if (dictType != null && classType.getPyClass() == dictType.getPyClass()) { - if (callee instanceof PyReferenceExpression) { - PsiElement maybeDict = ((PyReferenceExpression) callee).getReference().resolve(); - PyFunction dictInit = PyUtil.as(maybeDict, PyFunction.class); - if (dictInit != null) { - if (PyNames.INIT.equals(dictInit.getName())) { - return true; - } - } + if (dictType != null && classType.getPyClass() == dictType.getPyClass() && callee instanceof PyReferenceExpression refExpr) { + PsiElement maybeDict = refExpr.getReference().resolve(); + PyFunction dictInit = PyUtil.as(maybeDict, PyFunction.class); + if (dictInit != null && PyNames.INIT.equals(dictInit.getName())) { + return true; } } return false; } + @RequiredReadAction private static String getSeparator(PyStringLiteralExpression leftExpression) { String separator = ""; // detect nontrivial whitespace around the "%" Pair crop = collectWhitespace(leftExpression); @@ -383,6 +387,7 @@ private static String getSeparator(PyStringLiteralExpression leftExpression) { return separator; } + @RequiredReadAction private static Pair collectWhitespace(PsiElement start) { StringBuilder sb = new StringBuilder(); PsiElement seeker = start; diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertVariadicParamIntention.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertVariadicParamIntention.java index 9f18ef38..bc83be9d 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertVariadicParamIntention.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/intentions/ConvertVariadicParamIntention.java @@ -16,6 +16,8 @@ package com.jetbrains.python.impl.codeInsight.intentions; import com.jetbrains.python.psi.*; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; import consulo.language.ast.ASTNode; import consulo.language.editor.intention.BaseIntentionAction; @@ -52,13 +54,14 @@ public LocalizeValue getText() { return PyLocalize.intnConvertVariadicParam(); } + @Override + @RequiredReadAction public boolean isAvailable(Project project, Editor editor, PsiFile file) { if (!(file instanceof PyFile)) { return false; } - PyFunction function = - PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyFunction.class); + PyFunction function = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyFunction.class); if (function != null) { PyParameter[] parameterList = function.getParameterList().getParameters(); for (PyParameter parameter : parameterList) { @@ -91,6 +94,8 @@ private static PyParameter getKeywordContainer(PyFunction function) { return null; } + @Override + @RequiredWriteAction public void invoke(Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PyFunction function = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyFunction.class); @@ -103,10 +108,11 @@ public void invoke(Project project, Editor editor, PsiFile file) throws Incorrec * * @param function */ + @RequiredReadAction private static List fillSubscriptions(PyFunction function) { - List subscriptions = new ArrayList(); + List subscriptions = new ArrayList<>(); PyStatementList statementList = function.getStatementList(); - Stack stack = new Stack(); + Stack stack = new Stack<>(); PyParameter keywordContainer = getKeywordContainer(function); if (keywordContainer != null && statementList != null) { String keywordContainerName = keywordContainer.getName(); @@ -114,8 +120,8 @@ private static List fillSubscriptions(PyFunction funct stack.push(st); while (!stack.isEmpty()) { PsiElement e = stack.pop(); - if (e instanceof PySubscriptionExpression) { - if (((PySubscriptionExpression) e).getOperand().getText().equals(keywordContainerName)) { + if (e instanceof PySubscriptionExpression subscriptionExpr) { + if (subscriptionExpr.getOperand().getText().equals(keywordContainerName)) { subscriptions.add((PySubscriptionExpression) e); } } @@ -130,6 +136,7 @@ private static List fillSubscriptions(PyFunction funct return subscriptions; } + @RequiredReadAction private static boolean isCallElement(PyExpression callee, String keywordContainerName) { PyExpression qualifier = ((PyQualifiedExpression) callee).getQualifier(); return (qualifier != null && qualifier.getText().equals(keywordContainerName) @@ -137,10 +144,11 @@ private static boolean isCallElement(PyExpression callee, String keywordContaine || "__getitem__".equals(((PyQualifiedExpression) callee).getReferencedName()))); } + @RequiredReadAction private static List fillCallExpressions(PyFunction function) { - List callElements = new ArrayList(); + List callElements = new ArrayList<>(); PyStatementList statementList = function.getStatementList(); - Stack stack = new Stack(); + Stack stack = new Stack<>(); PyParameter keywordContainer = getKeywordContainer(function); if (keywordContainer != null && statementList != null) { String keywordContainerName = keywordContainer.getName(); @@ -149,9 +157,9 @@ private static List fillCallExpressions(PyFunction function) { while (!stack.isEmpty()) { PsiElement e = stack.pop(); if (!(e instanceof PySubscriptionExpression)) { - if (e instanceof PyCallExpression && ((PyCallExpression) e).getCallee() instanceof PyQualifiedExpression - && isCallElement(((PyCallExpression) e).getCallee(), keywordContainerName)) { - callElements.add((PyCallExpression) e); + if (e instanceof PyCallExpression call && call.getCallee() instanceof PyQualifiedExpression + && isCallElement(call.getCallee(), keywordContainerName)) { + callElements.add(call); } else { for (PsiElement psiElement : e.getChildren()) { @@ -165,6 +173,7 @@ && isCallElement(((PyCallExpression) e).getCallee(), keywordContainerName)) { return callElements; } + @RequiredWriteAction private static void replaceSubscriptions(PyFunction function, Project project) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); List subscriptions = fillSubscriptions(function); @@ -172,11 +181,9 @@ private static void replaceSubscriptions(PyFunction function, Project project) { for (int i = 0; i != size; ++i) { PySubscriptionExpression subscriptionExpression = subscriptions.get(i); PyExpression indexExpression = subscriptionExpression.getIndexExpression(); - if (indexExpression instanceof PyStringLiteralExpression) { - PyExpression p = elementGenerator.createExpressionFromText( - LanguageLevel.forElement(function), - ((PyStringLiteralExpression) indexExpression).getStringValue() - ); + if (indexExpression instanceof PyStringLiteralExpression stringLiteral) { + PyExpression p = + elementGenerator.createExpressionFromText(LanguageLevel.forElement(function), stringLiteral.getStringValue()); ASTNode comma = elementGenerator.createComma(); PyClass containingClass = function.getContainingClass(); if (p != null) { @@ -194,6 +201,7 @@ private static void replaceSubscriptions(PyFunction function, Project project) { } } + @RequiredWriteAction private static void replaceCallElements(PyFunction function, Project project) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); List callElements = fillCallExpressions(function); @@ -201,26 +209,21 @@ private static void replaceCallElements(PyFunction function, Project project) { int size = callElements.size(); for (int i = 0; i != size; ++i) { PyCallExpression callExpression = callElements.get(i); - PyExpression indexExpression = callExpression.getArguments()[0]; - if (indexExpression instanceof PyStringLiteralExpression) { + if (callExpression.getArguments()[0] instanceof PyStringLiteralExpression stringLiteral) { PyNamedParameter defaultValue = null; if (callExpression.getArguments().length > 1) { - defaultValue = elementGenerator.createParameter( - ((PyStringLiteralExpression) indexExpression).getStringValue() - + "=" + callExpression.getArguments()[1].getText()); + defaultValue = + elementGenerator.createParameter(stringLiteral.getStringValue() + "=" + callExpression.getArguments()[1].getText()); } if (defaultValue == null) { PyExpression callee = callExpression.getCallee(); - if (callee instanceof PyQualifiedExpression && "get".equals(((PyQualifiedExpression) callee).getReferencedName())) { - defaultValue = - elementGenerator.createParameter(((PyStringLiteralExpression) indexExpression).getStringValue() + "=None"); + if (callee instanceof PyQualifiedExpression qExpr && "get".equals(qExpr.getReferencedName())) { + defaultValue = elementGenerator.createParameter(stringLiteral.getStringValue() + "=None"); } } - PyExpression p = elementGenerator.createExpressionFromText( - LanguageLevel.forElement(function), - ((PyStringLiteralExpression) indexExpression).getStringValue() - ); + PyExpression p = + elementGenerator.createExpressionFromText(LanguageLevel.forElement(function), stringLiteral.getStringValue()); ASTNode comma = elementGenerator.createComma(); PyParameter keywordContainer = getKeywordContainer(function); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestAction.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestAction.java index f51c8009..3c899d61 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestAction.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestAction.java @@ -19,14 +19,13 @@ import com.jetbrains.python.impl.testing.pytest.PyTestUtil; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; -import consulo.language.editor.CodeInsightBundle; import consulo.language.editor.intention.PsiElementBaseIntentionAction; import consulo.language.editor.localize.CodeInsightLocalize; import consulo.language.psi.PsiDirectory; import consulo.language.psi.PsiDocumentManager; import consulo.language.psi.PsiElement; -import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.language.util.IncorrectOperationException; import consulo.localize.LocalizeValue; @@ -45,16 +44,15 @@ public LocalizeValue getText() { return CodeInsightLocalize.intentionCreateTest(); } + @Override public boolean isAvailable(Project project, Editor editor, PsiElement element) { PyClass psiClass = PsiTreeUtil.getParentOfType(element, PyClass.class); - if (psiClass != null && PyTestUtil.isPyTestClass(psiClass, null)) { - return false; - } - return true; + return psiClass == null || !PyTestUtil.isPyTestClass(psiClass, null); } @Override + @RequiredWriteAction public void invoke(Project project, Editor editor, PsiElement element) throws IncorrectOperationException { PyFunction srcFunction = PsiTreeUtil.getParentOfType(element, PyFunction.class); PyClass srcClass = PsiTreeUtil.getParentOfType(element, PyClass.class); @@ -108,10 +106,13 @@ public void invoke(Project project, Editor editor, PsiElement element) throws In if (!d.showAndGet()) { return; } - CommandProcessor.getInstance().executeCommand(project, () -> { - PsiFile e = PyTestCreator.generateTestAndNavigate(project, d); - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); - documentManager.commitAllDocuments(); - }, CodeInsightBundle.message("intention.create.test"), this); + CommandProcessor.getInstance().newCommand() + .project(project) + .name(CodeInsightLocalize.intentionCreateTest()) + .run(() -> { + PyTestCreator.generateTestAndNavigate(project, d); + PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); + documentManager.commitAllDocuments(); + }); } } \ No newline at end of file diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestDialog.java b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestDialog.java index 8a265fa0..f6a82d82 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestDialog.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/codeInsight/testIntegration/CreateTestDialog.java @@ -13,16 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.codeInsight.testIntegration; -import consulo.fileChooser.FileChooserDescriptorFactory; import consulo.application.HelpManager; +import consulo.fileChooser.FileChooserDescriptorFactory; import consulo.project.Project; +import consulo.ui.ex.awt.BooleanTableCellRenderer; import consulo.ui.ex.awt.DialogWrapper; import consulo.ui.ex.awt.TextFieldWithBrowseButton; import consulo.util.lang.StringUtil; -import consulo.ui.ex.awt.BooleanTableCellRenderer; import javax.swing.*; import javax.swing.event.DocumentEvent; @@ -30,13 +29,11 @@ import javax.swing.table.DefaultTableModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** - * User: catherine + * @author catherine */ public class CreateTestDialog extends DialogWrapper { private TextFieldWithBrowseButton myTargetDir; @@ -54,18 +51,12 @@ protected CreateTestDialog(Project project) { myTargetDir.setEditable(false); - myTargetDir.addActionListener(new ActionListener() { - @Override - public void actionPerformed(ActionEvent actionEvent) { - getOKAction().setEnabled(isValid()); - } - }); + myTargetDir.addActionListener(actionEvent -> getOKAction().setEnabled(isValid())); setTitle("Create test"); addUpdater(myFileName); addUpdater(myClassName); - } public void methodsSize(int methods) { @@ -88,14 +79,17 @@ protected void addUpdater(JTextField field) { field.getDocument().addDocumentListener(new MyDocumentListener()); } private class MyDocumentListener implements DocumentListener { + @Override public void insertUpdate(DocumentEvent documentEvent) { getOKAction().setEnabled(isValid()); } + @Override public void removeUpdate(DocumentEvent documentEvent) { getOKAction().setEnabled(isValid()); } + @Override public void changedUpdate(DocumentEvent documentEvent) { getOKAction().setEnabled(isValid()); } @@ -141,20 +135,22 @@ public void addMethod(String name, int row) { } public List getMethods() { - List res = new ArrayList(); + List res = new ArrayList<>(); for (int i = 0; i != myTableModel.getRowCount(); ++i) { Object val = myTableModel.getValueAt(i, 0); - if (val != null && (Boolean)val == true) + if (val != null && (Boolean) val) res.add((String)myTableModel.getValueAt(i, 1)); } return res; } + @Override protected Action[] createActions() { return new Action[]{getOKAction(), getCancelAction(), getHelpAction()}; } + @Override protected void doHelpAction() { HelpManager.getInstance().invokeHelp("reference.dialogs.createTestsFromGoTo"); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/AbstractLineBreakpointHandler.java b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/AbstractLineBreakpointHandler.java index e2373dca..80581a5f 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/AbstractLineBreakpointHandler.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/AbstractLineBreakpointHandler.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.debugger; import com.google.common.collect.Lists; @@ -49,6 +48,7 @@ public void reregisterBreakpoints() { } } + @Override public void registerBreakpoint(XLineBreakpoint breakpoint) { XSourcePosition position = breakpoint.getSourcePosition(); if (position != null) { @@ -57,6 +57,7 @@ public void registerBreakpoint(XLineBreakpoint breakpoint } } + @Override public void unregisterBreakpoint(XLineBreakpoint breakpoint, boolean temporary) { XSourcePosition position = myBreakPointPositions.get(breakpoint); if (position != null) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/ArrayTableCellRenderer.java b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/ArrayTableCellRenderer.java index 2b8a7561..4a4c87fc 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/ArrayTableCellRenderer.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/ArrayTableCellRenderer.java @@ -49,7 +49,8 @@ public ArrayTableCellRenderer(double min, double max, String type) myType = type; } - public void setColored(boolean colored) + @Override + public void setColored(boolean colored) { myColored = colored; } @@ -60,7 +61,8 @@ public boolean getColored() return myColored; } - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); if(value != null) diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/AsyncArrayTableModel.java b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/AsyncArrayTableModel.java index 414adb8f..11e5c965 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/AsyncArrayTableModel.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/array/AsyncArrayTableModel.java @@ -84,7 +84,8 @@ public boolean isCellEditable(int row, int col) return false; } - public Object getValueAt(int row, int col) + @Override + public Object getValueAt(int row, int col) { Pair key = itemToChunkKey(row, col); @@ -134,17 +135,20 @@ private static int getPageColStart(int colOffset) return colOffset - (colOffset % CHUNK_COL_SIZE); } - public int getColumnCount() + @Override + public int getColumnCount() { return myColumns; } - public String getColumnName(int col) + @Override + public String getColumnName(int col) { return String.valueOf(col); } - public int getRowCount() + @Override + public int getRowCount() { return myRows; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTable.java b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTable.java index 2869f918..44b655ed 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTable.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTable.java @@ -15,7 +15,6 @@ */ package com.jetbrains.python.impl.debugger.dataframe; - import consulo.project.Project; import com.jetbrains.python.debugger.ArrayChunk; import com.jetbrains.python.debugger.PyDebugValue; @@ -26,40 +25,34 @@ import com.jetbrains.python.impl.debugger.containerview.ViewNumericContainerDialog; /** + * A bunch of this is copied from NumpyArrayTable. + * * @author amarch */ - /* A bunch of this is copied from NumpyArrayTable*/ - -public class DataFrameTable extends NumericContainerViewTable implements TableChunkDatasource -{ - - private Project myProject; - - public DataFrameTable(Project project, ViewNumericContainerDialog dialog, PyDebugValue value) - { - super(project, dialog, value); - } - - @Override - protected AsyncArrayTableModel createTableModel(int rowCount, int columnCount) - { - return new DataFrameTableModel(rowCount, columnCount, this); - } - - @Override - protected ColoredCellRenderer createCellRenderer(double minValue, double maxValue, ArrayChunk chunk) - { - return new DataFrameTableCellRenderer(); - } - - @Override - public boolean isNumeric() - { - return true; - } - - protected final String getTitlePresentation(String slice) - { - return "DataFrame View: " + slice; - } +public class DataFrameTable extends NumericContainerViewTable implements TableChunkDatasource { + private Project myProject; + + public DataFrameTable(Project project, ViewNumericContainerDialog dialog, PyDebugValue value) { + super(project, dialog, value); + } + + @Override + protected AsyncArrayTableModel createTableModel(int rowCount, int columnCount) { + return new DataFrameTableModel(rowCount, columnCount, this); + } + + @Override + protected ColoredCellRenderer createCellRenderer(double minValue, double maxValue, ArrayChunk chunk) { + return new DataFrameTableCellRenderer(); + } + + @Override + public boolean isNumeric() { + return true; + } + + @Override + protected final String getTitlePresentation(String slice) { + return "DataFrame View: " + slice; + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTableCellRenderer.java b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTableCellRenderer.java index 62fb7a3b..6a305959 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTableCellRenderer.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/debugger/dataframe/DataFrameTableCellRenderer.java @@ -26,72 +26,54 @@ import com.jetbrains.python.impl.debugger.containerview.ColoredCellRenderer; import com.jetbrains.python.impl.debugger.containerview.PyNumericViewUtil; - -class DataFrameTableCellRenderer extends DefaultTableCellRenderer implements ColoredCellRenderer -{ - - - private boolean myColored = true; - - public DataFrameTableCellRenderer() - { - setHorizontalAlignment(CENTER); - setHorizontalTextPosition(LEFT); - setVerticalAlignment(BOTTOM); - } - - public void setColored(boolean colored) - { - myColored = colored; - } - - @Override - public boolean getColored() - { - return myColored; - } - - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) - { - super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); - if(value != null) - { - setText(value.toString()); - } - - if(!(value instanceof TableValueDescriptor)) - { - return this; - } - - TableValueDescriptor descriptor = (TableValueDescriptor) value; - - if(hasFocus) - { - this.setBorder(new LineBorder(JBColor.BLUE, 2)); - } - - if(myColored) - { - try - { - double rangedValue = descriptor.getRangedValue(); - if(!Double.isNaN(rangedValue)) - { - this.setBackground(PyNumericViewUtil.rangedValueToColor(rangedValue)); - } - } - catch(NumberFormatException ignored) - { - - } - } - else - { - this.setBackground(new JBColor(UIUtil.getBgFillColor(table), UIUtil.getBgFillColor(table))); - } - - - return this; - } +class DataFrameTableCellRenderer extends DefaultTableCellRenderer implements ColoredCellRenderer { + private boolean myColored = true; + + public DataFrameTableCellRenderer() { + setHorizontalAlignment(CENTER); + setHorizontalTextPosition(LEFT); + setVerticalAlignment(BOTTOM); + } + + @Override + public void setColored(boolean colored) { + myColored = colored; + } + + @Override + public boolean getColored() { + return myColored; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { + super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); + if (value != null) { + setText(value.toString()); + } + + if (!(value instanceof TableValueDescriptor descriptor)) { + return this; + } + + if (hasFocus) { + this.setBorder(new LineBorder(JBColor.BLUE, 2)); + } + + if (myColored) { + try { + double rangedValue = descriptor.getRangedValue(); + if (!Double.isNaN(rangedValue)) { + this.setBackground(PyNumericViewUtil.rangedValueToColor(rangedValue)); + } + } + catch (NumberFormatException ignored) { + } + } + else { + this.setBackground(new JBColor(UIUtil.getBgFillColor(table), UIUtil.getBgFillColor(table))); + } + + return this; + } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/DocStringTypeReference.java b/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/DocStringTypeReference.java index 0861a04f..5143d791 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/DocStringTypeReference.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/DocStringTypeReference.java @@ -18,15 +18,19 @@ import com.google.common.collect.Lists; import com.jetbrains.python.PyNames; import com.jetbrains.python.impl.psi.PyUtil; +import com.jetbrains.python.impl.psi.impl.ResolveResultList; +import com.jetbrains.python.impl.psi.resolve.ImportedResolveResult; +import com.jetbrains.python.impl.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.impl.psi.types.PyClassTypeImpl; import com.jetbrains.python.impl.psi.types.PyImportedModuleType; import com.jetbrains.python.impl.psi.types.PyModuleType; import com.jetbrains.python.psi.*; -import com.jetbrains.python.impl.psi.impl.ResolveResultList; -import com.jetbrains.python.impl.psi.resolve.ImportedResolveResult; -import com.jetbrains.python.impl.psi.resolve.QualifiedNameFinder; import com.jetbrains.python.psi.resolve.RatedResolveResult; -import com.jetbrains.python.psi.types.*; +import com.jetbrains.python.psi.types.PyClassType; +import com.jetbrains.python.psi.types.PyType; +import com.jetbrains.python.psi.types.TypeEvalContext; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.document.util.TextRange; import consulo.language.editor.completion.CompletionUtilCore; import consulo.language.psi.*; @@ -34,13 +38,12 @@ import consulo.language.util.IncorrectOperationException; import consulo.util.collection.ArrayUtil; import consulo.util.lang.StringUtil; - import org.jspecify.annotations.Nullable; -import java.util.ArrayList; + import java.util.List; /** - * User : catherine + * @author catherine */ public class DocStringTypeReference extends PsiPolyVariantReferenceBase { @@ -58,36 +61,37 @@ public DocStringTypeReference(PsiElement element, TextRange range, TextRange ful myImportElement = importElement; } - @Nullable + @Nullable @Override + @RequiredWriteAction public PsiElement bindToElement(PsiElement element) throws IncorrectOperationException { if(element.equals(resolve())) { return element; } - if(myElement instanceof PyStringLiteralExpression && element instanceof PyClass) + if(myElement instanceof PyStringLiteralExpression e && element instanceof PyClass cls) { - PyStringLiteralExpression e = (PyStringLiteralExpression) myElement; - PyClass cls = (PyClass) element; - QualifiedName qname = QualifiedNameFinder.findCanonicalImportPath(cls, element); - if(qname != null) + QualifiedName qName = QualifiedNameFinder.findCanonicalImportPath(cls, element); + if(qName != null) { - qname = qname.append(cls.getName()); + qName = qName.append(cls.getName()); ElementManipulator manipulator = ElementManipulators.getManipulator(e); myType = new PyClassTypeImpl(cls, false); - return manipulator.handleContentChange(e, myFullRange, qname.toString()); + return manipulator.handleContentChange(e, myFullRange, qName.toString()); } } return null; } - public boolean isSoft() + @Override + public boolean isSoft() { return false; } @Override + @RequiredWriteAction public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { newElementName = StringUtil.trimEnd(newElementName, PyNames.DOT_PY); @@ -95,6 +99,7 @@ public PsiElement handleElementRename(String newElementName) throws IncorrectOpe } @Override + @RequiredReadAction public boolean isReferenceTo(PsiElement element) { if(myType instanceof PyImportedModuleType) @@ -105,21 +110,22 @@ public boolean isReferenceTo(PsiElement element) } @Override + @RequiredReadAction public ResolveResult[] multiResolve(boolean incompleteCode) { PsiElement result = null; ResolveResultList results = new ResolveResultList(); - if(myType instanceof PyClassType) + if(myType instanceof PyClassType classType) { - result = ((PyClassType) myType).getPyClass(); + result = classType.getPyClass(); } - else if(myType instanceof PyImportedModuleType) + else if(myType instanceof PyImportedModuleType importedModuleType) { - result = ((PyImportedModuleType) myType).getImportedModule().resolve(); + result = importedModuleType.getImportedModule().resolve(); } - else if(myType instanceof PyModuleType) + else if(myType instanceof PyModuleType moduleType) { - result = ((PyModuleType) myType).getModule(); + result = moduleType.getModule(); } if(result != null) { @@ -136,21 +142,24 @@ else if(myType instanceof PyModuleType) } @Override + @RequiredReadAction public Object[] getVariants() { // see PyDocstringCompletionContributor return ArrayUtil.EMPTY_OBJECT_ARRAY; } - public List collectTypeVariants() + @RequiredReadAction + public List collectTypeVariants() { - PsiFile file = myElement.getContainingFile(); - ArrayList variants = Lists.newArrayList("str", "int", "basestring", "bool", "buffer", "bytearray", "complex", "dict", "tuple", "enumerate", "file", "float", - "frozenset", "list", "long", "set", "object"); - if(file instanceof PyFile) + List variants = Lists.newArrayList( + "str", "int", "basestring", "bool", "buffer", "bytearray", "complex", "dict", "tuple", "enumerate", "file", "float", + "frozenset", "list", "long", "set", "object" + ); + if(myElement.getContainingFile() instanceof PyFile file) { - variants.addAll(((PyFile) file).getTopLevelClasses()); - List fromImports = ((PyFile) file).getFromImports(); + variants.addAll(file.getTopLevelClasses()); + List fromImports = file.getFromImports(); for(PyFromImportStatement fromImportStatement : fromImports) { PyImportElement[] elements = fromImportStatement.getImportElements(); @@ -162,9 +171,9 @@ public List collectTypeVariants() continue; } PyType type = TypeEvalContext.userInitiated(file.getProject(), CompletionUtilCore.getOriginalOrSelf(file)).getType(referenceExpression); - if(type instanceof PyClassType) + if(type instanceof PyClassType classType) { - variants.add(((PyClassType) type).getPyClass()); + variants.add(classType.getPyClass()); } } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/EpydocString.java b/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/EpydocString.java index 2449707b..beaa65f3 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/EpydocString.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/documentation/docstrings/EpydocString.java @@ -101,8 +101,8 @@ public class EpydocString extends TagBasedDocString { "see" }; - public EpydocString(Substring docstringText) { - super(docstringText, "@"); + public EpydocString(Substring docStringText) { + super(docStringText, "@"); } @Override diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddEncodingQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddEncodingQuickFix.java index f4474a93..bc8b3607 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddEncodingQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddEncodingQuickFix.java @@ -18,6 +18,7 @@ import com.jetbrains.python.impl.inspections.PyEncodingUtil; import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.psi.PyElementGenerator; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiComment; @@ -48,6 +49,8 @@ public LocalizeValue getName() { return PyLocalize.qfixAddEncoding(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiFile file = descriptor.getPsiElement().getContainingFile(); if (file == null) { @@ -57,7 +60,9 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { if (firstLine instanceof PsiComment && firstLine.getText().startsWith("#!")) { firstLine = firstLine.getNextSibling(); } - PsiComment encodingLine = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.forElement(file), PsiComment.class, + PsiComment encodingLine = PyElementGenerator.getInstance(project).createFromText( + LanguageLevel.forElement(file), + PsiComment.class, String.format(PyEncodingUtil.ENCODING_FORMAT_PATTERN[myEncodingFormatIndex], myDefaultEncoding) ); file.addBefore(encodingLine, firstLine); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFieldQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFieldQuickFix.java index 5cdcf02f..b8ad82c7 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFieldQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFieldQuickFix.java @@ -15,15 +15,16 @@ */ package com.jetbrains.python.impl.inspections.quickfix; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.PyNames; import com.jetbrains.python.impl.psi.PyUtil; +import com.jetbrains.python.impl.psi.types.PyClassTypeImpl; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.types.PyClassType; -import com.jetbrains.python.impl.psi.types.PyClassTypeImpl; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; import consulo.fileEditor.FileEditorManager; import consulo.language.editor.CodeInsightUtilCore; @@ -41,8 +42,8 @@ import consulo.python.impl.localize.PyLocalize; import consulo.ui.NotificationType; import consulo.virtualFileSystem.VirtualFile; - import org.jspecify.annotations.Nullable; + import java.util.function.Function; /** @@ -71,6 +72,7 @@ public LocalizeValue getName() { } @Nullable + @RequiredWriteAction public static PsiElement appendToMethod(PyFunction init, Function callback) { // add this field as the last stmt of the constructor PyStatementList statementList = init.getStatementList(); @@ -89,6 +91,8 @@ public static PsiElement appendToMethod(PyFunction init, Function callback) { if (cls != null && itemName != null) { PyFunction init = cls.findMethodByName(PyNames.INIT, false, null); @@ -186,9 +191,11 @@ public static PsiElement addFieldToInit(Project project, PyClass cls, String ite PyStatementList clsContent = cls.getStatementList(); newInit = (PyFunction)clsContent.addAfter(newInit, addAnchor); - PyUtil.showBalloon(project, - PyBundle.message("QFIX.added.constructor.$0.for.field.$1", cls.getName(), itemName), - NotificationType.INFO); + PyUtil.showBalloon( + project, + PyLocalize.qfixAddedConstructor$0ForField$1(cls.getName(), itemName), + NotificationType.INFO + ); PyStatementList statementList = newInit.getStatementList(); PyStatement[] statements = statementList.getStatements(); return statements.length != 0 ? statements[0] : null; @@ -198,6 +205,7 @@ public static PsiElement addFieldToInit(Project project, PyClass cls, String ite } @Nullable + @RequiredReadAction private static PyFunction createInitMethod(Project project, PyClass cls, @Nullable PyFunction ancestorInit) { // found it; copy its param list and make a call to it. if (!FileModificationService.getInstance().preparePsiElementForWrite(cls)) { @@ -263,11 +271,13 @@ private CreateFieldCallback(Project project, String itemName, String initializer myInitializer = initializer; } + @Override public PyStatement apply(String selfName) { - return PyElementGenerator.getInstance(myProject) - .createFromText(LanguageLevel.getDefault(), - PyStatement.class, - selfName + "." + myItemName + " = " + myInitializer); + return PyElementGenerator.getInstance(myProject).createFromText( + LanguageLevel.getDefault(), + PyStatement.class, + selfName + "." + myItemName + " = " + myInitializer + ); } } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFunctionQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFunctionQuickFix.java index 3b5fba3c..85ab9432 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFunctionQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddFunctionQuickFix.java @@ -15,15 +15,16 @@ */ package com.jetbrains.python.impl.inspections.quickfix; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.impl.psi.PyUtil; -import com.jetbrains.python.inspections.PyInspectionExtension; -import com.jetbrains.python.psi.*; import com.jetbrains.python.impl.psi.impl.ParamHelper; import com.jetbrains.python.impl.psi.impl.PyFunctionBuilder; import com.jetbrains.python.impl.psi.types.PyModuleType; +import com.jetbrains.python.inspections.PyInspectionExtension; +import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; import consulo.component.extension.Extensions; import consulo.fileEditor.FileEditorManager; @@ -69,40 +70,40 @@ public LocalizeValue getName() { return PyLocalize.qfixNameAddFunction$0ToModule$1(myIdentifier, myModuleName); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { try { - PsiElement problemElement = descriptor.getPsiElement(); - if (!(problemElement instanceof PyQualifiedExpression)) { + if (!(descriptor.getPsiElement() instanceof PyQualifiedExpression problemElement)) { return; } - PyExpression qualifier = ((PyQualifiedExpression)problemElement).getQualifier(); + PyExpression qualifier = problemElement.getQualifier(); if (qualifier == null) { return; } PyType type = TypeEvalContext.userInitiated(problemElement.getProject(), problemElement.getContainingFile()).getType(qualifier); - if (!(type instanceof PyModuleType)) { + if (!(type instanceof PyModuleType moduleType)) { return; } - PyFile file = ((PyModuleType)type).getModule(); + PyFile file = moduleType.getModule(); sure(file); sure(FileModificationService.getInstance().preparePsiElementForWrite(file)); // try to at least match parameter count // TODO: get parameter style from code style PyFunctionBuilder builder = new PyFunctionBuilder(myIdentifier, problemElement); PsiElement problemParent = problemElement.getParent(); - if (problemParent instanceof PyCallExpression) { - PyArgumentList arglist = ((PyCallExpression)problemParent).getArgumentList(); - if (arglist == null) { + if (problemParent instanceof PyCallExpression callExpr) { + PyArgumentList argList = callExpr.getArgumentList(); + if (argList == null) { return; } - PyExpression[] args = arglist.getArguments(); + PyExpression[] args = argList.getArguments(); for (PyExpression arg : args) { - if (arg instanceof PyKeywordArgument) { // foo(bar) -> def foo(bar_1) - builder.parameter(((PyKeywordArgument)arg).getKeyword()); + if (arg instanceof PyKeywordArgument kwArg) { // foo(bar) -> def foo(bar_1) + builder.parameter(kwArg.getKeyword()); } - else if (arg instanceof PyReferenceExpression) { - PyReferenceExpression refex = (PyReferenceExpression)arg; - builder.parameter(refex.getReferencedName()); + else if (arg instanceof PyReferenceExpression refEx) { + builder.parameter(refEx.getReferencedName()); } else { // use a boring name builder.parameter("param"); @@ -120,7 +121,7 @@ else if (problemParent != null) { } } } - // else: no arglist, use empty args + // else: no argList, use empty args PyFunction function = builder.buildFunction(project, LanguageLevel.forElement(file)); // add to the bottom @@ -129,15 +130,17 @@ else if (problemParent != null) { } catch (IncorrectOperationException ignored) { // we failed. tell about this - PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.function"), NotificationType.ERROR); + PyUtil.showBalloon(project, PyLocalize.qfixFailedToAddFunction(), NotificationType.ERROR); } } + @RequiredReadAction private static void showTemplateBuilder(PyFunction method, PsiFile file) { method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method); final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(method); ParamHelper.walkDownParamArray(method.getParameterList().getParameters(), new ParamHelper.ParamVisitor() { + @Override public void visitNamedParameter(PyNamedParameter param, boolean first, boolean last) { builder.replaceElement(param, param.getName()); } @@ -149,9 +152,8 @@ public void visitNamedParameter(PyNamedParameter param, boolean first, boolean l if (virtualFile == null) { return; } - Editor editor = - FileEditorManager.getInstance(file.getProject()) - .openTextEditor(OpenFileDescriptorFactory.getInstance(file.getProject()).builder(virtualFile).build(), true); + Editor editor = FileEditorManager.getInstance(file.getProject()) + .openTextEditor(OpenFileDescriptorFactory.getInstance(file.getProject()).builder(virtualFile).build(), true); if (editor == null) { return; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddGlobalQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddGlobalQuickFix.java index 1d50eee8..bde40de1 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddGlobalQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddGlobalQuickFix.java @@ -17,6 +17,7 @@ import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.psi.*; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -24,7 +25,7 @@ import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.python.impl.localize.PyLocalize; -import consulo.util.lang.ref.Ref; +import consulo.util.lang.ref.SimpleReference; /** * @author oleg @@ -35,14 +36,15 @@ public LocalizeValue getName() { return PyLocalize.qfixAddGlobal(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiElement problemElt = descriptor.getPsiElement(); - if (problemElt instanceof PyReferenceExpression) { - PyReferenceExpression expression = (PyReferenceExpression)problemElt; + if (problemElt instanceof PyReferenceExpression expression) { final String name = expression.getReferencedName(); ScopeOwner owner = PsiTreeUtil.getParentOfType(problemElt, ScopeOwner.class); 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); + final SimpleReference added = new SimpleReference<>(false); owner.accept(new PyRecursiveElementVisitor(){ @Override public void visitElement(PsiElement element) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddMethodQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddMethodQuickFix.java index 114b6c9b..a6a4d01a 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddMethodQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddMethodQuickFix.java @@ -25,6 +25,8 @@ import com.jetbrains.python.psi.types.PyClassType; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.codeEditor.Editor; import consulo.fileEditor.FileEditorManager; import consulo.language.editor.CodeInsightUtilCore; @@ -69,6 +71,8 @@ public LocalizeValue getName() { return PyLocalize.qfixNameAddMethod$0ToClass$1(myIdentifier, myClassName); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { try { // there can be no name clash, else the name would have resolved, and it hasn't. @@ -84,28 +88,26 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { // try to at least match parameter count // TODO: get parameter style from code style PyFunctionBuilder builder = new PyFunctionBuilder(myIdentifier, cls); - PsiElement pe = problemElement.getParent(); - String decoratorName = null; // set to non-null to add a decorator + String decoratorName = null; // set to non-null to add a decorator PyExpression[] args = PyExpression.EMPTY_ARRAY; - if (pe instanceof PyCallExpression) { - PyArgumentList arglist = ((PyCallExpression)pe).getArgumentList(); - if (arglist == null) { + if (problemElement.getParent() instanceof PyCallExpression call) { + PyArgumentList argList = call.getArgumentList(); + if (argList == null) { return; } - args = arglist.getArguments(); + args = argList.getArguments(); } boolean madeInstance = false; if (callByClass) { if (args.length > 0) { TypeEvalContext context = TypeEvalContext.userInitiated(cls.getProject(), cls.getContainingFile()); - PyType firstArgType = context.getType(args[0]); - if (firstArgType instanceof PyClassType && ((PyClassType)firstArgType).getPyClass().isSubclass(cls, context)) { + if (context.getType(args[0]) instanceof PyClassType firstArgType && firstArgType.getPyClass().isSubclass(cls, context)) { // class, first arg ok: instance method builder.parameter("self"); // NOTE: might use a name other than 'self', according to code style. madeInstance = true; } } - if (!madeInstance) { // class, first arg absent or of different type: classmethod + if (!madeInstance) { // class, first arg absent or of different type: class-method builder.parameter("cls"); // NOTE: might use a name other than 'cls', according to code style. decoratorName = PyNames.CLASSMETHOD; } @@ -119,12 +121,11 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { skipFirst = false; continue; } - if (arg instanceof PyKeywordArgument) { // foo(bar) -> def foo(self, bar_1) - builder.parameter(((PyKeywordArgument)arg).getKeyword()); + if (arg instanceof PyKeywordArgument kwArg) { // foo(bar) -> def foo(self, bar_1) + builder.parameter(kwArg.getKeyword()); } - else if (arg instanceof PyReferenceExpression) { - PyReferenceExpression refex = (PyReferenceExpression)arg; - builder.parameter(refex.getReferencedName()); + else if (arg instanceof PyReferenceExpression refEx) { + builder.parameter(refEx.getReferencedName()); } else { // use a boring name builder.parameter("param"); @@ -148,7 +149,7 @@ else if (arg instanceof PyReferenceExpression) { } catch (IncorrectOperationException ignored) { // we failed. tell about this - PyUtil.showBalloon(project, PyBundle.message("QFIX.failed.to.add.method"), NotificationType.ERROR); + PyUtil.showBalloon(project, PyLocalize.qfixFailedToAddMethod(), NotificationType.ERROR); } } @@ -165,6 +166,7 @@ private static PyClassType getClassType(PsiElement problemElement) { return pyClass != null ? new PyClassTypeImpl(pyClass, false) : null; } + @RequiredReadAction private static void showTemplateBuilder(PyFunction method) { method = CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(method); PsiFile file = method.getContainingFile(); @@ -173,6 +175,7 @@ private static void showTemplateBuilder(PyFunction method) { } final TemplateBuilder builder = TemplateBuilderFactory.getInstance().createTemplateBuilder(method); ParamHelper.walkDownParamArray(method.getParameterList().getParameters(), new ParamHelper.ParamVisitor() { + @Override public void visitNamedParameter(PyNamedParameter param, boolean first, boolean last) { builder.replaceElement(param, param.getName()); } @@ -185,9 +188,8 @@ public void visitNamedParameter(PyNamedParameter param, boolean first, boolean l if (virtualFile == null) { return; } - Editor editor = - FileEditorManager.getInstance(file.getProject()) - .openTextEditor(OpenFileDescriptorFactory.getInstance(file.getProject()).builder(virtualFile).build(), true); + Editor editor = FileEditorManager.getInstance(file.getProject()) + .openTextEditor(OpenFileDescriptorFactory.getInstance(file.getProject()).builder(virtualFile).build(), true); if (editor == null) { return; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddSelfQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddSelfQuickFix.java index 727e51a7..30ae5e7f 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddSelfQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AddSelfQuickFix.java @@ -18,10 +18,10 @@ import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyNamedParameter; import com.jetbrains.python.psi.PyParameterList; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.FileModificationService; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.psi.PsiElement; import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.python.impl.localize.PyLocalize; @@ -44,15 +44,15 @@ public LocalizeValue getName() { return PyLocalize.qfixAddParameterSelf(myParamName); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { - PsiElement problem_elt = descriptor.getPsiElement(); - if (problem_elt instanceof PyParameterList) { - PyParameterList param_list = (PyParameterList) problem_elt; - if (!FileModificationService.getInstance().preparePsiElementForWrite(problem_elt)) { + if (descriptor.getPsiElement() instanceof PyParameterList paramList) { + if (!FileModificationService.getInstance().preparePsiElementForWrite(paramList)) { return; } PyNamedParameter new_param = PyElementGenerator.getInstance(project).createParameter(myParamName); - param_list.addParameter(new_param); + paramList.addParameter(new_param); } } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AugmentedAssignmentQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AugmentedAssignmentQuickFix.java index 6891d5cc..201a2e7f 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AugmentedAssignmentQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/AugmentedAssignmentQuickFix.java @@ -17,6 +17,7 @@ import com.jetbrains.python.impl.psi.impl.PyAugAssignmentStatementImpl; import com.jetbrains.python.psi.*; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiComment; @@ -40,12 +41,12 @@ public LocalizeValue getName() { return PyLocalize.qfixAugmentAssignment(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); - if (element instanceof PyAssignmentStatement && element.isWritable()) { - PyAssignmentStatement statement = (PyAssignmentStatement) element; - + if (element instanceof PyAssignmentStatement statement && element.isWritable()) { PyExpression target = statement.getLeftHandSideExpression(); PyBinaryExpression expression = (PyBinaryExpression) statement.getAssignedValue(); if (expression == null) { @@ -53,8 +54,8 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { } PyExpression leftExpression = expression.getLeftExpression(); PyExpression rightExpression = expression.getRightExpression(); - if (rightExpression instanceof PyParenthesizedExpression) { - rightExpression = ((PyParenthesizedExpression) rightExpression).getContainedExpression(); + if (rightExpression instanceof PyParenthesizedExpression parenthesizedExpr) { + rightExpression = parenthesizedExpr.getContainedExpression(); } if (target != null && rightExpression != null) { String targetText = target.getText(); @@ -74,12 +75,13 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { if (psiOperator == null) { return; } - stringBuilder.append(targetText).append(" "). - append(psiOperator.getText()).append("= ").append(rightExpression.getText()); - PyAugAssignmentStatementImpl augAssignment = - elementGenerator.createFromText(LanguageLevel.forElement(element), - PyAugAssignmentStatementImpl.class, stringBuilder.toString() - ); + stringBuilder.append(targetText).append(" ") + .append(psiOperator.getText()).append("= ").append(rightExpression.getText()); + PyAugAssignmentStatementImpl augAssignment = elementGenerator.createFromText( + LanguageLevel.forElement(element), + PyAugAssignmentStatementImpl.class, + stringBuilder.toString() + ); for (PsiComment comment : comments) augAssignment.add(comment); statement.replace(augAssignment); @@ -88,5 +90,4 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { } } } - } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ChainedComparisonsQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ChainedComparisonsQuickFix.java index 7e7e0632..bfa0f529 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ChainedComparisonsQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ChainedComparisonsQuickFix.java @@ -19,6 +19,8 @@ import com.jetbrains.python.psi.PyBinaryExpression; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyExpression; +import consulo.annotation.access.RequiredReadAction; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -49,29 +51,26 @@ public LocalizeValue getName() { return PyLocalize.qfixChainedComparison(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { - PsiElement expression = descriptor.getPsiElement(); - if (expression != null && expression.isWritable()) { - if (expression instanceof PyBinaryExpression) { - PyExpression leftExpression = ((PyBinaryExpression) expression).getLeftExpression(); - PyExpression rightExpression = ((PyBinaryExpression) expression).getRightExpression(); - if (rightExpression instanceof PyBinaryExpression && leftExpression instanceof PyBinaryExpression) { - if (((PyBinaryExpression) expression).getOperator() == PyTokenTypes.AND_KEYWORD) { - if (getInnerRight && ((PyBinaryExpression) leftExpression).getRightExpression() instanceof PyBinaryExpression - && PyTokenTypes.AND_KEYWORD == ((PyBinaryExpression) leftExpression).getOperator()) { - leftExpression = ((PyBinaryExpression) leftExpression).getRightExpression(); - } - checkOperator((PyBinaryExpression) leftExpression, (PyBinaryExpression) rightExpression, project); - } - } + if (descriptor.getPsiElement() instanceof PyBinaryExpression binaryExpr + && binaryExpr.isWritable() + && binaryExpr.getRightExpression() instanceof PyBinaryExpression rightExpr + && binaryExpr.getLeftExpression() instanceof PyBinaryExpression leftExpr + && binaryExpr.getOperator() == PyTokenTypes.AND_KEYWORD) { + PyBinaryExpression leftRightmostExpr = leftExpr; + if (getInnerRight + && leftExpr.getRightExpression() instanceof PyBinaryExpression leftRightExpression + && PyTokenTypes.AND_KEYWORD == leftExpr.getOperator()) { + leftRightmostExpr = leftRightExpression; } + checkOperator(leftRightmostExpr, rightExpr, project); } } - private void checkOperator( - PyBinaryExpression leftExpression, - PyBinaryExpression rightExpression, Project project - ) { + @RequiredWriteAction + private void checkOperator(PyBinaryExpression leftExpression, PyBinaryExpression rightExpression, Project project) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); if (myIsLeftLeft) { PyExpression newLeftExpression = invertExpression(leftExpression, elementGenerator); @@ -79,63 +78,69 @@ private void checkOperator( if (myIsRightLeft) { PsiElement operator = getLeftestOperator(rightExpression); PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression( - operator.getText(), newLeftExpression, getLargeRightExpression(rightExpression, project)); + operator.getText(), + newLeftExpression, + getLargeRightExpression(rightExpression, project) + ); leftExpression.replace(binaryExpression); rightExpression.delete(); } else { String operator = invertOperator(rightExpression.getPsiOperator()); PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression( - operator, newLeftExpression, rightExpression.getLeftExpression()); + operator, + newLeftExpression, + rightExpression.getLeftExpression() + ); leftExpression.replace(binaryExpression); rightExpression.delete(); } } + else if (myIsRightLeft) { + PsiElement operator = getLeftestOperator(rightExpression); + PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression( + operator.getText(), + leftExpression, + getLargeRightExpression(rightExpression, project) + ); + leftExpression.replace(binaryExpression); + rightExpression.delete(); + } else { - if (myIsRightLeft) { - PsiElement operator = getLeftestOperator(rightExpression); - PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression( - operator.getText(), leftExpression, getLargeRightExpression(rightExpression, project)); - leftExpression.replace(binaryExpression); - rightExpression.delete(); - } - else { - PyExpression expression = rightExpression.getLeftExpression(); - if (expression instanceof PyBinaryExpression) { - expression = invertExpression((PyBinaryExpression) expression, elementGenerator); - } - String operator = invertOperator(rightExpression.getPsiOperator()); - PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression( - operator, leftExpression, expression); - leftExpression.replace(binaryExpression); - rightExpression.delete(); + PyExpression expression = rightExpression.getLeftExpression(); + if (expression instanceof PyBinaryExpression binExpr) { + expression = invertExpression(binExpr, elementGenerator); } + String operator = invertOperator(rightExpression.getPsiOperator()); + PyBinaryExpression binaryExpression = elementGenerator.createBinaryExpression(operator, leftExpression, expression); + leftExpression.replace(binaryExpression); + rightExpression.delete(); } - } private PsiElement getLeftestOperator(PyBinaryExpression expression) { PsiElement op = expression.getPsiOperator(); - while (expression.getLeftExpression() instanceof PyBinaryExpression) { - expression = (PyBinaryExpression) expression.getLeftExpression(); + while (expression.getLeftExpression() instanceof PyBinaryExpression binExpr) { + expression = binExpr; op = expression.getPsiOperator(); } assert op != null; return op; } + @RequiredReadAction private PyExpression invertExpression(PyBinaryExpression leftExpression, PyElementGenerator elementGenerator) { PsiElement operator = leftExpression.getPsiOperator(); PyExpression right = leftExpression.getRightExpression(); PyExpression left = leftExpression.getLeftExpression(); - if (left instanceof PyBinaryExpression) { - left = invertExpression((PyBinaryExpression) left, elementGenerator); + if (left instanceof PyBinaryExpression leftBinary) { + left = invertExpression(leftBinary, elementGenerator); } String newOperator = invertOperator(operator); - return elementGenerator.createBinaryExpression( - newOperator, right, left); + return elementGenerator.createBinaryExpression(newOperator, right, left); } + @RequiredReadAction private String invertOperator(PsiElement op) { if (op.getText().equals(">")) { return "<"; @@ -153,20 +158,17 @@ private String invertOperator(PsiElement op) { } @Nullable + @RequiredReadAction static private PyExpression getLargeRightExpression(PyBinaryExpression expression, Project project) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); PyExpression left = expression.getLeftExpression(); PyExpression right = expression.getRightExpression(); PsiElement operator = expression.getPsiOperator(); - while (left instanceof PyBinaryExpression) { + while (left instanceof PyBinaryExpression leftBinary) { assert operator != null; - right = elementGenerator.createBinaryExpression( - operator.getText(), - ((PyBinaryExpression) left).getRightExpression(), - right - ); - operator = ((PyBinaryExpression) left).getPsiOperator(); - left = ((PyBinaryExpression) left).getLeftExpression(); + right = elementGenerator.createBinaryExpression(operator.getText(), leftBinary.getRightExpression(), right); + operator = leftBinary.getPsiOperator(); + left = leftBinary.getLeftExpression(); } return right; } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ComparisonWithNoneQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ComparisonWithNoneQuickFix.java index 25a1855d..e207cf4d 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ComparisonWithNoneQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ComparisonWithNoneQuickFix.java @@ -20,9 +20,9 @@ import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyElementType; import com.jetbrains.python.psi.PyExpression; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; -import consulo.language.psi.PsiElement; import consulo.localize.LocalizeValue; import consulo.project.Project; import consulo.python.impl.localize.PyLocalize; @@ -37,10 +37,10 @@ public LocalizeValue getName() { return PyLocalize.qfixReplaceEquality(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { - PsiElement problemElement = descriptor.getPsiElement(); - if (problemElement instanceof PyBinaryExpression) { - PyBinaryExpression binaryExpression = (PyBinaryExpression) problemElement; + if (descriptor.getPsiElement() instanceof PyBinaryExpression binaryExpression) { PyElementType operator = binaryExpression.getOperator(); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); String temp; diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CompatibilityPrintCallQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CompatibilityPrintCallQuickFix.java index ef866e0e..76394469 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CompatibilityPrintCallQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CompatibilityPrintCallQuickFix.java @@ -18,6 +18,7 @@ import com.jetbrains.python.psi.LanguageLevel; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyExpression; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -38,22 +39,27 @@ public LocalizeValue getName() { return PyLocalize.qfixStatementEffect(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiElement expression = descriptor.getPsiElement(); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); replacePrint(expression, elementGenerator); } + @RequiredWriteAction private static void replacePrint(PsiElement expression, PyElementGenerator elementGenerator) { StringBuilder stringBuilder = new StringBuilder("print("); PyExpression[] target = PsiTreeUtil.getChildrenOfType(expression, PyExpression.class); if (target != null) { - stringBuilder.append(StringUtil.join(target, o -> o.getText(), ", ")); + stringBuilder.append(StringUtil.join(target, PsiElement::getText, ", ")); } stringBuilder.append(")"); - expression.replace(elementGenerator.createFromText(LanguageLevel.forElement(expression), PyExpression.class, + expression.replace(elementGenerator.createFromText( + LanguageLevel.forElement(expression), + PyExpression.class, stringBuilder.toString() )); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ConvertDocstringQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ConvertDocstringQuickFix.java index 9ecbd1bd..e1f07dd2 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ConvertDocstringQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/ConvertDocstringQuickFix.java @@ -19,6 +19,7 @@ import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyExpression; import com.jetbrains.python.psi.PyStringLiteralExpression; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; @@ -39,14 +40,15 @@ public LocalizeValue getName() { return PyLocalize.qfixConvertSingleQuotedDocstring(); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiElement expression = descriptor.getPsiElement(); if (expression instanceof PyStringLiteralExpression && expression.isWritable()) { PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); String stringText = expression.getText(); - int prefixLength = PyStringLiteralExpressionImpl - .getPrefixLength(stringText); + int prefixLength = PyStringLiteralExpressionImpl.getPrefixLength(stringText); String prefix = stringText.substring(0, prefixLength); String content = stringText.substring(prefixLength); if (content.startsWith("'''")) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CreateClassQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CreateClassQuickFix.java index 37e4d70f..66832a7b 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CreateClassQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/CreateClassQuickFix.java @@ -20,6 +20,7 @@ import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyFile; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.CodeInsightUtilCore; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; @@ -49,6 +50,8 @@ public LocalizeValue getName() { return LocalizeValue.localizeTODO("Create class '" + myClassName + "'"); } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PsiElement anchor = myAnchor; if (!anchor.isValid()) { @@ -59,9 +62,8 @@ public void applyFix(Project project, ProblemDescriptor descriptor) { anchor = anchor.getParent(); } } - PyClass pyClass = PyElementGenerator.getInstance(project).createFromText(LanguageLevel.getDefault(), PyClass.class, - "class " + myClassName + "(object):\n pass" - ); + PyClass pyClass = PyElementGenerator.getInstance(project) + .createFromText(LanguageLevel.getDefault(), PyClass.class, "class " + myClassName + "(object):\n pass"); if (anchor instanceof PyFile) { pyClass = (PyClass) anchor.add(pyClass); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/DocstringQuickFix.java b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/DocstringQuickFix.java index 65b4e9ac..4514e0eb 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/DocstringQuickFix.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/inspections/quickfix/DocstringQuickFix.java @@ -18,6 +18,7 @@ import com.jetbrains.python.impl.codeInsight.intentions.PyGenerateDocstringIntention; import com.jetbrains.python.impl.documentation.docstrings.PyDocstringGenerator; import com.jetbrains.python.psi.*; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.SmartPointerManager; @@ -63,6 +64,8 @@ else if (myUnexpectedParamName != null) { } } + @Override + @RequiredWriteAction public void applyFix(Project project, ProblemDescriptor descriptor) { PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PyDocStringOwner.class); if (docStringOwner == null) { diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/lexer/_PythonLexer.java b/python-impl/src/main/java/com/jetbrains/python/impl/lexer/_PythonLexer.java index b3dc4a79..1759cd10 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/lexer/_PythonLexer.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/lexer/_PythonLexer.java @@ -25,7 +25,6 @@ import consulo.util.lang.CharArrayUtil; import consulo.util.lang.StringUtil; - /** * This class is a scanner generated by * JFlex 1.4.3 @@ -277,8 +276,7 @@ private static int zzUnpackAction(String packed, int offset, int [] result) { return j; } - - /** + /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); @@ -603,7 +601,6 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { return j; } - /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; @@ -614,7 +611,7 @@ private static int zzUnpackTrans(String packed, int offset, int [] result) { /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { - "Unkown internal scanner error", + "Unknown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; @@ -668,10 +665,10 @@ the source of the yytext() string */ /** this buffer may contains the current text array to be matched when it is cheap to acquire it */ private char[] zzBufferArray; - /** the textposition at the last accepting state */ + /** the text-position at the last accepting state */ private int zzMarkedPos; - /** the textposition at the last state to be included in yytext */ + /** the text-position at the last state to be included in yytext */ private int zzPushbackPos; /** the current text position in the buffer */ @@ -680,8 +677,7 @@ the source of the yytext() string */ /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; - /** endRead marks the last character in the buffer, that has been read - from input */ + /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** @@ -696,15 +692,13 @@ the source of the yytext() string */ private boolean zzEOFDone; /* user code: */ -private int getSpaceLength(CharSequence string) { -String string1 = string.toString(); -string1 = StringUtil.trimEnd(string1, "\\"); -string1 = StringUtil.trimEnd(string1, ";"); -String s = StringUtil.trimTrailing(string1); -return yylength()-s.length(); - -} - + private int getSpaceLength(CharSequence string) { + String string1 = string.toString(); + string1 = StringUtil.trimEnd(string1, "\\"); + string1 = StringUtil.trimEnd(string1, ";"); + String s = StringUtil.trimTrailing(string1); + return yylength()-s.length(); + } _PythonLexer(java.io.Reader in) { this.zzReader = in; @@ -738,15 +732,18 @@ private int getSpaceLength(CharSequence string) { return map; } + @Override public final int getTokenStart(){ return zzStartRead; } + @Override public final int getTokenEnd(){ return getTokenStart() + yylength(); } - public void reset(CharSequence buffer, int start, int end,int initialState){ + @Override + public void reset(CharSequence buffer, int start, int end, int initialState){ zzBuffer = buffer; zzBufferArray = CharArrayUtil.fromSequenceWithoutCopying(buffer); zzCurrentPos = zzMarkedPos = zzStartRead = start; @@ -768,25 +765,24 @@ private boolean zzRefill() throws java.io.IOException { return true; } - /** * Returns the current lexical state. */ + @Override public final int yystate() { return zzLexicalState; } - /** * Enters a new lexical state * * @param newState the new lexical state */ + @Override public final void yybegin(int newState) { zzLexicalState = newState; } - /** * Returns the text matched by the current regular expression. */ @@ -794,7 +790,6 @@ public final CharSequence yytext() { return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } - /** * Returns the character at position pos from the * matched text. @@ -810,7 +805,6 @@ public final char yycharat(int pos) { return zzBufferArray != null ? zzBufferArray[zzStartRead+pos]:zzBuffer.charAt(zzStartRead+pos); } - /** * Returns the length of the matched text region. */ @@ -818,11 +812,10 @@ public final int yylength() { return zzMarkedPos-zzStartRead; } - /** - * Reports an error that occured while scanning. + * Reports an error that occurred while scanning. * - * In a wellformed scanner (no or only correct usage of + * In a well-formed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong @@ -831,7 +824,7 @@ public final int yylength() { * Usual syntax/scanner level error handling should be done * in error fallback rules. * - * @param errorCode the code of the errormessage to display + * @param errorCode the code of the error-message to display */ private void zzScanError(int errorCode) { String message; @@ -845,7 +838,6 @@ private void zzScanError(int errorCode) { throw new Error(message); } - /** * Pushes the specified amount of characters back into the input stream. * @@ -861,7 +853,6 @@ public void yypushback(int number) { zzMarkedPos -= number; } - /** * Contains user EOF-code, which will be executed exactly once, * when the end of file is reached @@ -873,7 +864,6 @@ private void zzDoEOF() { } } - /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. @@ -881,6 +871,7 @@ private void zzDoEOF() { * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ + @Override public IElementType advance() throws java.io.IOException { int zzInput; int zzAction; @@ -906,10 +897,8 @@ public IElementType advance() throws java.io.IOException { zzState = ZZ_LEXSTATE[zzLexicalState]; - zzForAction: { while (true) { - if (zzCurrentPosL < zzEndReadL) zzInput = (zzBufferArrayL != null ? zzBufferArrayL[zzCurrentPosL++] : zzBufferL.charAt(zzCurrentPosL++)); else if (zzAtEOF) { @@ -1368,6 +1357,4 @@ else if (zzAtEOF) { } } } - - } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/psi/PyUtil.java b/python-impl/src/main/java/com/jetbrains/python/impl/psi/PyUtil.java index 19eb9ad6..5e6cc928 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/psi/PyUtil.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/psi/PyUtil.java @@ -44,6 +44,7 @@ import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.resolve.RatedResolveResult; import com.jetbrains.python.psi.types.*; +import consulo.annotation.DeprecationInfo; import consulo.annotation.access.RequiredReadAction; import consulo.annotation.access.RequiredWriteAction; import consulo.application.Application; @@ -77,6 +78,7 @@ import consulo.language.psi.util.QualifiedName; import consulo.language.scratch.ScratchFileService; import consulo.language.util.IncorrectOperationException; +import consulo.localize.LocalizeValue; import consulo.module.Module; import consulo.module.ModuleManager; import consulo.module.content.ModuleRootManager; @@ -259,6 +261,20 @@ public static PyFile getContainingPyFile(PyElement element) { * @param notificationType message type, changes the icon and the background. */ // TODO: move to a better place + public static void showBalloon(Project project, LocalizeValue message, NotificationType notificationType) { + showBalloon(project, message.get(), notificationType); + } + + /** + * Shows an information balloon in a reasonable place at the top right of the window. + * + * @param project our project + * @param message the text, HTML markup allowed + * @param notificationType message type, changes the icon and the background. + */ + // TODO: move to a better place + @Deprecated + @DeprecationInfo("Use variant with LocalizeValue") public static void showBalloon(Project project, String message, NotificationType notificationType) { // ripped from com.intellij.openapi.vcs.changes.ui.ChangesViewBalloonProblemNotifier JFrame frame = WindowManager.getInstance().getFrame(project.isDefault() ? null : project); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/psi/types/_PyTypeLexer.java b/python-impl/src/main/java/com/jetbrains/python/impl/psi/types/_PyTypeLexer.java index a1457c44..5a921147 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/psi/types/_PyTypeLexer.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/psi/types/_PyTypeLexer.java @@ -1,5 +1,4 @@ /* The following code was generated by JFlex 1.7.0-SNAPSHOT tweaked for IntelliJ platform */ - package com.jetbrains.python.impl.psi.types; import static com.jetbrains.python.impl.psi.types.PyTypeTokenTypes.IDENTIFIER; @@ -12,7 +11,6 @@ import consulo.language.lexer.FlexLexer; import com.jetbrains.python.psi.PyElementType; - /** * This class is a scanner generated by * JFlex 1.7.0-SNAPSHOT @@ -20,7 +18,6 @@ */ public class _PyTypeLexer implements FlexLexer { - /** * This character denotes the end of file */ @@ -301,7 +298,6 @@ public _PyTypeLexer(java.io.Reader in) this.zzReader = in; } - /** * Unpacks the compressed character translation table. * @@ -331,17 +327,20 @@ private static char[] zzUnpackCMap(String packed) return map; } - public final int getTokenStart() + @Override + public final int getTokenStart() { return zzStartRead; } - public final int getTokenEnd() + @Override + public final int getTokenEnd() { return getTokenStart() + yylength(); } - public void reset(CharSequence buffer, int start, int end, int initialState) + @Override + public void reset(CharSequence buffer, int start, int end, int initialState) { zzBuffer = buffer; zzCurrentPos = zzMarkedPos = zzStartRead = start; @@ -362,27 +361,26 @@ private boolean zzRefill() throws java.io.IOException return true; } - /** * Returns the current lexical state. */ - public final int yystate() + @Override + public final int yystate() { return zzLexicalState; } - /** * Enters a new lexical state * * @param newState the new lexical state */ - public final void yybegin(int newState) + @Override + public final void yybegin(int newState) { zzLexicalState = newState; } - /** * Returns the text matched by the current regular expression. */ @@ -391,7 +389,6 @@ public final CharSequence yytext() return zzBuffer.subSequence(zzStartRead, zzMarkedPos); } - /** * Returns the character at position pos from the * matched text. @@ -407,7 +404,6 @@ public final char yycharat(int pos) return zzBuffer.charAt(zzStartRead + pos); } - /** * Returns the length of the matched text region. */ @@ -416,11 +412,10 @@ public final int yylength() return zzMarkedPos - zzStartRead; } - /** - * Reports an error that occured while scanning. + * Reports an error that occurred while scanning. *

- * In a wellformed scanner (no or only correct usage of + * In a well-formed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong @@ -429,7 +424,7 @@ public final int yylength() * Usual syntax/scanner level error handling should be done * in error fallback rules. * - * @param errorCode the code of the errormessage to display + * @param errorCode the code of the error-message to display */ private void zzScanError(int errorCode) { @@ -446,7 +441,6 @@ private void zzScanError(int errorCode) throw new Error(message); } - /** * Pushes the specified amount of characters back into the input stream. *

@@ -465,7 +459,6 @@ public void yypushback(int number) zzMarkedPos -= number; } - /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. @@ -473,7 +466,8 @@ public void yypushback(int number) * @return the next token * @throws java.io.IOException if any I/O-Error occurs */ - public PyElementType advance() throws java.io.IOException + @Override + public PyElementType advance() throws java.io.IOException { int zzInput; int zzAction; @@ -505,7 +499,6 @@ public PyElementType advance() throws java.io.IOException zzAction = zzState; } - zzForAction: { while(true) @@ -618,5 +611,4 @@ else if(zzAtEOF) } } } - } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/introduce/constant/ConstantValidator.java b/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/introduce/constant/ConstantValidator.java index 085ebd7a..acf266ad 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/introduce/constant/ConstantValidator.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/refactoring/introduce/constant/ConstantValidator.java @@ -13,21 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.refactoring.introduce.constant; -import consulo.language.psi.PsiElement; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.impl.refactoring.introduce.IntroduceValidator; +import consulo.language.psi.PsiElement; +import consulo.python.impl.localize.PyLocalize; /** * @author Alexey.Ivanov */ public class ConstantValidator extends IntroduceValidator { - public String check(String name, PsiElement psiElement) { - if (isDefinedInScope(name, psiElement) || isDefinedInScope(name, psiElement.getContainingFile())) { - return PyBundle.message("refactoring.introduce.constant.scope.error"); + @Override + public String check(String name, PsiElement psiElement) { + if (isDefinedInScope(name, psiElement) || isDefinedInScope(name, psiElement.getContainingFile())) { + return PyLocalize.refactoringIntroduceConstantScopeError().get(); + } + return null; } - return null; - } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/run/AbstractPythonRunConfiguration.java b/python-impl/src/main/java/com/jetbrains/python/impl/run/AbstractPythonRunConfiguration.java index 91900e08..08d7484a 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/run/AbstractPythonRunConfiguration.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/run/AbstractPythonRunConfiguration.java @@ -16,16 +16,15 @@ package com.jetbrains.python.impl.run; import com.google.common.collect.Lists; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.impl.sdk.PythonEnvUtil; import com.jetbrains.python.impl.sdk.PythonSdkType; import com.jetbrains.python.impl.testing.PyPsiLocationWithFixedClass; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.run.AbstractPythonRunConfigurationParams; +import consulo.annotation.access.RequiredReadAction; import consulo.content.bundle.Sdk; import consulo.content.bundle.SdkType; -import consulo.execution.ExecutionBundle; import consulo.execution.RuntimeConfigurationException; import consulo.execution.action.Location; import consulo.execution.configuration.AbstractRunConfiguration; @@ -35,6 +34,7 @@ import consulo.execution.configuration.log.ui.LogConfigurationPanel; import consulo.execution.configuration.ui.SettingsEditor; import consulo.execution.configuration.ui.SettingsEditorGroup; +import consulo.execution.localize.ExecutionLocalize; import consulo.execution.test.AbstractTestProxy; import consulo.execution.ui.awt.EnvironmentVariablesComponent; import consulo.ide.impl.idea.util.PathMappingSettings; @@ -47,6 +47,7 @@ import consulo.process.cmd.GeneralCommandLine; import consulo.process.cmd.ParamsGroup; import consulo.project.Project; +import consulo.python.impl.localize.PyLocalize; import consulo.python.module.extension.PyModuleExtension; import consulo.util.lang.StringUtil; import consulo.util.xml.serializer.InvalidDataException; @@ -54,8 +55,8 @@ import consulo.util.xml.serializer.WriteExternalException; import consulo.virtualFileSystem.VirtualFile; import org.jdom.Element; - import org.jspecify.annotations.Nullable; + import java.io.File; import java.util.HashMap; import java.util.List; @@ -86,23 +87,27 @@ public abstract class AbstractPythonRunConfiguration getValidModules() + @Override + public List getValidModules() { return getValidModules(getProject()); } - public PathMappingSettings getMappingSettings() + @Override + public PathMappingSettings getMappingSettings() { return myMappingSettings; } - public void setMappingSettings(@Nullable PathMappingSettings mappingSettings) + @Override + public void setMappingSettings(@Nullable PathMappingSettings mappingSettings) { myMappingSettings = mappingSettings; } @@ -153,12 +158,12 @@ public final SettingsEditor getConfigurationEditor() SettingsEditorGroup group = new SettingsEditorGroup<>(); // run configuration settings tab: - group.addEditor(ExecutionBundle.message("run.configuration.configuration.tab.title"), runConfigurationEditor); + group.addEditor(ExecutionLocalize.runConfigurationConfigurationTabTitle(), runConfigurationEditor); // tabs provided by extensions: //noinspection unchecked PythonRunConfigurationExtensionsManager.getInstance().appendEditors(this, (SettingsEditorGroup) group); - group.addEditor(ExecutionBundle.message("logs.tab.title"), new LogConfigurationPanel<>()); + group.addEditor(ExecutionLocalize.logsTabTitle(), new LogConfigurationPanel<>()); return group; } @@ -197,11 +202,11 @@ private void checkSdk() throws RuntimeConfigurationError { if(StringUtil.isEmptyOrSpaces(getSdkHome())) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_sdk")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_sdk()); } else if(!PythonSdkType.getInstance().isValidSdkHome(getSdkHome())) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_valid_sdk")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_valid_sdk()); } } else @@ -209,12 +214,13 @@ else if(!PythonSdkType.getInstance().isValidSdkHome(getSdkHome())) Sdk sdk = PythonSdkType.findPythonSdk(getModule()); if(sdk == null) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_module_sdk")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_module_sdk()); } } } - public String getSdkHome() + @Override + public String getSdkHome() { String sdkHome = mySdkHome; if(StringUtil.isEmptyOrSpaces(mySdkHome)) @@ -260,7 +266,8 @@ public Sdk getSdk() } } - public void readExternal(Element element) throws InvalidDataException + @Override + public void readExternal(Element element) throws InvalidDataException { super.readExternal(element); myInterpreterOptions = JDOMExternalizerUtil.readField(element, "INTERPRETER_OPTIONS"); @@ -292,7 +299,8 @@ protected void readEnvs(Element element) EnvironmentVariablesComponent.readExternal(element, getEnvs()); } - public void writeExternal(Element element) throws WriteExternalException + @Override + public void writeExternal(Element element) throws WriteExternalException { super.writeExternal(element); JDOMExternalizerUtil.writeField(element, "INTERPRETER_OPTIONS", myInterpreterOptions); @@ -319,43 +327,51 @@ protected void writeEnvs(Element element) EnvironmentVariablesComponent.writeExternal(element, getEnvs()); } - public String getInterpreterOptions() + @Override + public String getInterpreterOptions() { return myInterpreterOptions; } - public void setInterpreterOptions(String interpreterOptions) + @Override + public void setInterpreterOptions(String interpreterOptions) { myInterpreterOptions = interpreterOptions; } - public String getWorkingDirectory() + @Override + public String getWorkingDirectory() { return myWorkingDirectory; } - public void setWorkingDirectory(String workingDirectory) + @Override + public void setWorkingDirectory(String workingDirectory) { myWorkingDirectory = workingDirectory; } - public void setSdkHome(String sdkHome) + @Override + public void setSdkHome(String sdkHome) { mySdkHome = sdkHome; } @Nullable + @Override public Module getModule() { return getConfigurationModule().getModule(); } - public boolean isUseModuleSdk() + @Override + public boolean isUseModuleSdk() { return myUseModuleSdk; } - public void setUseModuleSdk(boolean useModuleSdk) + @Override + public void setUseModuleSdk(boolean useModuleSdk) { myUseModuleSdk = useModuleSdk; } @@ -404,7 +420,8 @@ public static void copyParams(AbstractPythonRunConfigurationParams source, Abstr * * @param commandLine what to patch */ - public void patchCommandLine(GeneralCommandLine commandLine) + @Override + public void patchCommandLine(GeneralCommandLine commandLine) { String interpreterPath = getInterpreterPath(); Sdk sdk = getSdk(); @@ -489,7 +506,8 @@ public boolean canRunWithCoverage() * @param failedTest failed test * @return string spec or null if spec calculation is impossible */ - @Nullable + @Nullable + @RequiredReadAction public String getTestSpec(Location location, AbstractTestProxy failedTest) { PsiElement element = location.getPsiElement(); diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/testing/AbstractPythonTestRunConfiguration.java b/python-impl/src/main/java/com/jetbrains/python/impl/testing/AbstractPythonTestRunConfiguration.java index 5f7eddc6..21d71759 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/testing/AbstractPythonTestRunConfiguration.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/testing/AbstractPythonTestRunConfiguration.java @@ -15,13 +15,13 @@ */ package com.jetbrains.python.impl.testing; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; +import com.jetbrains.python.impl.run.AbstractPythonRunConfiguration; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFile; import com.jetbrains.python.psi.PyFunction; -import com.jetbrains.python.impl.run.AbstractPythonRunConfiguration; import com.jetbrains.python.run.AbstractPythonRunConfigurationParams; +import consulo.annotation.access.RequiredReadAction; import consulo.execution.RuntimeConfigurationException; import consulo.execution.configuration.ConfigurationFactory; import consulo.execution.configuration.RuntimeConfigurationError; @@ -33,6 +33,7 @@ import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.project.Project; +import consulo.python.impl.localize.PyLocalize; import consulo.util.io.FileUtil; import consulo.util.lang.Comparing; import consulo.util.lang.StringUtil; @@ -42,12 +43,12 @@ import consulo.virtualFileSystem.LocalFileSystem; import consulo.virtualFileSystem.VirtualFile; import org.jdom.Element; - import org.jspecify.annotations.Nullable; + import java.io.File; /** - * User: catherine + * @author catherine */ public abstract class AbstractPythonTestRunConfiguration extends AbstractPythonRunConfiguration implements AbstractPythonRunConfigurationParams, AbstractPythonTestRunConfigurationParams, RefactoringListenerProvider { @@ -60,6 +61,7 @@ public abstract class AbstractPythonTestRunConfiguration extends AbstractPythonR private String myPattern = ""; // pattern for modules in folder to match against private boolean usePattern = false; + @RequiredReadAction protected AbstractPythonTestRunConfiguration(Project project, ConfigurationFactory configurationFactory) { super(project, configurationFactory); } @@ -118,62 +120,77 @@ public void writeExternal(Element element) throws WriteExternalException { JDOMExternalizerUtil.writeField(element, "USE_PATTERN", String.valueOf(usePattern)); } + @Override public AbstractPythonRunConfigurationParams getBaseParams() { return this; } + @Override public String getClassName() { return myClassName; } + @Override public void setClassName(String className) { myClassName = className; } + @Override public String getFolderName() { return myFolderName; } + @Override public void setFolderName(String folderName) { myFolderName = folderName; } + @Override public String getScriptName() { return myScriptName; } + @Override public void setScriptName(String scriptName) { myScriptName = scriptName; } + @Override public String getMethodName() { return myMethodName; } + @Override public void setMethodName(String methodName) { myMethodName = methodName; } + @Override public TestType getTestType() { return myTestType; } + @Override public void setTestType(TestType testType) { myTestType = testType; } + @Override public String getPattern() { return myPattern; } + @Override public void setPattern(String pattern) { myPattern = pattern; } + @Override public boolean usePattern() { return usePattern; } + @Override public void usePattern(boolean usePattern) { this.usePattern = usePattern; } @@ -191,19 +208,19 @@ public void checkConfiguration() throws RuntimeConfigurationException { super.checkConfiguration(); if (StringUtil.isEmptyOrSpaces(myFolderName) && myTestType == TestType.TEST_FOLDER) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_folder_name")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_folder_name()); } if (StringUtil.isEmptyOrSpaces(getScriptName()) && myTestType != TestType.TEST_FOLDER) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_script_name")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_script_name()); } if (StringUtil.isEmptyOrSpaces(myClassName) && (myTestType == TestType.TEST_METHOD || myTestType == TestType.TEST_CLASS)) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_class_name")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_class_name()); } if (StringUtil.isEmptyOrSpaces(myMethodName) && (myTestType == TestType.TEST_METHOD || myTestType == TestType.TEST_FUNCTION)) { - throw new RuntimeConfigurationError(PyBundle.message("runcfg.unittest.no_method_name")); + throw new RuntimeConfigurationError(PyLocalize.runcfgUnittestNo_method_name()); } } @@ -290,6 +307,7 @@ public String getActionName() { protected abstract String getPluralTitle(); + @RequiredReadAction @Override public RefactoringElementListener getRefactoringElementListener(PsiElement element) { if (element instanceof PsiDirectory) { @@ -343,12 +361,13 @@ public void undoElementMovedOrRenamed(PsiElement newElement, String oldQualified } }; } - if (element instanceof PyClass && (myTestType == TestType.TEST_CLASS || myTestType == TestType.TEST_METHOD) && - Comparing.equal(((PyClass)element).getName(), myClassName)) { + if (element instanceof PyClass pyClass && (myTestType == TestType.TEST_CLASS || myTestType == TestType.TEST_METHOD) && + Comparing.equal(pyClass.getName(), myClassName)) { return new RefactoringElementAdapter() { @Override + @RequiredReadAction protected void elementRenamedOrMoved(PsiElement newElement) { - myClassName = ((PyClass)newElement).getName(); + myClassName = ((PyClass) newElement).getName(); } @Override @@ -357,13 +376,13 @@ public void undoElementMovedOrRenamed(PsiElement newElement, String oldQualified } }; } - if (element instanceof PyFunction && Comparing.equal(((PyFunction)element).getName(), myMethodName)) { - ScopeOwner scopeOwner = PsiTreeUtil.getParentOfType(element, ScopeOwner.class); - if ((myTestType == TestType.TEST_FUNCTION && scopeOwner instanceof PyFile) || (myTestType == TestType.TEST_METHOD && scopeOwner instanceof PyClass && Comparing - .equal(scopeOwner - .getName(), myClassName))) { + if (element instanceof PyFunction function && Comparing.equal(function.getName(), myMethodName)) { + ScopeOwner scopeOwner = PsiTreeUtil.getParentOfType(function, ScopeOwner.class); + if ((myTestType == TestType.TEST_FUNCTION && scopeOwner instanceof PyFile) + || (myTestType == TestType.TEST_METHOD && scopeOwner instanceof PyClass && Comparing.equal(scopeOwner.getName(), myClassName))) { return new RefactoringElementAdapter() { @Override + @RequiredReadAction protected void elementRenamedOrMoved(PsiElement newElement) { myMethodName = ((PyFunction)newElement).getName(); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterable.java b/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterable.java index 2ea10332..40a6d027 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterable.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterable.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.toolbox; import org.jspecify.annotations.Nullable; @@ -23,8 +22,8 @@ /** * Iterable that splices other iterables and iterates over them sequentially. - * User: dcheryasov - * Date: Nov 20, 2009 8:01:23 AM + * @author dcheryasov + * @since 2009-11-20 */ public class ChainIterable extends ChainedListBase> implements Iterable { @@ -40,7 +39,7 @@ public ChainIterable(T initial) { super(Collections.singleton(initial)); } - + @Override public ChainIterable add(Iterable another) { return (ChainIterable)super.add(another); } @@ -71,8 +70,6 @@ public boolean isEmpty() { } public Iterator iterator() { - - class IterMixedIn extends ChainIterationMixin> { IterMixedIn(ChainedListBase> link) { super(link); @@ -85,35 +82,34 @@ public Iterator toIterator(Iterable first) { } final IterMixedIn mixin = new IterMixedIn(this); - class Iter extends ChainedListBase> implements Iterator { - Iter(ChainedListBase> piggybacked) { super(piggybacked.myPayload); myNext = piggybacked.myNext; } + @Override public boolean hasNext() { return mixin.hasNext(); } + @Override public void remove() { throw new UnsupportedOperationException(); // we don't remove things } + @Override public T next() { //noinspection RedundantCast return (T)mixin.next(); } - } return new Iter(this); - } @Override public String toString() { - return FP.fold(new FP.StringCollector(), this, new StringBuilder()).toString(); + return FP.fold(new FP.StringCollector<>(), this, new StringBuilder()).toString(); } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterator.java b/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterator.java index 8e2773c7..dd17fb7b 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterator.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/toolbox/ChainIterator.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.toolbox; import org.jspecify.annotations.Nullable; @@ -22,8 +21,9 @@ /** * An iterator that combines several other iterators and exhaust them one by one, in chain. - * User: dcheryasov - * Date: Nov 19, 2009 3:49:38 AM + * + * @author dcheryasov + * @since 2009-11-19 */ public class ChainIterator extends ChainedListBase> implements Iterator { @@ -36,7 +36,7 @@ public class ChainIterator extends ChainedListBase> implements It public ChainIterator(@Nullable Iterator initial) { super(initial); - myMixin = new ChainIterationMixin>(this) { + myMixin = new ChainIterationMixin<>(this) { @Override public Iterator toIterator(Iterator first) { return first; @@ -44,26 +44,28 @@ public Iterator toIterator(Iterator first) { }; } - /** * Adds another iterator to the chain. Values from this iterator will follow the values of the iterator passed to the constructor. * Adding after the iteration has started is safe. * @param another iterator to add to the end of the chain. * @return self, for easy chaining. */ + @Override public ChainIterator add(Iterator another) { return (ChainIterator)super.add(another); } - + @Override public boolean hasNext() { return myMixin.hasNext(); } + @Override public T next() { return myMixin.next(); } + @Override public void remove() { throw new UnsupportedOperationException("Cannot remove from ChainIterator"); } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/ui/IdeaDialog.java b/python-impl/src/main/java/com/jetbrains/python/impl/ui/IdeaDialog.java index 92dc5ec5..6d4ff85e 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/ui/IdeaDialog.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/ui/IdeaDialog.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.ui; import consulo.project.Project; @@ -28,7 +27,7 @@ /** * @author Alexei Orischenko - * Date: Nov 30, 2009 + * @since 2009-11-30 */ public abstract class IdeaDialog extends DialogWrapper { @@ -45,14 +44,17 @@ private void updateOkButton() { } private class MyDocumentListener implements DocumentListener { + @Override public void insertUpdate(DocumentEvent documentEvent) { updateOkButton(); } + @Override public void removeUpdate(DocumentEvent documentEvent) { updateOkButton(); } + @Override public void changedUpdate(DocumentEvent documentEvent) { updateOkButton(); } @@ -63,10 +65,6 @@ protected void addUpdater(JTextField field) { } protected void addUpdater(JToggleButton check) { - check.addActionListener(new ActionListener() { - public void actionPerformed(ActionEvent actionEvent) { - updateOkButton(); - } - }); + check.addActionListener(actionEvent -> updateOkButton()); } } diff --git a/python-impl/src/main/java/com/jetbrains/python/impl/validation/AssignTargetAnnotator.java b/python-impl/src/main/java/com/jetbrains/python/impl/validation/AssignTargetAnnotator.java index 56882147..32ff47e9 100644 --- a/python-impl/src/main/java/com/jetbrains/python/impl/validation/AssignTargetAnnotator.java +++ b/python-impl/src/main/java/com/jetbrains/python/impl/validation/AssignTargetAnnotator.java @@ -13,14 +13,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.jetbrains.python.impl.validation; -import consulo.virtualFileSystem.VirtualFile; -import com.jetbrains.python.impl.PyBundle; import com.jetbrains.python.PyNames; -import com.jetbrains.python.psi.*; import com.jetbrains.python.impl.sdk.PythonSdkType; +import com.jetbrains.python.psi.*; +import consulo.annotation.access.RequiredReadAction; +import consulo.localize.LocalizeValue; +import consulo.python.impl.localize.PyLocalize; +import consulo.virtualFileSystem.VirtualFile; /** * @author yole @@ -76,65 +77,72 @@ public void visitPyWithItem(PyWithItem node) { private class ExprVisitor extends PyElementVisitor { private final Operation myOp; - private final String DELETING_NONE = PyBundle.message("ANN.deleting.none"); - private final String ASSIGNMENT_TO_NONE = PyBundle.message("ANN.assign.to.none"); - private final String CANT_ASSIGN_TO_FUNCTION_CALL = PyBundle.message("ANN.cant.assign.to.call"); - private final String CANT_DELETE_FUNCTION_CALL = PyBundle.message("ANN.cant.delete.call"); public ExprVisitor(Operation op) { myOp = op; } @Override + @RequiredReadAction public void visitPyReferenceExpression(PyReferenceExpression node) { String referencedName = node.getReferencedName(); if (PyNames.NONE.equals(referencedName)) { - getHolder().createErrorAnnotation(node, (myOp == Operation.Delete) ? DELETING_NONE : ASSIGNMENT_TO_NONE); + getHolder().newError(myOp == Operation.Delete ? PyLocalize.annDeletingNone() : PyLocalize.annAssignToNone()).range(node).create(); } } @Override + @RequiredReadAction public void visitPyTargetExpression(PyTargetExpression node) { String targetName = node.getName(); if (PyNames.NONE.equals(targetName)) { - VirtualFile vfile = node.getContainingFile().getVirtualFile(); - if (vfile != null && !vfile.getUrl().contains("/" + PythonSdkType.SKELETON_DIR_NAME + "/")){ - getHolder().createErrorAnnotation(node, (myOp == Operation.Delete) ? DELETING_NONE : ASSIGNMENT_TO_NONE); + VirtualFile vFile = node.getContainingFile().getVirtualFile(); + if (vFile != null && !vFile.getUrl().contains("/" + PythonSdkType.SKELETON_DIR_NAME + "/")){ + getHolder().newError(myOp == Operation.Delete ? PyLocalize.annDeletingNone() : PyLocalize.annAssignToNone()).range(node).create(); } } if (PyNames.DEBUG.equals(targetName)) { if (LanguageLevel.forElement(node).isPy3K()) { - getHolder().createErrorAnnotation(node, "assignment to keyword"); + getHolder().newError(LocalizeValue.localizeTODO("assignment to keyword")).range(node).create(); } else { - getHolder().createErrorAnnotation(node, "cannot assign to __debug__"); + getHolder().newError(LocalizeValue.localizeTODO("cannot assign to __debug__")).range(node).create(); } } } @Override + @RequiredReadAction public void visitPyCallExpression(PyCallExpression node) { - getHolder().createErrorAnnotation(node, (myOp == Operation.Delete) ? CANT_DELETE_FUNCTION_CALL : CANT_ASSIGN_TO_FUNCTION_CALL); + getHolder() + .newError(myOp == Operation.Delete ? PyLocalize.annCantDeleteCall() : PyLocalize.annCantAssignToCall()) + .range(node) + .create(); } @Override + @RequiredReadAction public void visitPyGeneratorExpression(PyGeneratorExpression node) { - getHolder().createErrorAnnotation(node, PyBundle.message( - myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.generator" : "ANN.cant.assign.to.generator")); + getHolder() + .newError(myOp == Operation.AugAssign ? PyLocalize.annCantAugAssignToGenerator() : PyLocalize.annCantAssignToGenerator()) + .range(node) + .create(); } @Override + @RequiredReadAction public void visitPyBinaryExpression(PyBinaryExpression node) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.assign.to.operator")); + getHolder().newError(PyLocalize.annCantAssignToOperator()).range(node).create(); } @Override + @RequiredReadAction public void visitPyTupleExpression(PyTupleExpression node) { if (node.getElements().length == 0) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.assign.to.parens")); + getHolder().newError(PyLocalize.annCantAssignToParens()).range(node).create(); } else if (myOp == Operation.AugAssign) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.aug.assign.to.tuple.or.generator")); + getHolder().newError(PyLocalize.annCantAugAssignToTupleOrGenerator()).range(node).create(); } else { node.acceptChildren(this); @@ -142,9 +150,10 @@ else if (myOp == Operation.AugAssign) { } @Override + @RequiredReadAction public void visitPyParenthesizedExpression(PyParenthesizedExpression node) { if (myOp == Operation.AugAssign) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.aug.assign.to.tuple.or.generator")); + getHolder().newError(PyLocalize.annCantAugAssignToTupleOrGenerator()).range(node).create(); } else { node.acceptChildren(this); @@ -152,12 +161,13 @@ public void visitPyParenthesizedExpression(PyParenthesizedExpression node) { } @Override + @RequiredReadAction public void visitPyListLiteralExpression(PyListLiteralExpression node) { if (node.getElements().length == 0) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.assign.to.brackets")); + getHolder().newError(PyLocalize.annCantAssignToBrackets()).range(node).create(); } else if (myOp == Operation.AugAssign) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.aug.assign.to.list.or.comprh")); + getHolder().newError(PyLocalize.annCantAugAssignToListOrComprh()).range(node).create(); } else { node.acceptChildren(this); @@ -165,62 +175,88 @@ else if (myOp == Operation.AugAssign) { } @Override + @RequiredReadAction public void visitPyListCompExpression(PyListCompExpression node) { - markError(node, PyBundle.message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.comprh" : "ANN.cant.assign.to.comprh")); + getHolder() + .newError(myOp == Operation.AugAssign ? PyLocalize.annCantAugAssignToComprh() : PyLocalize.annCantAssignToComprh()) + .range(node) + .create(); } @Override + @RequiredReadAction public void visitPyDictCompExpression(PyDictCompExpression node) { - markError(node, PyBundle.message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.dict.comprh" : "ANN.cant.assign.to.dict.comprh")); + getHolder() + .newError(myOp == Operation.AugAssign ? PyLocalize.annCantAugAssignToDictComprh() : PyLocalize.annCantAssignToDictComprh()) + .range(node) + .create(); } @Override + @RequiredReadAction public void visitPySetCompExpression(PySetCompExpression node) { - markError(node, PyBundle.message(myOp == Operation.AugAssign ? "ANN.cant.aug.assign.to.set.comprh" : "ANN.cant.assign.to.set.comprh")); + getHolder() + .newError(myOp == Operation.AugAssign ? PyLocalize.annCantAugAssignToSetComprh() : PyLocalize.annCantAssignToSetComprh()) + .range(node) + .create(); } @Override + @RequiredReadAction public void visitPyStarExpression(PyStarExpression node) { super.visitPyStarExpression(node); if (!(node.getParent() instanceof PySequenceExpression)) { - markError(node, "starred assignment target must be in a list or tuple"); + getHolder().newError(LocalizeValue.localizeTODO("starred assignment target must be in a list or tuple")).range(node).create(); } } @Override + @RequiredReadAction public void visitPyDictLiteralExpression(PyDictLiteralExpression node) { checkLiteral(node); } @Override + @RequiredReadAction public void visitPySetLiteralExpression(PySetLiteralExpression node) { checkLiteral(node); } + @Override + @RequiredReadAction public void visitPyNumericLiteralExpression(PyNumericLiteralExpression node) { checkLiteral(node); } + @Override + @RequiredReadAction public void visitPyStringLiteralExpression(PyStringLiteralExpression node) { checkLiteral(node); } + @RequiredReadAction private void checkLiteral(PyExpression node) { - getHolder().createErrorAnnotation(node, PyBundle.message(myOp == Operation.Delete? "ANN.cant.delete.literal" : "ANN.cant.assign.to.literal")); + getHolder().newError(myOp == Operation.Delete ? PyLocalize.annCantDeleteLiteral() : PyLocalize.annCantAssignToLiteral()) + .range(node) + .create(); } + @Override + @RequiredReadAction public void visitPyLambdaExpression(PyLambdaExpression node) { - getHolder().createErrorAnnotation(node, PyBundle.message("ANN.cant.assign.to.lambda")); + getHolder().newError(PyLocalize.annCantAssignToLambda()).range(node).create(); } @Override + @RequiredReadAction public void visitPyNoneLiteralExpression(PyNoneLiteralExpression node) { - getHolder().createErrorAnnotation(node, "assignment to keyword"); + getHolder().newError(LocalizeValue.localizeTODO("assignment to keyword")).range(node).create(); } @Override + @RequiredReadAction public void visitPyBoolLiteralExpression(PyBoolLiteralExpression node) { - getHolder().createErrorAnnotation(node, "assignment to keyword"); + getHolder().newError(LocalizeValue.localizeTODO("assignment to keyword")).range(node).create(); } } }