From a77547446a7aae1c4354658cdc42c8ece649f241 Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Wed, 23 May 2012 15:12:25 +0200 Subject: [PATCH 01/45] enable error reporting for Android UI Designer --- plugins/android-designer/src/META-INF/plugin.xml | 1 + plugins/ui-designer/ui-designer-new/src/META-INF/plugin.xml | 3 +++ 2 files changed, 4 insertions(+) diff --git a/plugins/android-designer/src/META-INF/plugin.xml b/plugins/android-designer/src/META-INF/plugin.xml index 6fc6233692a6..e14f2545aae2 100644 --- a/plugins/android-designer/src/META-INF/plugin.xml +++ b/plugins/android-designer/src/META-INF/plugin.xml @@ -11,6 +11,7 @@ com.intellij.ui-designer-new + + + + From 42f136ba0eaf63037a729addf036b3b54372d22a Mon Sep 17 00:00:00 2001 From: Dmitry Jemerov Date: Wed, 23 May 2012 17:58:18 +0200 Subject: [PATCH 02/45] unfortunately the SSR path macro filter must be in the platform --- .../StructuralSearchPathMacroFilter.java | 35 +++++++++++++++++++ .../src/META-INF/LangExtensions.xml | 1 + 2 files changed, 36 insertions(+) create mode 100644 platform/lang-impl/src/com/intellij/openapi/application/StructuralSearchPathMacroFilter.java diff --git a/platform/lang-impl/src/com/intellij/openapi/application/StructuralSearchPathMacroFilter.java b/platform/lang-impl/src/com/intellij/openapi/application/StructuralSearchPathMacroFilter.java new file mode 100644 index 000000000000..b42ba1701b31 --- /dev/null +++ b/platform/lang-impl/src/com/intellij/openapi/application/StructuralSearchPathMacroFilter.java @@ -0,0 +1,35 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.openapi.application; + +import org.jdom.Attribute; + +/** + * Since SSR inspections can be stored in inspection profiles and loaded by users who don't have the SSR plugin installed, unfortunately + * this must be in the platform and not in the SSR plugin. + * + * @author yole + */ +public class StructuralSearchPathMacroFilter extends PathMacroFilter { + @Override + public boolean skipPathMacros(Attribute attribute) { + final String parentName = attribute.getParent().getName(); + if ("replaceConfiguration".equals(parentName) || "searchConfiguration".equals(parentName)) { + return true; + } + return false; + } +} diff --git a/platform/platform-resources/src/META-INF/LangExtensions.xml b/platform/platform-resources/src/META-INF/LangExtensions.xml index 27da33d8d9d3..6080ee552079 100644 --- a/platform/platform-resources/src/META-INF/LangExtensions.xml +++ b/platform/platform-resources/src/META-INF/LangExtensions.xml @@ -772,4 +772,5 @@ order="first, before commitCompletion"/> + From b3069dc58a8e76c9d1f5010252b9babcd0166bc0 Mon Sep 17 00:00:00 2001 From: "Maxim.Medvedev" Date: Wed, 23 May 2012 14:31:21 +0400 Subject: [PATCH 03/45] \n after doc comments --- .../formatter/processors/GroovySpacingProcessorBasic.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java index 75746daa40df..d758275b6368 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java @@ -78,6 +78,10 @@ public abstract class GroovySpacingProcessorBasic { return LAZY_SPACING; } + if (leftType == GROOVY_DOC_COMMENT) { + return COMMON_SPACING_WITH_NL; + } + //For type parameters if (mLT == leftType && right instanceof GrTypeParameter || mGT == rightType && left instanceof GrTypeParameter || From cf9446dfa4d2d1f4d5ecbcdc7f1c555695037cc7 Mon Sep 17 00:00:00 2001 From: "Maxim.Medvedev" Date: Wed, 23 May 2012 14:44:15 +0400 Subject: [PATCH 04/45] reformat created groovy class --- .../jetbrains/plugins/groovy/actions/NewGroovyClassAction.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java index cdd5e6d8436c..bab6c05bdeb5 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/actions/NewGroovyClassAction.java @@ -32,6 +32,7 @@ import com.intellij.psi.JavaDirectoryService; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; +import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.GroovyBundle; @@ -112,6 +113,7 @@ public class NewGroovyClassAction extends JavaCreateTemplateInPackageAction Date: Thu, 24 May 2012 12:56:28 +0400 Subject: [PATCH 05/45] IDEA-86550 Groovy: Correct 'Smart complete statement' for the control flow and conditional operators --- .../plugins/groovy/formatter/GroovyBraceEnforcer.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBraceEnforcer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBraceEnforcer.java index 948bde9ff652..371c27c025c6 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBraceEnforcer.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/GroovyBraceEnforcer.java @@ -34,10 +34,7 @@ import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; -import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement; +import org.jetbrains.plugins.groovy.lang.psi.api.statements.*; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock; /** @@ -118,7 +115,7 @@ public class GroovyBraceEnforcer extends GroovyRecursiveElementVisitor { } private void processStatement(GrStatement statement, GrStatement blockCandidate, int options) { - if (blockCandidate instanceof GrCodeBlock || blockCandidate == null) return; + if (blockCandidate instanceof GrCodeBlock || blockCandidate instanceof GrBlockStatement || blockCandidate == null) return; if (options == CommonCodeStyleSettings.FORCE_BRACES_ALWAYS || options == CommonCodeStyleSettings.FORCE_BRACES_IF_MULTILINE && PostFormatProcessorHelper.isMultiline(statement)) { replaceWithBlock(statement, blockCandidate); From a671f5af073750f0fde81cd32a9fe1617693dee9 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 24 May 2012 14:04:59 +0400 Subject: [PATCH 06/45] NPE --- .../src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java index 73d7335e87d1..ad2ce95af9fc 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java @@ -32,6 +32,7 @@ class ConstantExpressionPredicate implements PsiElementPredicate { } final PsiPolyadicExpression expression = (PsiPolyadicExpression)element; final PsiType expressionType = expression.getType(); + if (expressionType == null) return false; if (expressionType.equalsToText("java.lang.String")) { // intention disabled for string concatenations because of performance issues on // relatively common large string expressions. From 30efd8ab5ff784769c0e0388c06ba284e201e2c6 Mon Sep 17 00:00:00 2001 From: Rustam Vishnyakov Date: Thu, 24 May 2012 14:15:14 +0400 Subject: [PATCH 07/45] Better diagnostic message for block realignment --- .../AbstractBlockAlignmentProcessor.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/formatting/AbstractBlockAlignmentProcessor.java b/platform/lang-impl/src/com/intellij/formatting/AbstractBlockAlignmentProcessor.java index 329cab1f1e7a..d166573bdb97 100644 --- a/platform/lang-impl/src/com/intellij/formatting/AbstractBlockAlignmentProcessor.java +++ b/platform/lang-impl/src/com/intellij/formatting/AbstractBlockAlignmentProcessor.java @@ -15,7 +15,9 @@ */ package com.intellij.formatting; +import com.intellij.diagnostic.LogMessageEx; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.util.TextRange; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -85,12 +87,20 @@ public abstract class AbstractBlockAlignmentProcessor implements BlockAlignmentP // alignment of blocks located before them and post error every time we detect endless cycle. Set blocksCausedRealignment = context.backwardShiftedAlignedBlocks.get(offsetResponsibleBlock); if (blocksCausedRealignment != null && blocksCausedRealignment.contains(context.targetBlock)) { - LOG.error(String.format("Please create dedicated ticket at the tracker with the content of the current editor attached%n%n" - + "Formatting error - code block %s is set to be shifted right because of its alignment with " - + "block %s more than once. I.e. moving the former block because of alignment algorithm causes " - + "subsequent block to be shifted right as well - cyclic dependency.%nDebug info: %s", - offsetResponsibleBlock.getTextRange(), context.targetBlock.getTextRange(), context.targetBlock.getDebugInfo() - )); + StringBuilder messageBuilder = new StringBuilder(); + TextRange targetRange = context.targetBlock.getTextRange(); + messageBuilder.append( + String.format("Formatting error - code block %s is set to be shifted right because of its alignment with " + + "block %s more than once. I.e. moving the former block because of alignment algorithm causes " + + "subsequent block to be shifted right as well - cyclic dependency.", + offsetResponsibleBlock.getTextRange(), targetRange + )); + messageBuilder.append(context.targetBlock.getDebugInfo()); + messageBuilder.append("\nBlock content: '") + .append(context.document.getText().substring(targetRange.getStartOffset(), targetRange.getEndOffset())) + .append("'\n"); + messageBuilder.append("Note: document text is attached to this report."); + LogMessageEx.error(LOG, messageBuilder.toString(), context.document.getText()); blocksCausedRealignment.add(context.targetBlock); return Result.UNABLE_TO_ALIGN_BACKWARD_BLOCK; } From f486f0a08ba41d04b87ffea78c2b07ace6ca2ade Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Thu, 24 May 2012 12:54:25 +0200 Subject: [PATCH 08/45] avoid using empty encoding --- .../impl/src/com/intellij/compiler/server/BuildManager.java | 2 +- .../src/org/jetbrains/jps/cmdline/BuildSession.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 0efa25f378ac..44a9e6ab979b 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -525,7 +525,7 @@ public class BuildManager implements ApplicationComponent{ } final String defaultCharset = EncodingManager.getInstance().getDefaultCharsetName(); - if (defaultCharset != null) { + if (!StringUtil.isEmpty(defaultCharset)) { cmdBuilder.setGlobalEncoding(defaultCharset); } diff --git a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java index 7838b9d84135..5ec0df3ea587 100644 --- a/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java +++ b/jps/jps-builders/src/org/jetbrains/jps/cmdline/BuildSession.java @@ -477,7 +477,7 @@ final class BuildSession implements Runnable, CanceledStatus { final String loadPath = isDirectoryBased(projectFile) ? new File(projectFile, IDEA_PROJECT_DIRNAME).getPath() : projectPath; IdeaProjectLoader.loadFromPath(project, loadPath, myPathVars, null, new SystemOutErrorReporter(false)); final String globalEncoding = myGlobalEncoding; - if (globalEncoding != null && project.getProjectCharset() == null) { + if (!StringUtil.isEmpty(globalEncoding) && project.getProjectCharset() == null) { project.setProjectCharset(globalEncoding); } project.getIgnoredFilePatterns().loadFromString(myIgnorePatterns); From cb3ffa1a7eebebeb52c8be5eb7605256ba70d480 Mon Sep 17 00:00:00 2001 From: "Denis.Zhdanov" Date: Thu, 24 May 2012 12:53:44 +0400 Subject: [PATCH 09/45] IDEA-19061 Integrate the Rearranger-plugin into core-IDEA More tests have been refactored and enabled --- .../com/wrq/rearranger/RearrangerTest.groovy | 46 ++++++++----------- .../rearranger/util/RearrangerTestDsl.java | 2 +- .../util/SettingsConfigurationBuilder.groovy | 8 ++++ 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy index 7487b73ca465..a0204dd778aa 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy @@ -495,7 +495,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { name: GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX, body: GetterSetterDefinition.GETTER_BODY_IMMATERIAL ) - setterCriteria( + 'setter criteria'( name: GetterSetterDefinition.SETTER_NAME_CORRECT_PREFIX, body: GetterSetterDefinition.SETTER_BODY_IMMATERIAL ) @@ -641,7 +641,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { name: GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX, body: GetterSetterDefinition.GETTER_BODY_RETURNS ) - setterCriteria( + 'setter criteria'( name: GetterSetterDefinition.SETTER_NAME_CORRECT_PREFIX, body: GetterSetterDefinition.SETTER_BODY_IMMATERIAL ) } @@ -691,7 +691,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } } } public void testSpacingOptions() throws Exception { - /** + /* * From Thomas Singer: * I've enabled * - Force 0 blank lines before class close brace "}" @@ -869,29 +869,22 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { fieldRule.create { } } } -// public void testExcludeFromExtraction() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest36.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementTest36.java"); -// } -// -// public void testInterferingGSNames() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest37.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rs.setKeepGettersSettersTogether(true); -// rs.getDefaultGSDefinition().setGetterBodyCriterion(GetterSetterDefinition.GETTER_BODY_IMMATERIAL); -// rs.getDefaultGSDefinition().setGetterNameCriterion(GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX); -// rs.getDefaultGSDefinition().setSetterBodyCriterion(GetterSetterDefinition.SETTER_BODY_IMMATERIAL); -// rs.getDefaultGSDefinition().setSetterNameCriterion(GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult37.java"); -// } -// + public void testExcludeFromExtraction() throws Exception { doTest('RearrangementTest36', 'RearrangementTest36') } + + public void testInterferingGSNames() throws Exception { + doTest('RearrangementTest37', 'RearrangementResult37') { + settings.configure { + 'keep together'( 'getters and setters' ) + 'getter criteria'( + name: GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX, + body: GetterSetterDefinition.GETTER_BODY_IMMATERIAL + ) + 'setter criteria'( + name: GetterSetterDefinition.SETTER_NAME_CORRECT_PREFIX, + body: GetterSetterDefinition.SETTER_BODY_IMMATERIAL + ) + } } } + // public void testInterferingGSNamesNoKGSTogether() throws Exception { // configureByFile("/com/wrq/rearranger/RearrangementTest37.java"); // final PsiFile file = getFile(); @@ -1360,7 +1353,6 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { doTest(srcFileName, expectedResultFileName, 'java', adjustment) } - private void doTest(@NotNull String srcFileName, @Nullable String expectedResultFileName, @Nullable String extension, @Nullable Closure adjustment = null) { diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java index 07bdde6296db..7af715290453 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java @@ -33,7 +33,7 @@ public enum RearrangerTestDsl { SORT, COMMENT, GETTER_CRITERIA("getter criteria"), - SETTER_CRITERIA("setterCriteria"), + SETTER_CRITERIA("setter criteria"), SPACING, PRECEDING_COMMENT("preceding comment"), TRAILING_COMMENT("trailing comment"), diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/SettingsConfigurationBuilder.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/util/SettingsConfigurationBuilder.groovy index fe06eb05731d..4a5bcdc5ecc6 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/SettingsConfigurationBuilder.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/SettingsConfigurationBuilder.groovy @@ -68,6 +68,14 @@ class SettingsConfigurationBuilder extends BuilderSupport { setIf(RearrangerTestDsl.ORDER, attributes, 'overloadedOrder', settings) setIf(RearrangerTestDsl.KEEP_TOGETHER, attributes, 'keepOverloadedMethodsTogether', settings) break + case RearrangerTestDsl.GETTER_CRITERIA.value: + setIf(RearrangerTestDsl.NAME, attributes, 'getterNameCriterion', settings.defaultGSDefinition) + setIf(RearrangerTestDsl.BODY, attributes, 'getterBodyCriterion', settings.defaultGSDefinition) + break + case RearrangerTestDsl.SETTER_CRITERIA.value: + setIf(RearrangerTestDsl.NAME, attributes, 'setterNameCriterion', settings.defaultGSDefinition) + setIf(RearrangerTestDsl.BODY, attributes, 'setterBodyCriterion', settings.defaultGSDefinition) + break default: setIf(RearrangerTestDsl.REARRANGE_INNER_CLASSES, attributes, 'rearrangeInnerClasses', settings) if (attributes[RearrangerTestDsl.CLASS_COMMENT.value]) { From ad2b057a68388e50ec4ec959ad64076578f482f1 Mon Sep 17 00:00:00 2001 From: "Denis.Zhdanov" Date: Thu, 24 May 2012 14:34:18 +0400 Subject: [PATCH 10/45] IDEA-19061 Integrate the Rearranger-plugin into core-IDEA More tests have been refactored and enabled --- .../com/wrq/rearranger/RearrangerTest.groovy | 166 +++++++----------- .../rearranger/util/RearrangerTestDsl.java | 3 +- .../util/java/AbstractJavaRuleBuilder.groovy | 9 +- .../java/{SortType.java => SortOption.java} | 4 +- .../wrq/rearranger/RearrangementTest38cfg.xml | 4 +- 5 files changed, 78 insertions(+), 108 deletions(-) rename plugins/rearranger/test/src/com/wrq/rearranger/util/java/{SortType.java => SortOption.java} (59%) diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy index a0204dd778aa..27399a4c2420 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy @@ -24,6 +24,7 @@ package com.wrq.rearranger; import com.intellij.openapi.application.ApplicationManager import com.intellij.psi.PsiModifier +import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase import com.wrq.rearranger.settings.CommentRule import com.wrq.rearranger.settings.RearrangerSettings @@ -36,7 +37,6 @@ import com.wrq.rearranger.util.SettingsConfigurationBuilder import org.jetbrains.annotations.NotNull import org.jetbrains.annotations.Nullable import com.wrq.rearranger.util.java.* -import com.intellij.testFramework.PlatformTestUtil /** JUnit tests for the rearranger plugin. */ class RearrangerTest extends LightCodeInsightFixtureTestCase { @@ -136,7 +136,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { doTest('RearrangementTest', 'RearrangementResult9') { methodRule.create { target([ MethodType.GETTER_OR_SETTER, MethodType.OTHER ]) - sort(SortType.BY_NAME) + 'sort by'( SortOption.BY_NAME ) } } } public final void testSimpleComment() throws Exception { @@ -197,11 +197,11 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } fieldRule.create { modifier([ PsiModifier.PUBLIC, PsiModifier.STATIC, PsiModifier.FINAL ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } fieldRule.create { modifier([ PsiModifier.PUBLIC, PsiModifier.STATIC ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//************************************** PUBLIC FIELDS *****************************************', @@ -210,7 +210,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } fieldRule.create { modifier( PsiModifier.PUBLIC ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//*********************************** PROTECTED/PACKAGE FIELDS **************************************', @@ -219,15 +219,15 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } fieldRule.create { modifier([ PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL, PsiModifier.STATIC, PsiModifier.FINAL ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } fieldRule.create { modifier([ PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL, PsiModifier.STATIC ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } fieldRule.create { modifier([ PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//************************************** PRIVATE FIELDS *****************************************', @@ -236,7 +236,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } fieldRule.create { modifier( PsiModifier.PRIVATE ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//************************************** CONSTRUCTORS ************************************* ', @@ -256,11 +256,11 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { methodRule.create { modifier( PsiModifier.PUBLIC ) target( MethodType.GETTER_OR_SETTER ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } methodRule.create { target( MethodType.GETTER_OR_SETTER ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } def text = '//************************************** PUBLIC METHODS ************************************* ' if (doublePublicMethods) { @@ -272,7 +272,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } methodRule.create { modifier( PsiModifier.PUBLIC ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//********************************* PACKAGE/PROTECTED METHODS ******************************** ', @@ -281,7 +281,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } methodRule.create { modifier([ PsiModifier.PROTECTED, PsiModifier.PACKAGE_LOCAL ]) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//************************************** PRIVATE METHODS *************************************', @@ -290,14 +290,14 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { } methodRule.create { modifier( PsiModifier.PRIVATE ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('//************************************** INNER CLASSES ************************************* ', condition: CommentRule.EMIT_IF_ITEMS_MATCH_SUBSEQUENT_RULE, 'all subsequent': true, 'all preceding': true, 'subsequent rules to match': 1, 'preceding rules to match': 1) } - innerClassRule.create { sort(SortType.BY_NAME ) } + innerClassRule.create { 'sort by'(SortOption.BY_NAME ) } mySettings.extractedMethodsSettings.moveExtractedMethods = false if (doGlobalPattern) { @@ -463,7 +463,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { methodRule.create { target( MethodType.CONSTRUCTOR ) } methodRule.create { target( MethodType.GETTER_OR_SETTER ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } } } public final void testKeepGSWithProperty() throws Exception { @@ -476,7 +476,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { methodRule.create { target(MethodType.CONSTRUCTOR) } methodRule.create { target( MethodType.GETTER_OR_SETTER ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } } } public final void testKeepGSWithPropertyElseTogether() throws Exception { @@ -499,10 +499,10 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { name: GetterSetterDefinition.SETTER_NAME_CORRECT_PREFIX, body: GetterSetterDefinition.SETTER_BODY_IMMATERIAL ) - sort( SortType.BY_NAME ) + 'sort by'( SortOption.BY_NAME ) } commentRule.create { comment('// Other Methods', condition: CommentRule.EMIT_ALWAYS) } - methodRule.create { sort( SortType.BY_NAME ) } + methodRule.create { 'sort by'( SortOption.BY_NAME ) } } } public final void testKeepOverloadsTogetherOriginalOrder() throws Exception { @@ -527,7 +527,7 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { public final void testMultipleFieldDecl() throws Exception { doTest('RearrangementTest21', 'RearrangementResult21') { - fieldRule.create { sort( SortType.BY_NAME ) } + fieldRule.create { 'sort by'( SortOption.BY_NAME ) } } } public final void testRemoveBlankLines() throws Exception { @@ -885,87 +885,51 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { ) } } } -// public void testInterferingGSNamesNoKGSTogether() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest37.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rs.setKeepGettersSettersTogether(false); -// rs.getDefaultGSDefinition().setGetterBodyCriterion(GetterSetterDefinition.GETTER_BODY_IMMATERIAL); -// rs.getDefaultGSDefinition().setGetterNameCriterion(GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX); -// rs.getDefaultGSDefinition().setSetterBodyCriterion(GetterSetterDefinition.SETTER_BODY_IMMATERIAL); -// rs.getDefaultGSDefinition().setSetterNameCriterion(GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementTest37.java"); -// } -// -// public void testRemoveBlankLineInsideMethodBug() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest38.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// File settingsFile = new File(InteractiveTest.DEFAULT_CONFIGURATION_ROOT + -// "/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml"); -// rs = RearrangerSettings.getSettingsFromFile(settingsFile); -// rs.setAskBeforeRearranging(false); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementTest38.java"); -// } -// -// public void testSortFieldsByTypeAndName() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest39.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// FieldAttributes fa = new FieldAttributes(); -// fa.getSortAttr().setByType(true); -// fa.getSortAttr().setByName(true); -// rs.addItem(fa, 0); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult39B.java"); -// } -// -// public void testSortFieldsByType() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest39.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// FieldAttributes fa = new FieldAttributes(); -// fa.getSortAttr().setByType(true); -// fa.getSortAttr().setByName(false); -// rs.addItem(fa, 0); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult39C.java"); -// } -// -// public void testSortFieldsByTypeICAndName() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest39.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// FieldAttributes fa = new FieldAttributes(); -// fa.getSortAttr().setByType(true); -// fa.getSortAttr().setTypeCaseInsensitive(true); -// fa.getSortAttr().setByName(true); -// rs.addItem(fa, 0); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult39.java"); -// } -// -// public void testSortFieldsByTypeIC() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest39.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// FieldAttributes fa = new FieldAttributes(); -// fa.getSortAttr().setByType(true); -// fa.getSortAttr().setTypeCaseInsensitive(true); -// fa.getSortAttr().setByName(false); -// rs.addItem(fa, 0); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult39A.java"); -// } -// + public void testInterferingGSNamesNoKGSTogether() throws Exception { + doTest('RearrangementTest37', 'RearrangementTest37') { + settings.configure { + 'getter criteria'( + name: GetterSetterDefinition.GETTER_NAME_CORRECT_PREFIX, + body: GetterSetterDefinition.GETTER_BODY_IMMATERIAL + ) + 'setter criteria'( + name: GetterSetterDefinition.SETTER_NAME_CORRECT_PREFIX, + body: GetterSetterDefinition.SETTER_BODY_IMMATERIAL + ) + } } } + + public void testRemoveBlankLineInsideMethodBug() throws Exception { + doTest('RearrangementTest38', 'RearrangementTest38') { + setupSettings('/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml') + } } + + public void testSortFieldsByTypeAndName() throws Exception { + doTest('RearrangementTest39', 'RearrangementResult39B') { + fieldRule.create { + 'sort by'([ SortOption.BY_NAME, SortOption.BY_TYPE ]) + } } } + + public void testSortFieldsByType() throws Exception { + doTest('RearrangementTest39', 'RearrangementResult39C') { + fieldRule.create { + 'sort by' SortOption.BY_TYPE + 'not sort by' SortOption.BY_NAME + } + } } + + public void testSortFieldsByTypeICAndName() throws Exception { + doTest('RearrangementTest39', 'RearrangementResult39') { + fieldRule.create { + 'sort by'([ SortOption.BY_NAME, SortOption.BY_TYPE, SortOption.TYPE_CASE_INSENSITIVE ]) + } } } + + public void testSortFieldsByTypeIC() throws Exception { + doTest('RearrangementTest39', 'RearrangementResult39A') { + fieldRule.create { + 'sort by'([ SortOption.BY_TYPE, SortOption.TYPE_CASE_INSENSITIVE ]) + 'not sort by' SortOption.BY_NAME + } } } + // /** // * test detection of method overrides/overridden/implements/implemented attributes. // * diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java index 7af715290453..bcba515070d4 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java @@ -30,7 +30,8 @@ public enum RearrangerTestDsl { TARGET, TYPE, RETURN_TYPE("return type"), - SORT, + SORT("sort by"), + NOT_SORT("not sort by"), COMMENT, GETTER_CRITERIA("getter criteria"), SETTER_CRITERIA("setter criteria"), diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/AbstractJavaRuleBuilder.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/AbstractJavaRuleBuilder.groovy index 1ffbe3a767e2..8540a5a9e6cb 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/AbstractJavaRuleBuilder.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/AbstractJavaRuleBuilder.groovy @@ -18,10 +18,17 @@ abstract class AbstractJavaRuleBuilder extends AbstractRuleBuilder {{ }) // Sort - def sortOptions = [ (SortType.BY_NAME) : "byName"] + def sortOptions = [ + (SortOption.BY_NAME) : 'byName', + (SortOption.BY_TYPE) : 'byType', + (SortOption.TYPE_CASE_INSENSITIVE) : 'typeCaseInsensitive', + ] registerHandler(RearrangerTestDsl.SORT, { data, attributes, rule -> rule.sortOptions."${sortOptions[data]}" = true }) + registerHandler(RearrangerTestDsl.NOT_SORT, { data, attributes, rule -> + rule.sortOptions."${sortOptions[data]}" = false + }) // Modifiers // Visibility diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortType.java b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortOption.java similarity index 59% rename from plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortType.java rename to plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortOption.java index ab035a85809e..77f8340bdf26 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortType.java +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/SortOption.java @@ -4,6 +4,6 @@ package com.wrq.rearranger.util.java; * @author Denis Zhdanov * @since 5/17/12 3:57 PM */ -public enum SortType { - BY_NAME +public enum SortOption { + BY_NAME, BY_TYPE, TYPE_CASE_INSENSITIVE } diff --git a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml index d900d4239981..96f82645dfe9 100644 --- a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml +++ b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementTest38cfg.xml @@ -179,9 +179,7 @@ noExtractedMethods="false"/> - \n\ - \ //////////////////////////////////////////////\n\ \ //\ Instance\ Methods\n\ \ ////////////////////////////////////////////// - + \n //////////////////////////////////////////////\n // Instance Methods\n ////////////////////////////////////////////// From e8229b26259cc14892eaef45dee2d021f3c6f7f5 Mon Sep 17 00:00:00 2001 From: "Denis.Zhdanov" Date: Thu, 24 May 2012 14:51:47 +0400 Subject: [PATCH 11/45] IDEA-19061 Integrate the Rearranger-plugin into core-IDEA More tests have been refactored and enabled --- .../com/wrq/rearranger/RearrangerTest.groovy | 101 +++++------------- .../rearranger/util/RearrangerTestDsl.java | 5 +- .../util/java/JavaMethodRuleBuilder.groovy | 22 +++- .../wrq/rearranger/RearrangementResult41.java | 3 +- .../wrq/rearranger/RearrangementResult43.java | 2 +- 5 files changed, 56 insertions(+), 77 deletions(-) diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy index 27399a4c2420..8f6737079a92 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy @@ -930,78 +930,35 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { 'not sort by' SortOption.BY_NAME } } } -// /** -// * test detection of method overrides/overridden/implements/implemented attributes. -// * -// * @throws Exception test exception -// */ -// public void testOverImpl() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest40.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult40.java"); -// } -// -// public final void testRemoveBlankLinesBeforeMethod() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest41.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rs.getAfterClassLBrace().setForce(true); -// rs.getAfterClassLBrace().setnBlankLines(0); -// rs.getBeforeMethodLBrace().setForce(true); -// rs.getBeforeMethodLBrace().setnBlankLines(0); -// rs.getAfterMethodLBrace().setForce(true); -// rs.getAfterMethodLBrace().setnBlankLines(0); -// rs.getBeforeMethodRBrace().setForce(true); -// rs.getBeforeMethodRBrace().setnBlankLines(0); -// rs.getAfterMethodRBrace().setForce(true); -// rs.getAfterMethodRBrace().setnBlankLines(0); -// rs.getBeforeClassRBrace().setForce(true); -// rs.getBeforeClassRBrace().setnBlankLines(0); -// rs.getAfterClassRBrace().setForce(true); -// rs.getAfterClassRBrace().setnBlankLines(0); -// rs.setRemoveBlanksInsideCodeBlocks(true); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult41.java"); -// } -// -// public final void testEnumClass() throws Exception { -// final Project project = getProject(); -// final LanguageLevelProjectExtension llpExtension = LanguageLevelProjectExtension.getInstance(project); -// LanguageLevel oldLevel = llpExtension.getLanguageLevel(); -// llpExtension.setLanguageLevel(LanguageLevel.JDK_1_5); -// configureByFile("/com/wrq/rearranger/RearrangementTest42.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult42.java"); -// llpExtension.setLanguageLevel(oldLevel); -// } -// -// public final void testNumParameters() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest43.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// MethodAttributes ma; -// ma = new MethodAttributes(); -// ma.getMinParamsAttr().setMatch(true); -// ma.getMinParamsAttr().setValue(2); -// ma.getMaxParamsAttr().setMatch(true); -// ma.getMaxParamsAttr().setValue(3); -// rs.addItem(ma, 0); -// ma = new MethodAttributes(); -// ma.getMinParamsAttr().setMatch(true); -// ma.getMinParamsAttr().setValue(1); -// rs.addItem(ma, 1); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult43.java"); -// } -// + /** + * test detection of method overrides/overridden/implements/implemented attributes. + * + * @throws Exception test exception + */ + public void testOverImpl() throws Exception { doTest('RearrangementTest40', 'RearrangementResult40') } + + public final void testRemoveBlankLinesBeforeMethod() throws Exception { + doTest('RearrangementTest41', 'RearrangementResult41') { + spacingRule.create { + spacing(anchor: [ SpacingAnchor.AFTER_CLASS_LBRACE, SpacingAnchor.BEFORE_METHOD_LBRACE, SpacingAnchor.AFTER_METHOD_LBRACE, + SpacingAnchor.BEFORE_METHOD_RBRACE, SpacingAnchor.AFTER_METHOD_RBRACE, SpacingAnchor.BEFORE_CLASS_RBRACE, + SpacingAnchor.AFTER_CLASS_RBRACE], + lines: 0, 'remove blank lines': true) + } + } + } + + public final void testEnumClass() throws Exception { doTest('RearrangementTest42', 'RearrangementResult42') } + + public final void testNumParameters() throws Exception { + doTest('RearrangementTest43', 'RearrangementResult43') { + methodRule.create { + 'arguments number' ( from: 2, to: 3) + } + methodRule.create { + 'arguments number' ( from: 1) + } } } + // public final void testGeneratedComment() throws Exception { // configureByFile("/com/wrq/rearranger/RearrangementTest44.java"); // final PsiFile file = getFile(); diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java index bcba515070d4..d8266f988955 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java @@ -57,7 +57,10 @@ public enum RearrangerTestDsl { BELOW_FIRST_CALLER("below first caller"), NON_PRIVATE_TREATMENT("non-private treatment"), REARRANGE_INNER_CLASSES("rearranger inner classes"), - CLASS_COMMENT("class comment"); + CLASS_COMMENT("class comment"), + ARGUMENTS_NUMBER("arguments number"), + FROM, + TO; @NotNull private final String myValue; diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/JavaMethodRuleBuilder.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/JavaMethodRuleBuilder.groovy index 8b7c40b76d67..215e912de1bf 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/java/JavaMethodRuleBuilder.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/java/JavaMethodRuleBuilder.groovy @@ -14,12 +14,14 @@ class JavaMethodRuleBuilder extends AbstractJavaRuleBuilder { { def handlers = [ - (MethodType.CONSTRUCTOR) : createRawBooleanAttributeHandler('constructorMethodType'), + (MethodType.CONSTRUCTOR) : createRawBooleanAttributeHandler('constructorMethodType'), (MethodType.GETTER_OR_SETTER) : createRawBooleanAttributeHandler('getterSetterMethodType'), - (MethodType.OTHER) : createRawBooleanAttributeHandler('otherMethodType') + (MethodType.OTHER) : createRawBooleanAttributeHandler('otherMethodType') ] registerHandler(RearrangerTestDsl.TARGET, { data, attributes, rule -> handlers[data](attributes, rule) }) registerHandler(RearrangerTestDsl.RETURN_TYPE, createStringAttributeHandler('returnTypeAttr')) + + // Getters & setters criteria. registerHandler(RearrangerTestDsl.GETTER_CRITERIA, { data, attributes, rule -> RearrangerTestUtil.setIf(RearrangerTestDsl.NAME, attributes, 'getterNameCriterion', rule.getterSetterDefinition) RearrangerTestUtil.setIf(RearrangerTestDsl.BODY, attributes, 'getterBodyCriterion', rule.getterSetterDefinition) @@ -28,6 +30,22 @@ class JavaMethodRuleBuilder extends AbstractJavaRuleBuilder { RearrangerTestUtil.setIf(RearrangerTestDsl.NAME, attributes, 'setterNameCriterion', rule.getterSetterDefinition) RearrangerTestUtil.setIf(RearrangerTestDsl.BODY, attributes, 'setterBodyCriterion', rule.getterSetterDefinition) }) + + // Args number. + def argsNumber = [ + (RearrangerTestDsl.FROM) : 'minParamsAttr', + (RearrangerTestDsl.TO) : 'maxParamsAttr' + ] + def argsNumberHandler = { RearrangerTestDsl key, attributes, rule -> + if (attributes.containsKey(key.value)) { + rule."${argsNumber[key]}".match = true + rule."${argsNumber[key]}".value = attributes[key.value] + } + } + registerHandler(RearrangerTestDsl.ARGUMENTS_NUMBER, { data, attributes, rule -> + argsNumberHandler(RearrangerTestDsl.FROM, attributes, rule) + argsNumberHandler(RearrangerTestDsl.TO, attributes, rule) + }) } @Override diff --git a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult41.java b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult41.java index 899c73d58aea..ac91dac03562 100644 --- a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult41.java +++ b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult41.java @@ -1,5 +1,6 @@ public class RearrangementTest41 { - public final void setPrice(final double price) { + public final void setPrice(final double price) + { this.price = price; } } diff --git a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult43.java b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult43.java index 3c9995a3c124..049fbd8b5b6b 100644 --- a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult43.java +++ b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult43.java @@ -1,4 +1,5 @@ public class RearrangementTest43 { + void method2(int a, int b) { } @@ -7,7 +8,6 @@ public class RearrangementTest43 { void method1(int a) { } - void method0() { } } From 1cec92ada39c5844b847536fe8476212d64c4024 Mon Sep 17 00:00:00 2001 From: "Denis.Zhdanov" Date: Thu, 24 May 2012 15:11:51 +0400 Subject: [PATCH 12/45] IDEA-19061 Integrate the Rearranger-plugin into core-IDEA More tests have been refactored and enabled --- .../com/wrq/rearranger/RearrangerTest.groovy | 27 +++++-------------- .../rearranger/util/CommentRuleBuilder.groovy | 17 ++++++++---- .../rearranger/util/RearrangerTestDsl.java | 5 +++- .../wrq/rearranger/RearrangementResult44.java | 2 +- 4 files changed, 24 insertions(+), 27 deletions(-) diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy index 8f6737079a92..adfa21cd1d41 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/RearrangerTest.groovy @@ -959,26 +959,13 @@ class RearrangerTest extends LightCodeInsightFixtureTestCase { 'arguments number' ( from: 1) } } } -// public final void testGeneratedComment() throws Exception { -// configureByFile("/com/wrq/rearranger/RearrangementTest44.java"); -// final PsiFile file = getFile(); -// final Document doc = PsiDocumentManager.getInstance(getProject()).getDocument(file); -// final RearrangerActionHandler rah = new RearrangerActionHandler(); -// CommentRule cr = new CommentRule(); -// CommentFillString cfs = cr.getCommentFillString(); -// cfs.setFillString("-+"); -// cfs.setUseProjectWidthForFill(false); -// cfs.setFillWidth(30); -// cr.setEmitCondition(CommentRule.EMIT_ALWAYS); -// cr.setCommentText("// %FS% METHODS %FS%"); -// rs.addItem(cr, 0); -// MethodAttributes ma; -// ma = new MethodAttributes(); // match all methods -// rs.addItem(ma, 1); -// rah.rearrangeDocument(getProject(), file, rs, doc); -// super.checkResultByFile("/com/wrq/rearranger/RearrangementResult44.java"); -// } -// + public final void testGeneratedComment() throws Exception { + doTest('RearrangementTest44', 'RearrangementResult44') { + commentRule.comment('// %FS% METHODS %FS%', condition: CommentRule.EMIT_ALWAYS, 'fill string': '-+', + 'use project width for fill': false, 'fill width': 30) + methodRule.create { } // match all methods + } } + // public void testEnum1() throws Exception { // final Project project = getProject(); // final LanguageLevelProjectExtension llpExtension = LanguageLevelProjectExtension.getInstance(project); diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/CommentRuleBuilder.groovy b/plugins/rearranger/test/src/com/wrq/rearranger/util/CommentRuleBuilder.groovy index 868238943cc7..0c9b4a4ac17b 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/CommentRuleBuilder.groovy +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/CommentRuleBuilder.groovy @@ -13,11 +13,18 @@ class CommentRuleBuilder extends AbstractRuleBuilder { { registerHandler(RearrangerTestDsl.COMMENT, { data, attributes, rule -> rule.commentText = data - RearrangerTestUtil.setIf(RearrangerTestDsl.CONDITION, attributes, 'emitCondition', rule) - RearrangerTestUtil.setIf(RearrangerTestDsl.ALL_SUBSEQUENT, attributes, 'allSubsequentRules', rule) - RearrangerTestUtil.setIf(RearrangerTestDsl.ALL_PRECEDING, attributes, 'allPrecedingRules', rule) - RearrangerTestUtil.setIf(RearrangerTestDsl.SUBSEQUENT_RULES_TO_MATCH, attributes, 'NSubsequentRulesToMatch', rule) - RearrangerTestUtil.setIf(RearrangerTestDsl.PRECEDING_RULES_TO_MATCH, attributes, 'NPrecedingRulesToMatch', rule) + RearrangerTestUtil.setIf(RearrangerTestDsl.CONDITION, attributes, 'emitCondition', rule) + RearrangerTestUtil.setIf(RearrangerTestDsl.ALL_SUBSEQUENT, attributes, 'allSubsequentRules', rule) + RearrangerTestUtil.setIf(RearrangerTestDsl.ALL_PRECEDING, attributes, 'allPrecedingRules', rule) + RearrangerTestUtil.setIf(RearrangerTestDsl.SUBSEQUENT_RULES_TO_MATCH, attributes, 'NSubsequentRulesToMatch', rule) + RearrangerTestUtil.setIf(RearrangerTestDsl.PRECEDING_RULES_TO_MATCH, attributes, 'NPrecedingRulesToMatch', rule) + + def fillString = rule.commentFillString + RearrangerTestUtil.setIf(RearrangerTestDsl.USE_PROJECT_WIDTH_FOR_COMMENT_FILL, attributes, 'useProjectWidthForFill', fillString) + RearrangerTestUtil.setIf(RearrangerTestDsl.FILL_WIDTH, attributes, 'fillWidth', fillString) + if (attributes[RearrangerTestDsl.FILL_STRING.value]) { + rule.commentFillString.fillString = attributes[RearrangerTestDsl.FILL_STRING.value] + } }) } diff --git a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java index d8266f988955..04e6c62be229 100644 --- a/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java +++ b/plugins/rearranger/test/src/com/wrq/rearranger/util/RearrangerTestDsl.java @@ -60,7 +60,10 @@ public enum RearrangerTestDsl { CLASS_COMMENT("class comment"), ARGUMENTS_NUMBER("arguments number"), FROM, - TO; + TO, + FILL_STRING("fill string"), + USE_PROJECT_WIDTH_FOR_COMMENT_FILL("use project width for fill"), + FILL_WIDTH("fill width"); @NotNull private final String myValue; diff --git a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult44.java b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult44.java index 8a24d11d1a0d..ef7dac09dd16 100644 --- a/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult44.java +++ b/plugins/rearranger/test/testData/com/wrq/rearranger/RearrangementResult44.java @@ -1,6 +1,6 @@ /** test generated comment with fill. */ public class RearrangementTest44 { - // -+-+-+-+- METHODS -+-+-+-+- +// -+-+-+-+- METHODS -+-+-+-+- private void method(int i) { } } From 157f33e3f3ba211b7bd6afe728b66d4594a4e429 Mon Sep 17 00:00:00 2001 From: "Denis.Zhdanov" Date: Thu, 24 May 2012 15:35:33 +0400 Subject: [PATCH 13/45] IDEA-86572 UI: Return ability to navigate to the editor by pressing Esc at the detached tool window --- .../wm/impl/commands/RequestFocusInEditorComponentCmd.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java index 1adb4f46851e..96c0f77c6384 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInEditorComponentCmd.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -86,7 +86,8 @@ public final class RequestFocusInEditorComponentCmd extends FinalizableCommand{ return; } - if (owner instanceof IdeFrameImpl && IdeFrameImpl.getActiveFrame() != owner) { + final Window activeFrame = IdeFrameImpl.getActiveFrame(); + if (activeFrame != null && owner instanceof IdeFrameImpl && activeFrame != owner) { myDoneCallback.setRejected(); return; } From c3a883e308ba77be2b4cc12087059fbf8c676459 Mon Sep 17 00:00:00 2001 From: Kirill Likhodedov Date: Thu, 24 May 2012 15:36:18 +0400 Subject: [PATCH 14/45] VcsRoot: make fields private, use @Nullable getters VcsRoot.getVcs() and .getPath() can be null, because they are sometimes created like that. GitRepositoryManagerImpl.getRepositoryForFile: don't log null VCS. --- .../diff/impl/patch/IdeaTextPatchBuilder.java | 6 +-- .../src/com/intellij/openapi/vcs/VcsRoot.java | 37 ++++++++++++------- .../formove/TriggerAdditionOrDeletion.java | 30 +++++++-------- .../openapi/vcs/changes/DirtBuilder.java | 8 ++-- .../openapi/vcs/changes/FilePathUnderVcs.java | 4 +- .../vcs/changes/RemoteRevisionsCache.java | 3 +- .../changes/RemoteRevisionsNumbersCache.java | 12 +++--- .../changes/RemoteRevisionsStateCache.java | 6 +-- .../vcs/changes/VcsDirtyScopeImpl.java | 9 +++-- .../vcs/impl/LocalChangesUnderRoots.java | 7 ++-- .../openapi/vcs/impl/VcsRootIterator.java | 4 +- .../repo/GitRepositoryManagerImpl.java | 10 +++-- .../git4idea/status/GitChangesCollector.java | 2 +- .../src/org/zmlx/hg4idea/util/HgUtil.java | 4 +- 14 files changed, 78 insertions(+), 64 deletions(-) diff --git a/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/IdeaTextPatchBuilder.java b/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/IdeaTextPatchBuilder.java index 839e94ba8049..3b6b9a034cb0 100644 --- a/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/IdeaTextPatchBuilder.java +++ b/platform/vcs-api/src/com/intellij/openapi/diff/impl/patch/IdeaTextPatchBuilder.java @@ -52,12 +52,12 @@ public class IdeaTextPatchBuilder { for (VcsRoot root : byRoots.keySet()) { final Collection rootChanges = byRoots.get(root); - if (root.vcs == null || root.vcs.getOutgoingChangesProvider() == null) { + if (root.getVcs() == null || root.getVcs().getOutgoingChangesProvider() == null) { addConvertChanges(rootChanges, result); continue; } - final VcsOutgoingChangesProvider provider = root.vcs.getOutgoingChangesProvider(); - final Collection basedOnLocal = provider.filterLocalChangesBasedOnLocalCommits(rootChanges, root.path); + final VcsOutgoingChangesProvider provider = root.getVcs().getOutgoingChangesProvider(); + final Collection basedOnLocal = provider.filterLocalChangesBasedOnLocalCommits(rootChanges, root.getPath()); rootChanges.removeAll(basedOnLocal); addConvertChanges(rootChanges, result); diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsRoot.java b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsRoot.java index c05995636b45..771a7e29885a 100644 --- a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsRoot.java +++ b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsRoot.java @@ -17,18 +17,31 @@ package com.intellij.openapi.vcs; import com.intellij.openapi.vfs.VirtualFile; +import org.jetbrains.annotations.Nullable; /** * @author yole */ public class VcsRoot { - public final AbstractVcs vcs; - public final VirtualFile path; + + @Nullable private final AbstractVcs myVcs; + @Nullable private final VirtualFile myPath; + private int hashcode; - public VcsRoot(final AbstractVcs vcs, final VirtualFile path) { - this.vcs = vcs; - this.path = path; + public VcsRoot(@Nullable AbstractVcs vcs, @Nullable VirtualFile path) { + myVcs = vcs; + myPath = path; + } + + @Nullable + public AbstractVcs getVcs() { + return myVcs; + } + + @Nullable + public VirtualFile getPath() { + return myPath; } @Override @@ -38,26 +51,22 @@ public class VcsRoot { VcsRoot root = (VcsRoot)o; - if (path != null ? !path.equals(root.path) : root.path != null) return false; - if (vcs != null ? !vcs.getName().equals(root.vcs.getName()) : root.vcs != null) return false; + if (myPath != null ? !myPath.equals(root.myPath) : root.myPath != null) return false; + if (myVcs != null ? !myVcs.equals(root.myVcs) : root.myVcs != null) return false; return true; } - @Override public int hashCode() { if (hashcode == 0) { - hashcode = vcs != null ? vcs.getName().hashCode() : 0; - hashcode = 31 * hashcode + (path != null ? path.hashCode() : 0); + hashcode = myVcs != null ? myVcs.hashCode() : 0; + hashcode = 31 * hashcode + (myPath != null ? myPath.hashCode() : 0); } return hashcode; } @Override public String toString() { - return "VcsRoot{" + - "vcs=" + vcs + - ", path=" + path + - '}'; + return String.format("VcsRoot{vcs=%s, path=%s}", myVcs, myPath); } } \ No newline at end of file diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/TriggerAdditionOrDeletion.java b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/TriggerAdditionOrDeletion.java index e9a3eec147cd..b74937583127 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/TriggerAdditionOrDeletion.java +++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/formove/TriggerAdditionOrDeletion.java @@ -91,14 +91,14 @@ public class TriggerAdditionOrDeletion { if (myPreparedDeletion != null) { for (Map.Entry> entry : myPreparedDeletion.entrySet()) { final VcsRoot vcsRoot = entry.getKey(); - final CheckinEnvironment localChangesProvider = vcsRoot.vcs.getCheckinEnvironment(); + final CheckinEnvironment localChangesProvider = vcsRoot.getVcs().getCheckinEnvironment(); if (localChangesProvider == null) continue; final Collection filePaths = entry.getValue(); - if (vcsRoot.vcs.fileListenerIsSynchronous()) { + if (vcsRoot.getVcs().fileListenerIsSynchronous()) { myAffected.addAll(filePaths); continue; } - askUserIfNeededDeletion(vcsRoot.vcs, (List)filePaths); + askUserIfNeededDeletion(vcsRoot.getVcs(), (List)filePaths); myAffected.addAll(filePaths); localChangesProvider.scheduleMissingFileForDeletion((List)filePaths); } @@ -106,14 +106,14 @@ public class TriggerAdditionOrDeletion { if (myPreparedAddition != null) { for (Map.Entry> entry : myPreparedAddition.entrySet()) { final VcsRoot vcsRoot = entry.getKey(); - final CheckinEnvironment localChangesProvider = vcsRoot.vcs.getCheckinEnvironment(); + final CheckinEnvironment localChangesProvider = vcsRoot.getVcs().getCheckinEnvironment(); if (localChangesProvider == null) continue; final Collection filePaths = entry.getValue(); - if (vcsRoot.vcs.fileListenerIsSynchronous()) { + if (vcsRoot.getVcs().fileListenerIsSynchronous()) { myAffected.addAll(filePaths); continue; } - askUserIfNeededAddition(vcsRoot.vcs, (List)filePaths); + askUserIfNeededAddition(vcsRoot.getVcs(), (List)filePaths); myAffected.addAll(filePaths); localChangesProvider.scheduleUnversionedFilesForAddition(ObjectsConvertor.fp2vf(filePaths)); } @@ -128,10 +128,10 @@ public class TriggerAdditionOrDeletion { final MultiMap map = sortByVcsRoots.sort(myDeleted); myPreparedDeletion = new MultiMap(); for (VcsRoot vcsRoot : map.keySet()) { - if (vcsRoot != null && vcsRoot.vcs != null) { - final CheckinEnvironment localChangesProvider = vcsRoot.vcs.getCheckinEnvironment(); + if (vcsRoot != null && vcsRoot.getVcs() != null) { + final CheckinEnvironment localChangesProvider = vcsRoot.getVcs().getCheckinEnvironment(); if (localChangesProvider == null) continue; - final boolean takeDirs = vcsRoot.vcs.areDirectoriesVersionedItems(); + final boolean takeDirs = vcsRoot.getVcs().areDirectoriesVersionedItems(); final Collection files = map.get(vcsRoot); final List toBeDeleted = new LinkedList(); @@ -142,7 +142,7 @@ public class TriggerAdditionOrDeletion { } } if (toBeDeleted.isEmpty()) return; - if (! vcsRoot.vcs.fileListenerIsSynchronous()) { + if (! vcsRoot.getVcs().fileListenerIsSynchronous()) { for (FilePath filePath : toBeDeleted) { myVcsFileListenerContextHelper.ignoreDeleted(filePath); } @@ -159,15 +159,15 @@ public class TriggerAdditionOrDeletion { final MultiMap map = sortByVcsRoots.sort(myExisting); myPreparedAddition = new MultiMap(); for (VcsRoot vcsRoot : map.keySet()) { - if (vcsRoot != null && vcsRoot.vcs != null) { - final CheckinEnvironment localChangesProvider = vcsRoot.vcs.getCheckinEnvironment(); + if (vcsRoot != null && vcsRoot.getVcs() != null) { + final CheckinEnvironment localChangesProvider = vcsRoot.getVcs().getCheckinEnvironment(); if (localChangesProvider == null) continue; - final boolean takeDirs = vcsRoot.vcs.areDirectoriesVersionedItems(); + final boolean takeDirs = vcsRoot.getVcs().areDirectoriesVersionedItems(); final Collection files = map.get(vcsRoot); final List toBeAdded; if (takeDirs) { - final RecursiveCheckAdder adder = new RecursiveCheckAdder(vcsRoot.path); + final RecursiveCheckAdder adder = new RecursiveCheckAdder(vcsRoot.getPath()); for (FilePath file : files) { adder.process(file); } @@ -184,7 +184,7 @@ public class TriggerAdditionOrDeletion { return; } Collections.sort(toBeAdded, FilePathByPathComparator.getInstance()); - if (! vcsRoot.vcs.fileListenerIsSynchronous()) { + if (! vcsRoot.getVcs().fileListenerIsSynchronous()) { for (FilePath filePath : toBeAdded) { myVcsFileListenerContextHelper.ignoreAdded(filePath.getVirtualFile()); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.java index e67be9520256..aae32d66f9f2 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/DirtBuilder.java @@ -58,13 +58,13 @@ public class DirtBuilder implements DirtBuilderReader { } public void addDirtyFile(final VcsRoot root) { - if (myFileTypeManager.isFileIgnored(root.path.getName())) return; - myFiles.add(new FilePathUnderVcs(new FilePathImpl(root.path), root.vcs)); + if (myFileTypeManager.isFileIgnored(root.getPath().getName())) return; + myFiles.add(new FilePathUnderVcs(new FilePathImpl(root.getPath()), root.getVcs())); } public void addDirtyDirRecursively(final VcsRoot root) { - if (myFileTypeManager.isFileIgnored(root.path.getName())) return; - myDirs.add(new FilePathUnderVcs(new FilePathImpl(root.path), root.vcs)); + if (myFileTypeManager.isFileIgnored(root.getPath().getName())) return; + myDirs.add(new FilePathUnderVcs(new FilePathImpl(root.getPath()), root.getVcs())); } public void addDirtyFile(final FilePathUnderVcs root) { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/FilePathUnderVcs.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/FilePathUnderVcs.java index f3bed0b0a416..c2138f6d25cb 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/FilePathUnderVcs.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/FilePathUnderVcs.java @@ -33,8 +33,8 @@ public class FilePathUnderVcs { } FilePathUnderVcs(final VcsRoot root) { - myPath = new FilePathImpl(root.path); - myVcs = root.vcs; + myPath = new FilePathImpl(root.getPath()); + myVcs = root.getVcs(); } public FilePath getPath() { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsCache.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsCache.java index ae5412bdfd9c..b172810d17da 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsCache.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsCache.java @@ -15,7 +15,6 @@ */ package com.intellij.openapi.vcs.changes; -import com.intellij.lifecycle.AtomicSectionsAware; import com.intellij.lifecycle.PeriodicalTasksCloser; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; @@ -128,7 +127,7 @@ public class RemoteRevisionsCache implements PlusMinus final VcsRoot[] roots = myVcsManager.getAllVcsRoots(); synchronized (myLock) { for (VcsRoot root : roots) { - final AbstractVcs vcs = root.vcs; + final AbstractVcs vcs = root.getVcs(); if (! myKinds.containsKey(vcs.getName())) { myKinds.put(vcs.getName(), vcs.getRemoteDifferenceStrategy()); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsNumbersCache.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsNumbersCache.java index 193d994f90e3..386c5751eb42 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsNumbersCache.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsNumbersCache.java @@ -96,8 +96,8 @@ public class RemoteRevisionsNumbersCache implements ChangesOnServerTracker { for (Iterator> iterator = copyMap.entrySet().iterator(); iterator.hasNext();) { final Map.Entry entry = iterator.next(); final VcsRoot key = entry.getKey(); - final boolean backgroundOperationsAllowed = key.vcs.isVcsBackgroundOperationsAllowed(key.path); - LOG.debug("backgroundOperationsAllowed: " + backgroundOperationsAllowed + " for " + key.vcs.getName() + ", " + key.path.getPath()); + final boolean backgroundOperationsAllowed = key.getVcs().isVcsBackgroundOperationsAllowed(key.getPath()); + LOG.debug("backgroundOperationsAllowed: " + backgroundOperationsAllowed + " for " + key.getVcs().getName() + ", " + key.getPath().getPath()); if (! backgroundOperationsAllowed) { iterator.remove(); } @@ -232,7 +232,7 @@ public class RemoteRevisionsNumbersCache implements ChangesOnServerTracker { //todo check canceled - check VCS's ready for asynchronous queries final VirtualFile vf = myLfs.refreshAndFindFileByIoFile(new File(s)); final ItemLatestState state; - final DiffProvider diffProvider = myVcsRoot.vcs.getDiffProvider(); + final DiffProvider diffProvider = myVcsRoot.getVcs().getDiffProvider(); if (vf == null) { // doesnt matter if directory or not state = diffProvider.getLastRevision(FilePathImpl.createForDeletedFile(new File(s), false)); @@ -262,11 +262,11 @@ public class RemoteRevisionsNumbersCache implements ChangesOnServerTracker { } public Boolean compute() { - final AbstractVcs vcs = myVcsRoot.vcs; + final AbstractVcs vcs = myVcsRoot.getVcs(); // won't be called in parallel for same vcs -> just synchronized map is ok final String vcsName = vcs.getName(); - LOG.debug("should update for: " + vcsName + " root: " + myVcsRoot.path.getPath()); - final VcsRevisionNumber latestNew = vcs.getDiffProvider().getLatestCommittedRevision(myVcsRoot.path); + LOG.debug("should update for: " + vcsName + " root: " + myVcsRoot.getPath().getPath()); + final VcsRevisionNumber latestNew = vcs.getDiffProvider().getLatestCommittedRevision(myVcsRoot.getPath()); final VcsRevisionNumber latestKnown = myLatestRevisionsMap.get(vcsName); // not known diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsStateCache.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsStateCache.java index da6934f82e05..fd8a5372242a 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsStateCache.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/RemoteRevisionsStateCache.java @@ -135,12 +135,12 @@ public class RemoteRevisionsStateCache implements ChangesOnServerTracker { for (VcsRoot vcsRoot : dirty.keySet()) { // todo - actually it means nothing since the only known VCS to use this scheme is Git and now it always allow // todo - background operations. when it changes, develop more flexible behavior here - if (! vcsRoot.vcs.isVcsBackgroundOperationsAllowed(vcsRoot.path)) continue; - final TreeDiffProvider provider = vcsRoot.vcs.getTreeDiffProvider(); + if (! vcsRoot.getVcs().isVcsBackgroundOperationsAllowed(vcsRoot.getPath())) continue; + final TreeDiffProvider provider = vcsRoot.getVcs().getTreeDiffProvider(); if (provider == null) continue; final Collection paths = dirty.get(vcsRoot); - final Collection remotelyChanged = provider.getRemotelyChanged(vcsRoot.path, paths); + final Collection remotelyChanged = provider.getRemotelyChanged(vcsRoot.getPath(), paths); for (String path : paths) { results.put(path, new Pair(remotelyChanged.contains(path), vcsRoot)); } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeImpl.java index 97f9e623dbcc..fcdd21c64d16 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeImpl.java @@ -21,6 +21,7 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.vcs.*; import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; import com.intellij.util.Processor; @@ -307,16 +308,16 @@ public class VcsDirtyScopeImpl extends VcsModifiableDirtyScope { if (myProject.isDisposed()) return Boolean.FALSE; final VcsRoot rootObject = myVcsManager.getVcsRootObjectFor(path); if (vcsConsumer != null && rootObject != null) { - vcsConsumer.consume(rootObject.vcs); + vcsConsumer.consume(rootObject.getVcs()); } - if (rootObject == null || rootObject.vcs != myVcs) { + if (rootObject == null || rootObject.getVcs() != myVcs) { return Boolean.FALSE; } - final VirtualFile vcsRoot = rootObject.path; + final VirtualFile vcsRoot = rootObject.getPath(); if (vcsRoot != null) { for (VirtualFile contentRoot : myAffectedContentRoots) { - if (VfsUtil.isAncestor(contentRoot, vcsRoot, false)) { + if (VfsUtilCore.isAncestor(contentRoot, vcsRoot, false)) { THashSet dirsByRoot = myDirtyDirectoriesRecursively.get(contentRoot); if (dirsByRoot != null) { for (FilePath filePath : dirsByRoot) { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LocalChangesUnderRoots.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LocalChangesUnderRoots.java index eeba391dd2e8..3412cdb4f57c 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LocalChangesUnderRoots.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LocalChangesUnderRoots.java @@ -24,6 +24,7 @@ import com.intellij.openapi.vcs.changes.ChangeListManager; import com.intellij.openapi.vcs.changes.ChangesUtil; import com.intellij.openapi.vcs.changes.ContentRevision; import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -87,9 +88,9 @@ public class LocalChangesUnderRoots { } VirtualFile rootCandidate = null; for (VcsRoot root : myRoots) { - if (VfsUtil.isAncestor(root.path, vf, false)) { - if (rootCandidate == null || VfsUtil.isAncestor(rootCandidate, root.path, true)) { // in the case of nested roots choose the closest root - rootCandidate = root.path; + if (VfsUtilCore.isAncestor(root.getPath(), vf, false)) { + if (rootCandidate == null || VfsUtil.isAncestor(rootCandidate, root.getPath(), true)) { // in the case of nested roots choose the closest root + rootCandidate = root.getPath(); } } } diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java index c272b36ad3a3..d580acbb176b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsRootIterator.java @@ -92,8 +92,8 @@ public class VcsRootIterator { final String ourPath = myRoot.getUrl(); for (VcsRoot root : allRoots) { - if (Comparing.equal(root.vcs.getName(), myVcsName)) continue; - final String url = root.path.getUrl(); + if (Comparing.equal(root.getVcs().getName(), myVcsName)) continue; + final String url = root.getPath().getUrl(); if (url.startsWith(ourPath)) { myExcludedByOtherVcss.add(url); } diff --git a/plugins/git4idea/src/git4idea/repo/GitRepositoryManagerImpl.java b/plugins/git4idea/src/git4idea/repo/GitRepositoryManagerImpl.java index b853317890af..c266d7e185a1 100644 --- a/plugins/git4idea/src/git4idea/repo/GitRepositoryManagerImpl.java +++ b/plugins/git4idea/src/git4idea/repo/GitRepositoryManagerImpl.java @@ -100,12 +100,16 @@ public class GitRepositoryManagerImpl extends AbstractProjectComponent implement public GitRepository getRepositoryForFile(@NotNull VirtualFile file) { final VcsRoot vcsRoot = myVcsManager.getVcsRootObjectFor(file); if (vcsRoot == null) { return null; } - final AbstractVcs vcs = vcsRoot.vcs; + final AbstractVcs vcs = vcsRoot.getVcs(); if (!myVcs.equals(vcs)) { - LOG.info(String.format("getRepositoryForFile returned non-Git (%s) root for file %s", vcs != null ? vcs.getDisplayName() : vcs, file)); + if (vcs != null) { + // if null, the file is just not under version control, nothing interesting; + // otherwise log, because Git method is requested not for a Git-controlled file + LOG.info(String.format("getRepositoryForFile returned non-Git (%s) root for file %s", vcs.getDisplayName(), file)); + } return null; } - return getRepositoryForRoot(vcsRoot.path); + return getRepositoryForRoot(vcsRoot.getPath()); } @Override diff --git a/plugins/git4idea/src/git4idea/status/GitChangesCollector.java b/plugins/git4idea/src/git4idea/status/GitChangesCollector.java index 0d7869471475..df204a34f5a2 100644 --- a/plugins/git4idea/src/git4idea/status/GitChangesCollector.java +++ b/plugins/git4idea/src/git4idea/status/GitChangesCollector.java @@ -114,7 +114,7 @@ abstract class GitChangesCollector { protected void addToPaths(FilePath pathToAdd, List paths) { VcsRoot fileRoot = myVcsManager.getVcsRootObjectFor(pathToAdd); - if (fileRoot != null && fileRoot.vcs != null && fileRoot.vcs.equals(myVcs) && myVcsRoot.equals(fileRoot.path)) { + if (fileRoot != null && fileRoot.getVcs() != null && myVcs.equals(fileRoot.getVcs()) && myVcsRoot.equals(fileRoot.getPath())) { paths.add(pathToAdd.getPath()); } } diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java index 35c3ef69e993..ecceca01bfe8 100644 --- a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java +++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java @@ -332,8 +332,8 @@ public abstract class HgUtil { public static @NotNull List getHgRepositories(@NotNull Project project) { final List repos = new LinkedList(); for (VcsRoot root : ProjectLevelVcsManager.getInstance(project).getAllVcsRoots()) { - if (HgVcs.VCS_NAME.equals(root.vcs.getName())) { - repos.add(root.path); + if (HgVcs.VCS_NAME.equals(root.getVcs().getName())) { + repos.add(root.getPath()); } } return repos; From 34e0c64b2b23817fd6c14d56ba8f3545b4549ca2 Mon Sep 17 00:00:00 2001 From: Vassiliy Kudryashov Date: Thu, 24 May 2012 15:49:13 +0400 Subject: [PATCH 15/45] IDEA-48900 Temporary run configuration: on exceeding the limit erase the oldest used one, not the oldest created --- .../com/intellij/execution/RunManager.java | 6 +- .../runners/GenericProgramRunner.java | 5 ++ .../actions/RunConfigurationAction.java | 5 +- .../impl/ProjectRunConfigurationManager.java | 2 +- .../execution/impl/RunConfigurable.java | 60 ++++++++++---- .../execution/impl/RunManagerImpl.java | 82 ++++++++++++++----- .../src/com/intellij/mock/MockRunManager.java | 7 +- 7 files changed, 123 insertions(+), 44 deletions(-) diff --git a/platform/lang-api/src/com/intellij/execution/RunManager.java b/platform/lang-api/src/com/intellij/execution/RunManager.java index 4280e6b7c729..3f9522eb4c5f 100644 --- a/platform/lang-api/src/com/intellij/execution/RunManager.java +++ b/platform/lang-api/src/com/intellij/execution/RunManager.java @@ -18,6 +18,7 @@ package com.intellij.execution; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; +import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.project.Project; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -45,7 +46,7 @@ public abstract class RunManager { public abstract boolean isTemporary(@NotNull RunConfiguration configuration); - public abstract void makeStable(@Nullable RunConfiguration configuration); + public abstract void makeStable(@NotNull RunConfiguration configuration); @Nullable public abstract RunnerAndConfigurationSettings getSelectedConfiguration(); @@ -58,4 +59,7 @@ public abstract class RunManager { @NotNull public abstract RunnerAndConfigurationSettings[] getConfigurationSettings(@NotNull ConfigurationType type); + + public abstract void refreshUsagesList(RunProfile profile); + } diff --git a/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java b/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java index 8d8550e664cc..1605124ffcbf 100644 --- a/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java +++ b/platform/lang-api/src/com/intellij/execution/runners/GenericProgramRunner.java @@ -75,6 +75,11 @@ public abstract class GenericProgramRunner return; } + RunnerSettings runnerSettings = env.getRunnerSettings(); + if (runnerSettings != null) { + RunManager.getInstance(project).refreshUsagesList(runnerSettings.getRunProfile()); + } + ExecutionManager.getInstance(project).startRunProfile(new RunProfileStarter() { @Override public RunContentDescriptor execute(@NotNull Project project, diff --git a/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java b/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java index 006f4060141b..68e4b437a954 100644 --- a/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java +++ b/platform/lang-impl/src/com/intellij/execution/actions/RunConfigurationAction.java @@ -186,9 +186,10 @@ public class RunConfigurationAction extends ComboBoxAction implements DumbAware public void actionPerformed(final AnActionEvent e) { final Project project = e.getData(PlatformDataKeys.PROJECT); - if (project != null) { + RunConfiguration configuration = chooseTempConfiguration(project); + if (project != null && configuration != null) { final RunManager runManager = RunManager.getInstance(project); - runManager.makeStable(chooseTempConfiguration(project)); + runManager.makeStable(configuration); } } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java b/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java index 3ec35bfe5f28..ec3bcdb65793 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/ProjectRunConfigurationManager.java @@ -112,7 +112,7 @@ public class ProjectRunConfigurationManager implements ProjectComponent, Persist } if (configuration != null) { - existing.add(RunManagerImpl.getUniqueName(configuration)); + existing.add(RunManagerImpl.getUniqueName(configuration.getConfiguration())); } } diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java index 6f798533f6ff..1d20640a7930 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java @@ -54,10 +54,7 @@ import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.*; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; +import javax.swing.tree.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; @@ -518,7 +515,19 @@ class RunConfigurable extends BaseConfigurable { updateActiveConfigurationFromSelected(); final RunManagerImpl manager = getRunManager(); - final ConfigurationType[] configurationTypes = manager.getConfigurationFactories(); + final ConfigurationType[] types = manager.getConfigurationFactories(); + List configurationTypes = new ArrayList(); + for (int i = 0; i < myRoot.getChildCount(); i++) { + final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i); + if (node.getUserObject() instanceof ConfigurationType) { + configurationTypes.add((ConfigurationType)node.getUserObject()); + } + } + for (ConfigurationType type : types) { + if (!configurationTypes.contains(type)) + configurationTypes.add(type); + } + for (ConfigurationType configurationType : configurationTypes) { applyByType(configurationType); } @@ -1092,6 +1101,23 @@ class RunConfigurable extends BaseConfigurable { final RunnerAndConfigurationSettings originalConfiguration = configurationConfigurable.getSettings(); if (getRunManager().isTemporary(originalConfiguration)) { getRunManager().makeStable(originalConfiguration.getConfiguration()); + final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)myTree.getSelectionPath().getLastPathComponent(); + MutableTreeNode parent = (MutableTreeNode)treeNode.getParent(); + int initialPosition = parent.getIndex(treeNode); + int position = parent.getIndex(treeNode); + DefaultMutableTreeNode node = treeNode.getPreviousSibling(); + while (node != null) { + RunnerAndConfigurationSettings settings = getSettings(node); + if (settings != null && settings.isTemporary()) { + position--; + } else { + break; + } + node = node.getPreviousSibling(); + } + for (int i = 0; i < initialPosition - position; i++) { + TreeUtil.moveSelectedRow(myTree, -1); + } } myTree.repaint(); } @@ -1139,20 +1165,20 @@ class RunConfigurable extends BaseConfigurable { } } } + } - @Nullable - private RunnerAndConfigurationSettings getSettings(DefaultMutableTreeNode treeNode) { - if (treeNode == null) - return null; - RunnerAndConfigurationSettings settings = null; - if (treeNode.getUserObject() instanceof SingleConfigurationConfigurable) { - settings = (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)treeNode.getUserObject()).getSettings(); - } - if (treeNode.getUserObject() instanceof RunnerAndConfigurationSettings) { - settings = (RunnerAndConfigurationSettings)treeNode.getUserObject(); - } - return settings; + @Nullable + private static RunnerAndConfigurationSettings getSettings(DefaultMutableTreeNode treeNode) { + if (treeNode == null) + return null; + RunnerAndConfigurationSettings settings = null; + if (treeNode.getUserObject() instanceof SingleConfigurationConfigurable) { + settings = (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)treeNode.getUserObject()).getSettings(); } + if (treeNode.getUserObject() instanceof RunnerAndConfigurationSettings) { + settings = (RunnerAndConfigurationSettings)treeNode.getUserObject(); + } + return settings; } private static class RunConfigurationBean { diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java index 6fbf4652024e..a476cef85d14 100644 --- a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java +++ b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java @@ -59,6 +59,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, @NonNls protected static final String CONFIGURATION = "configuration"; + protected static final String RECENT = "recent_temporary"; private ConfigurationType[] myTypes; private final RunManagerConfig myConfig; @NonNls @@ -70,6 +71,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, private List myUnknownElements = null; private JDOMExternalizableStringList myOrder = new JDOMExternalizableStringList(); + private final ArrayList myRecentlyUsedTemporaries = new ArrayList(); private boolean myOrdered = true; private final EventDispatcher myDispatcher = EventDispatcher.create(RunManagerListener.class); @@ -243,7 +245,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, List tasks, boolean addEnabledTemplateTasksIfAbsent) { final RunConfiguration configuration = settings.getConfiguration(); - Integer existingId = findConfigurationIdByUniqueName(getUniqueName(settings)); + Integer existingId = findConfigurationIdByUniqueName(getUniqueName(configuration)); Integer newId = configuration.getUniqueID(); RunnerAndConfigurationSettings existingSettings = null; @@ -252,14 +254,17 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, mySharedConfigurations.remove(existingId); } - if (mySelectedConfigurationId != null && mySelectedConfigurationId.equals(existingId)) setSelectedConfigurationId(newId); + if (mySelectedConfigurationId != null && mySelectedConfigurationId.equals(existingId)) { + setSelectedConfigurationId(newId); + } myConfigurations.put(newId, settings); + if (existingId == null) { + refreshUsagesList(configuration); + } checkRecentsLimit(); mySharedConfigurations.put(newId, shared); setBeforeRunTasks(configuration, tasks, addEnabledTemplateTasksIfAbsent); - saveOrder(); - myOrdered = false; if (existingSettings == settings) { myDispatcher.getMulticaster().runConfigurationChanged(settings); @@ -269,12 +274,23 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, } } + @Override + public void refreshUsagesList(RunProfile profile) { + if (profile instanceof RunConfiguration && isTemporary((RunConfiguration)profile)) { + myRecentlyUsedTemporaries.remove((RunConfiguration)profile); + myRecentlyUsedTemporaries.add(0, (RunConfiguration)profile); + while(myRecentlyUsedTemporaries.size() > getConfig().getRecentsLimit()) { + myRecentlyUsedTemporaries.remove(myRecentlyUsedTemporaries.size() - 1); + } + } + } + void checkRecentsLimit() { List removed = new ArrayList(); while (getTempConfigurations().length > getConfig().getRecentsLimit()) { for (Iterator> it = myConfigurations.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = it.next(); - if (entry.getValue().isTemporary()) { + if (entry.getValue().isTemporary() && !myRecentlyUsedTemporaries.contains(entry.getValue().getConfiguration())) { removed.add(entry.getValue()); it.remove(); break; @@ -292,13 +308,12 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, myOrder.clear(); for (RunnerAndConfigurationSettings each : myConfigurations.values()) { if (each.getType() instanceof UnknownConfigurationType) continue; - myOrder.add(getUniqueName(each)); + myOrder.add(getUniqueName(each.getConfiguration())); } } - static String getUniqueName(@NotNull RunnerAndConfigurationSettings settings) { - RunConfiguration config = settings.getConfiguration(); - return config.getType().getDisplayName() + "." + settings.getName() + + static String getUniqueName(@NotNull RunConfiguration config) { + return config.getType().getDisplayName() + "." + config.getName() + (config instanceof UnknownRunConfiguration ? config.getUniqueID() : ""); } @@ -348,7 +363,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, List> order = new ArrayList>(myConfigurations.size()); for (RunnerAndConfigurationSettings each : myConfigurations.values()) { - order.add(Pair.create(getUniqueName(each), each)); + order.add(Pair.create(getUniqueName(each.getConfiguration()), each)); } myConfigurations.clear(); @@ -428,11 +443,20 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, //temp && stable configurations, !unknown for (RunnerAndConfigurationSettings each : myConfigurations.values()) { if (each.getType() instanceof UnknownConfigurationType) continue; - order.add(getUniqueName(each)); + order.add(getUniqueName(each.getConfiguration())); } order.writeExternal(parentNode); + final JDOMExternalizableStringList recentList = new JDOMExternalizableStringList(); + for (RunConfiguration each : myRecentlyUsedTemporaries) { + if (each.getType() instanceof UnknownConfigurationType) continue; + recentList.add(getUniqueName(each)); + } + final Element recent = new Element(RECENT); + parentNode.addContent(recent); + recentList.writeExternal(recent); + if (myUnknownElements != null) { for (Element unloadedElement : myUnknownElements) { parentNode.addContent((Element)unloadedElement.clone()); @@ -448,7 +472,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, } RunnerAndConfigurationSettings selected = getSelectedConfiguration(); if (selected != null) { - parentNode.setAttribute(SELECTED_ATTR, getUniqueName(selected)); + parentNode.setAttribute(SELECTED_ATTR, getUniqueName(selected.getConfiguration())); } } @@ -533,6 +557,18 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, } myOrder.readExternal(parentNode); + myRecentlyUsedTemporaries.clear(); + Element recentNode = parentNode.getChild(RECENT); + if (recentNode != null) { + JDOMExternalizableStringList list = new JDOMExternalizableStringList(); + list.readExternal(recentNode); + for (String name : list) { + Integer id = findConfigurationIdByUniqueName(name); + if (id != null) { + myRecentlyUsedTemporaries.add(myConfigurations.get(id).getConfiguration()); + } + } + } myOrdered = false; myLoadedSelectedConfigurationUniqueName = parentNode.getAttributeValue(SELECTED_ATTR); @@ -551,7 +587,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, if (myLoadedSelectedConfigurationUniqueName == null && config != null && Boolean.valueOf(element.getAttributeValue(SELECTED_ATTR)).booleanValue()) { - myLoadedSelectedConfigurationUniqueName = getUniqueName(config); + myLoadedSelectedConfigurationUniqueName = getUniqueName(config.getConfiguration()); } } @@ -564,7 +600,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, private Integer findConfigurationIdByUniqueName(@Nullable String selectedUniqueName) { if (selectedUniqueName != null) { for (RunnerAndConfigurationSettings each : myConfigurations.values()) { - if (selectedUniqueName.equals(getUniqueName(each))) { + if (selectedUniqueName.equals(getUniqueName(each.getConfiguration()))) { return each.getConfiguration().getUniqueID(); } } @@ -589,6 +625,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, mySelectedConfigurationId = null; myLoadedSelectedConfigurationUniqueName = null; myIdToIcon.clear(); + myRecentlyUsedTemporaries.clear(); fireRunConfigurationsRemoved(configurations); } @@ -728,11 +765,13 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, return configurations.toArray(new RunConfiguration[configurations.size()]); } - public void makeStable(@Nullable RunConfiguration configuration) { + public void makeStable(@NotNull RunConfiguration configuration) { RunnerAndConfigurationSettings settings = getSettings(configuration); if (settings != null) { invalidateConfigurationIcon(settings); settings.setTemporary(false); + myRecentlyUsedTemporaries.remove(configuration); + setOrdered(false); fireRunConfigurationChanged(settings); } } @@ -926,11 +965,11 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, void removeNotExistingSharedConfigurations(final Set existing) { List removed = new ArrayList(); for (Iterator> it = myConfigurations.entrySet().iterator(); it.hasNext(); ) { - Map.Entry c = it.next(); - final RunnerAndConfigurationSettings o = c.getValue(); - if (!o.isTemplate() && isConfigurationShared(o) && !existing.contains(getUniqueName(o))) { - removed.add(o); - invalidateConfigurationIcon(o); + Map.Entry entry = it.next(); + final RunnerAndConfigurationSettings settings = entry.getValue(); + if (!settings.isTemplate() && isConfigurationShared(settings) && !existing.contains(getUniqueName(settings.getConfiguration()))) { + removed.add(settings); + invalidateConfigurationIcon(settings); it.remove(); } } @@ -938,13 +977,12 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, } public void fireRunConfigurationChanged(@NotNull RunnerAndConfigurationSettings settings) { - myOrdered = false; invalidateConfigurationIcon(settings); myDispatcher.getMulticaster().runConfigurationChanged(settings); } private void fireRunConfigurationsRemoved(@NotNull List removed) { - myOrdered = false; + myRecentlyUsedTemporaries.removeAll(removed); for (RunnerAndConfigurationSettings settings : removed) { myDispatcher.getMulticaster().runConfigurationRemoved(settings); } diff --git a/platform/testFramework/src/com/intellij/mock/MockRunManager.java b/platform/testFramework/src/com/intellij/mock/MockRunManager.java index 450d8b68ba4f..ff465a3d13cb 100644 --- a/platform/testFramework/src/com/intellij/mock/MockRunManager.java +++ b/platform/testFramework/src/com/intellij/mock/MockRunManager.java @@ -4,6 +4,7 @@ import com.intellij.execution.*; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.execution.configurations.ConfigurationType; import com.intellij.execution.configurations.RunConfiguration; +import com.intellij.execution.configurations.RunProfile; import com.intellij.openapi.util.Key; import org.jetbrains.annotations.NotNull; @@ -46,7 +47,7 @@ public class MockRunManager extends RunManagerEx { } @Override - public void makeStable(RunConfiguration configuration) { + public void makeStable(@NotNull RunConfiguration configuration) { } @Override @@ -164,4 +165,8 @@ public class MockRunManager extends RunManagerEx { @Override public void removeRunManagerListener(RunManagerListener listener) { } + + @Override + public void refreshUsagesList(RunProfile profile) { + } } From bbf6ee0878318869de5ba3700fa32a2b09f8d424 Mon Sep 17 00:00:00 2001 From: Shaverdova Elena Date: Tue, 22 May 2012 20:06:01 +0400 Subject: [PATCH 16/45] WI-11323 Command Line Tools Console: "To previous/next command": refine numeration of commands --- .../src/com/intellij/execution/impl/EditorHyperlinkSupport.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java index 02c97564511f..10ddca58f138 100644 --- a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java +++ b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java @@ -338,7 +338,7 @@ public class EditorHyperlinkSupport { action.consume(next); linkFollowed(editor, ranges, next); } - }, i, ranges.size()); + }, newIndex == -1 ? -1 : newIndex + 1, ranges.size()); } // todo fix link followed here! From b9c3891f8447b6fa9c94209ebb8eb849fda21951 Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Thu, 24 May 2012 13:13:11 +0200 Subject: [PATCH 17/45] validation before external process compilation --- .../impl/src/com/intellij/compiler/impl/CompileDriver.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java index 697ea1fba91a..f8dfcb2928c8 100644 --- a/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java +++ b/java/compiler/impl/src/com/intellij/compiler/impl/CompileDriver.java @@ -2316,9 +2316,6 @@ public class CompileDriver { private boolean validateCompilerConfiguration(final CompileScope scope, boolean checkOutputAndSourceIntersection) { try { - if (useOutOfProcessBuild()) { - return true; - } final Module[] scopeModules = scope.getAffectedModules()/*ModuleManager.getInstance(myProject).getModules()*/; final List modulesWithoutOutputPathSpecified = new ArrayList(); boolean isProjectCompilePathSpecified = true; From 9f002548ac7f85a90363ab0c6e65b8977f6f1c39 Mon Sep 17 00:00:00 2001 From: Danila Ponomarenko Date: Thu, 24 May 2012 17:05:23 +0400 Subject: [PATCH 18/45] IDEA-86337 Disable actions in 'Generate...' popup which can't be applied. Fixed. --- .../GenerateGetterSetterHandlerBase.java | 9 +++-- .../JavaImplementMethodsHandler.java | 2 +- .../JavaOverrideMethodsHandler.java | 16 +++++++-- .../actions/GenerateGetterAction.java | 5 ++- .../GenerateGetterAndSetterAction.java | 3 +- .../GenerateGetterSetterBaseAction.java | 36 +++++++++++++++++++ .../actions/GenerateSetterAction.java | 2 +- .../actions/BaseGenerateAction.java | 5 +-- 8 files changed, 62 insertions(+), 16 deletions(-) create mode 100644 java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterSetterBaseAction.java diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java index 8874a983e58a..0bda4000366b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/GenerateGetterSetterHandlerBase.java @@ -35,7 +35,7 @@ import java.util.Collection; import java.util.Collections; import java.util.List; -abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHandlerBase { +public abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHandlerBase { private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.generation.GenerateGetterSetterHandlerBase"); static { @@ -44,7 +44,7 @@ abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHandlerBas public Collection fun(PsiClass s) { if (s.getLanguage() != StdLanguages.JAVA) return Collections.emptyList(); final List result = new ArrayList(); - for(PsiField field: s.getFields()) { + for (PsiField field : s.getFields()) { if (!(field instanceof PsiEnumConstant)) { result.add(new PsiFieldMember(field)); } @@ -75,6 +75,11 @@ abstract class GenerateGetterSetterHandlerBase extends GenerateMembersHandlerBas protected abstract String getNothingFoundMessage(); protected abstract String getNothingAcceptedMessage(); + public boolean canBeAppliedTo(PsiClass targetClass) { + final ClassMember[] allMembers = getAllOriginalMembers(targetClass); + return allMembers != null && allMembers.length != 0; + } + @Nullable protected ClassMember[] getAllOriginalMembers(final PsiClass aClass) { final List list = GenerateAccessorProviderRegistrar.getEncapsulatableClassMembers(aClass); diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/JavaImplementMethodsHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/JavaImplementMethodsHandler.java index 3202c82f9648..554aa5151cf0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/JavaImplementMethodsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/JavaImplementMethodsHandler.java @@ -34,7 +34,7 @@ public class JavaImplementMethodsHandler implements LanguageCodeInsightActionHan } PsiClass aClass = OverrideImplementUtil.getContextClass(file.getProject(), editor, file, false); - return aClass != null; + return aClass != null && !OverrideImplementUtil.getMethodSignaturesToImplement(aClass).isEmpty(); } public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideMethodsHandler.java b/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideMethodsHandler.java index 24ce4d40af4a..5e3745b78f7c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideMethodsHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/JavaOverrideMethodsHandler.java @@ -15,6 +15,7 @@ */ package com.intellij.codeInsight.generation; +import com.intellij.codeInsight.hint.HintManager; import com.intellij.lang.LanguageCodeInsightActionHandler; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; @@ -28,14 +29,23 @@ import org.jetbrains.annotations.NotNull; */ public class JavaOverrideMethodsHandler implements LanguageCodeInsightActionHandler { public boolean isValidFor(final Editor editor, final PsiFile file) { - return file instanceof PsiJavaFile && OverrideImplementUtil.getContextClass(file.getProject(), editor, file, true) != null; + if (!(file instanceof PsiJavaFile)) { + return false; + } + + PsiClass aClass = OverrideImplementUtil.getContextClass(file.getProject(), editor, file, true); + return aClass != null && !OverrideImplementUtil.getMethodSignaturesToOverride(aClass).isEmpty(); } public void invoke(@NotNull final Project project, @NotNull final Editor editor, @NotNull final PsiFile file) { PsiClass aClass = OverrideImplementUtil.getContextClass(project, editor, file, true); - if (aClass != null) { - OverrideImplementUtil.chooseAndOverrideMethods(project, editor, aClass); + if (aClass == null) return; + + if (OverrideImplementUtil.getMethodSignaturesToOverride(aClass).isEmpty()) { + HintManager.getInstance().showErrorHint(editor, "No methods to override have been found"); + return; } + OverrideImplementUtil.chooseAndOverrideMethods(project, editor, aClass); } public boolean startInWriteAction() { diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAction.java b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAction.java index 672633a528f3..08063cdff16c 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAction.java @@ -21,10 +21,9 @@ import com.intellij.codeInsight.generation.GenerateGetterHandler; * Action group which contains Generate... actions * Available in the Java code editor context only * @author Alexey Kudravtsev - */ -public class GenerateGetterAction extends BaseGenerateAction { + */ +public class GenerateGetterAction extends GenerateGetterSetterBaseAction { public GenerateGetterAction() { super(new GenerateGetterHandler()); } - } \ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAndSetterAction.java b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAndSetterAction.java index 7bdc0ccf979a..5b565cc249a4 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAndSetterAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterAndSetterAction.java @@ -22,9 +22,8 @@ import com.intellij.codeInsight.generation.GenerateGetterAndSetterHandler; * Available in the Java code editor context only * @author Alexey Kudravtsev */ -public class GenerateGetterAndSetterAction extends BaseGenerateAction { +public class GenerateGetterAndSetterAction extends GenerateGetterSetterBaseAction { public GenerateGetterAndSetterAction() { super(new GenerateGetterAndSetterHandler()); } - } \ No newline at end of file diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterSetterBaseAction.java b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterSetterBaseAction.java new file mode 100644 index 000000000000..e6056d84fad4 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateGetterSetterBaseAction.java @@ -0,0 +1,36 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.codeInsight.generation.actions; + +import com.intellij.codeInsight.generation.GenerateGetterSetterHandlerBase; +import com.intellij.psi.PsiClass; + +/** + * Action group which contains Generate... actions + * Available in the Java code editor context only + * @author Danila Ponomarenko + */ +public abstract class GenerateGetterSetterBaseAction extends BaseGenerateAction { + public GenerateGetterSetterBaseAction(GenerateGetterSetterHandlerBase handler) { + super(handler); + } + + @Override + protected boolean isValidForClass(PsiClass targetClass) { + final GenerateGetterSetterHandlerBase handler = (GenerateGetterSetterHandlerBase)getHandler(); + return handler.canBeAppliedTo(targetClass); + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSetterAction.java b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSetterAction.java index eebbc72b24f8..240befe1637e 100644 --- a/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSetterAction.java +++ b/java/java-impl/src/com/intellij/codeInsight/generation/actions/GenerateSetterAction.java @@ -22,7 +22,7 @@ import com.intellij.codeInsight.generation.GenerateSetterHandler; * Available in the Java code editor context only * @author Alexey Kudravtsev */ -public class GenerateSetterAction extends BaseGenerateAction { +public class GenerateSetterAction extends GenerateGetterSetterBaseAction { public GenerateSetterAction() { super(new GenerateSetterHandler()); } diff --git a/java/openapi/src/com/intellij/codeInsight/generation/actions/BaseGenerateAction.java b/java/openapi/src/com/intellij/codeInsight/generation/actions/BaseGenerateAction.java index 30d24589cd8d..cd3fed795f8a 100644 --- a/java/openapi/src/com/intellij/codeInsight/generation/actions/BaseGenerateAction.java +++ b/java/openapi/src/com/intellij/codeInsight/generation/actions/BaseGenerateAction.java @@ -53,10 +53,7 @@ public class BaseGenerateAction extends CodeInsightAction { PsiDocumentManager.getInstance(project).commitAllDocuments(); PsiClass targetClass = getTargetClass(editor, file); - if (targetClass == null) return false; - if (!isValidForClass(targetClass)) return false; //? - - return true; + return targetClass != null && isValidForClass(targetClass); } protected boolean isValidForClass(final PsiClass targetClass) { From 67c950e1a05f9d2e2fa766c49077ae7ee4a2198e Mon Sep 17 00:00:00 2001 From: peter Date: Wed, 23 May 2012 17:37:53 +0200 Subject: [PATCH 19/45] cleanup DfaMemoryStateImpl --- .../codeInspection/dataFlow/DfaMemoryStateImpl.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java index af8ccfdd5b82..718fc2c8b861 100644 --- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java +++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DfaMemoryStateImpl.java @@ -725,12 +725,8 @@ public class DfaMemoryStateImpl implements DfaMemoryState { if (!myHasDirtyFields) return; myHasDirtyFields = false; - DfaVariableValue[] fields = runner.getFields(); - for (DfaVariableValue field : fields) { - boolean resetNullability = isNotNull(field); + for (DfaVariableValue field : runner.getFields()) { flushVariable(field); - if (resetNullability) { - } getVariableState(field).setNullable(false); } } From 38e6f7f3c35f2590d0b7939b4edcf462cfb0c064 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 13:16:06 +0200 Subject: [PATCH 20/45] resolving freemarker imports from jars (IDEA-86192, IDEA-53342) --- .../resolve/reference/impl/providers/FileReferenceSet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java index 0e8c66a904ea..c52befbdd650 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceSet.java @@ -378,7 +378,7 @@ public class FileReferenceSet { } @NotNull - private static Collection getAbsoluteTopLevelDirLocations(final @NotNull PsiFile file) { + public static Collection getAbsoluteTopLevelDirLocations(final @NotNull PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { From f9a25a44b56d6afc75bb723f9088d781515f84bf Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 13:24:16 +0200 Subject: [PATCH 21/45] re-enable action groups when their children become visible --- .../completion/actions/CodeCompletionGroup.java | 5 +++++ .../intellij/openapi/actionSystem/ActionGroup.java | 4 ++++ .../intellij/openapi/actionSystem/impl/Utils.java | 14 +++++++------- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/CodeCompletionGroup.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/CodeCompletionGroup.java index b4be2de99a73..15c2da2bbc25 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/CodeCompletionGroup.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/CodeCompletionGroup.java @@ -47,4 +47,9 @@ public class CodeCompletionGroup extends DefaultActionGroup implements DumbAware presentation.setEnabled(true); } + + @Override + public boolean disableIfNoVisibleChildren() { + return false; + } } diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroup.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroup.java index bfc4375287c2..df23e12b780f 100644 --- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroup.java +++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ActionGroup.java @@ -188,4 +188,8 @@ public abstract class ActionGroup extends AnAction { public boolean hideIfNoVisibleChildren() { return false; } + + public boolean disableIfNoVisibleChildren() { + return true; + } } diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java index 056870f32628..0927854b75dd 100644 --- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java +++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/Utils.java @@ -130,14 +130,14 @@ public class Utils{ if (child instanceof ActionGroup) { ActionGroup actionGroup = (ActionGroup)child; if (actionGroup.isPopup()) { // popup menu has its own presentation - // disable group if it contains no visible actions - final boolean visibleChildren = hasVisibleChildren(actionGroup, presentationFactory, context, place); - if (actionGroup.hideIfNoVisibleChildren() && !visibleChildren) { - continue; - } - if (!actionGroup.canBePerformed(context) && !visibleChildren) { - presentation.setEnabled(false); + if (actionGroup.disableIfNoVisibleChildren()) { + final boolean visibleChildren = hasVisibleChildren(actionGroup, presentationFactory, context, place); + if (actionGroup.hideIfNoVisibleChildren() && !visibleChildren) { + continue; + } + presentation.setEnabled(actionGroup.canBePerformed(context) || visibleChildren); } + list.add(child); } else { From 2487bf48d3994be2ed867466f8226e0d0355772f Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Thu, 24 May 2012 15:42:37 +0200 Subject: [PATCH 22/45] cleanup --- .../com/siyeh/ipp/constant/ConstantExpressionPredicate.java | 3 +-- .../siyeh/ipp/constant/ConstantSubexpressionPredicate.java | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java index ad2ce95af9fc..fad82cd3fa2d 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantExpressionPredicate.java @@ -32,8 +32,7 @@ class ConstantExpressionPredicate implements PsiElementPredicate { } final PsiPolyadicExpression expression = (PsiPolyadicExpression)element; final PsiType expressionType = expression.getType(); - if (expressionType == null) return false; - if (expressionType.equalsToText("java.lang.String")) { + if (expressionType == null || expressionType.equalsToText("java.lang.String")) { // intention disabled for string concatenations because of performance issues on // relatively common large string expressions. return false; diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionPredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionPredicate.java index 02d111224d3b..77be61f4118b 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionPredicate.java +++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/constant/ConstantSubexpressionPredicate.java @@ -73,10 +73,10 @@ class ConstantSubexpressionPredicate implements PsiElementPredicate { if (currentToken == token) { final String binaryExpressionText = operands[i - 1].getText() + ' ' + token.getText() + ' ' + operand.getText(); final PsiElementFactory factory = JavaPsiFacade.getElementFactory(expression.getProject()); - return (PsiBinaryExpression)factory.createExpressionFromText(binaryExpressionText, expression); + return (PsiPolyadicExpression)factory.createExpressionFromText(binaryExpressionText, expression); } } - return null; + throw new AssertionError(); } private static boolean isPartOfLargerExpression(PsiPolyadicExpression expression) { From db2101100dabf41a300e5d97a7786fd52fa1ddfa Mon Sep 17 00:00:00 2001 From: Rustam Vishnyakov Date: Thu, 24 May 2012 17:50:27 +0400 Subject: [PATCH 23/45] Fixed WI-10681 Download Error dialog doesn't close on pressing Close button --- .../src/com/intellij/util/net/IOExceptionDialog.java | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java b/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java index 2dbed1f359d8..a6cde49c8888 100644 --- a/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java +++ b/platform/platform-api/src/com/intellij/util/net/IOExceptionDialog.java @@ -20,9 +20,7 @@ import com.intellij.ui.GuiUtils; import javax.swing.*; import java.awt.*; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyEvent; +import java.awt.event.*; import java.lang.reflect.InvocationTargetException; /** @@ -93,6 +91,14 @@ public class IOExceptionDialog extends JDialog { setLocation((parentSize.width - ownSize.width) / 2, (parentSize.height - ownSize.height) / 2); pack(); + setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + cancelPressed = true; + dispose(); + } + }); } /** From 80d7a2069f5af9a206ba806f47922090ae28b3a0 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 16:03:13 +0200 Subject: [PATCH 24/45] touch file when changing its content in groovy compiler tests --- .../plugins/groovy/compiler/GroovyCompilerTestCase.java | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java index d84d6630478d..304540b8e427 100644 --- a/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java +++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/compiler/GroovyCompilerTestCase.java @@ -231,6 +231,7 @@ public abstract class GroovyCompilerTestCase extends JavaCodeInsightFixtureTestC } } }); + touch(file.getVirtualFile()); } protected void setFileName(final PsiFile bar, final String name) { From 5882286166f989d6e187d130dbbd87651943537e Mon Sep 17 00:00:00 2001 From: "Gregory.Shrago" Date: Thu, 24 May 2012 18:36:16 +0400 Subject: [PATCH 25/45] even better column layout --- .../src/com/intellij/ui/table/JBTable.java | 11 +++++++++ .../src/com/intellij/ui/table/TableView.java | 23 +++++++++---------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/platform/platform-api/src/com/intellij/ui/table/JBTable.java b/platform/platform-api/src/com/intellij/ui/table/JBTable.java index 2f67b1bfefe8..342f8578e0e1 100644 --- a/platform/platform-api/src/com/intellij/ui/table/JBTable.java +++ b/platform/platform-api/src/com/intellij/ui/table/JBTable.java @@ -320,6 +320,17 @@ public class JBTable extends JTable implements ComponentWithEmptyText, Component } } + @Override + public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { + if (orientation == SwingConstants.VERTICAL) { + return super.getScrollableUnitIncrement(visibleRect, orientation, direction); + } + else { // if orientation == SwingConstants.HORIZONTAL + // use smooth editor-like scrolling + return SwingUtilities.computeStringWidth(getFontMetrics(getFont()), " "); + } + } + @Override public void doLayout() { super.doLayout(); diff --git a/platform/platform-api/src/com/intellij/ui/table/TableView.java b/platform/platform-api/src/com/intellij/ui/table/TableView.java index 06e05fc8e15d..e9a1c7e5fa26 100644 --- a/platform/platform-api/src/com/intellij/ui/table/TableView.java +++ b/platform/platform-api/src/com/intellij/ui/table/TableView.java @@ -93,8 +93,7 @@ public class TableView extends BaseTableView implements ItemsProvider, Sel int[] sizeMode = new int[columns.length]; int[] headers = new int[columns.length]; int[] widths = new int[columns.length]; - int fixedWidth = 0; - int varWidth = 0; + int allColumnWidth = 0; int varCount = 0; // calculate @@ -132,18 +131,18 @@ public class TableView extends BaseTableView implements ItemsProvider, Sel widths[i] = getFontMetrics(getFont()).stringWidth(preferredValue) + columnInfo.getAdditionalWidth(); varCount ++; } - if (sizeMode[i] == 0) { - fixedWidth += widths[i]; - } - else { - varWidth += widths[i]; - } + allColumnWidth += widths[i]; } - // apply: distribute available space between resizable columns but no more than *4 times. + // apply: distribute available space between resizable columns // and make sure that header will fit as well int viewWidth = getParent() != null? getParent().getWidth() : getWidth(); - int addendum = varCount > 0 && viewWidth > fixedWidth + varWidth? (viewWidth - fixedWidth - varWidth) / varCount : 0; + double gold = 0.5 * (3 - Math.sqrt(5)); + int addendum = + varCount == 0 ? 0 : (int)((allColumnWidth < gold * viewWidth ? gold * viewWidth : + allColumnWidth < (1 - gold) * viewWidth ? (1 - gold) * viewWidth : + viewWidth) - allColumnWidth) / varCount; + for (int i=0 ; i extends BaseTableView implements ItemsProvider, Sel column.setMinWidth(width); } else if (sizeMode[i] == 2) { - width = Math.max(width + Math.min(addendum, 4 * width), headers[i]); + width = Math.max(width + addendum, headers[i]); column.setPreferredWidth(width); column.setMaxWidth(width); } else if (sizeMode[i] == 3) { - width = Math.max(width + Math.min(addendum, 4 * width), headers[i]); + width = Math.max(width + addendum, headers[i]); column.setPreferredWidth(width); } } From 8a08072e3b27dea06d82428a21237408f5a5ab1e Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 24 May 2012 18:08:59 +0400 Subject: [PATCH 26/45] assert message --- .../refactoring/IntroduceVariableMultifileTest.java | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java index ae0e4715867e..e967250b7813 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableMultifileTest.java @@ -74,18 +74,13 @@ public class IntroduceVariableMultifileTest extends MultiFileTestCase { ); } - - public void testDummy() { - - } - PerformAction createAction(final String className, final IntroduceVariableBase testMe) { return new PerformAction() { @Override public void performAction(VirtualFile vroot, VirtualFile rootAfter) { final JavaPsiFacade psiManager = getJavaFacade(); final PsiClass aClass = psiManager.findClass(className, GlobalSearchScope.allScope(myProject)); - assertTrue(aClass != null); + assertTrue(className + " class not found", aClass != null); final PsiFile containingFile = aClass.getContainingFile(); final VirtualFile virtualFile = containingFile.getVirtualFile(); assertTrue(virtualFile != null); From a21cde80724eecbf7fb9281f813a5089ad2d98a7 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 24 May 2012 19:04:36 +0400 Subject: [PATCH 27/45] add error on qualified anonymous class creation when base type interface is (IDEA-57305) --- .../impl/analysis/HighlightClassUtil.java | 31 +++++++++++++------ .../impl/analysis/HighlightVisitorImpl.java | 2 +- .../advHighlighting/QualifiedNew.java | 13 ++++++++ 3 files changed, 35 insertions(+), 11 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index f980b7e3e172..9cf235c20dfe 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -640,7 +640,8 @@ public class HighlightClassUtil { } - public static HighlightInfo checkQualifiedNewOfStaticClass(PsiNewExpression expression) { + @Nullable + public static HighlightInfo checkQualifiedNew(PsiNewExpression expression) { PsiExpression qualifier = expression.getQualifier(); if (qualifier == null) return null; PsiType type = expression.getType(); @@ -652,18 +653,28 @@ public class HighlightClassUtil { return info; } PsiClass aClass = PsiUtil.resolveClassInType(type); - if (aClass != null && aClass.hasModifierProperty(PsiModifier.STATIC)) { - HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, - expression, - JavaErrorMessages.message("qualified.new.of.static.class")); - if (!aClass.isEnum()) { - IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(aClass, PsiModifier.STATIC, false, false); - QuickFixAction.registerQuickFixAction(info, fix); + HighlightInfo info = null; + if (aClass != null) { + if (aClass.hasModifierProperty(PsiModifier.STATIC)) { + info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, + expression, + JavaErrorMessages.message("qualified.new.of.static.class")); + if (!aClass.isEnum()) { + IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(aClass, PsiModifier.STATIC, false, false); + QuickFixAction.registerQuickFixAction(info, fix); + } + + } else if (aClass instanceof PsiAnonymousClass) { + final PsiClass baseClass = PsiUtil.resolveClassInType(((PsiAnonymousClass)aClass).getBaseClassType()); + if (baseClass != null && baseClass.isInterface()) { + info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, + expression, + "Anonymous class implements interface; cannot have qualifier for new"); + } } QuickFixAction.registerQuickFixAction(info, new RemoveNewQualifierFix(expression, aClass)); - return info; } - return null; + return info; } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java index dbe30be7f944..4de3dad216db 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java @@ -698,7 +698,7 @@ public class HighlightVisitorImpl extends JavaElementVisitor implements Highligh @Override public void visitNewExpression(PsiNewExpression expression) { myHolder.add(HighlightUtil.checkUnhandledExceptions(expression, null)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkAnonymousInheritFinal(expression)); - if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkQualifiedNewOfStaticClass(expression)); + if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkQualifiedNew(expression)); if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkCreateInnerClassFromStaticContext(expression)); if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkTypeParameterInstantiation(expression)); try { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedNew.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedNew.java index 28ed2c23d5e9..b832b91dd747 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedNew.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/QualifiedNew.java @@ -17,3 +17,16 @@ class b extends A { static class c {} } + +class WithAnonym { + interface I { + } + class Inner{} +} + +class WithAnonymInheritor extends WithAnonym { + { + this.new I() {}; + this.new Inner() {}; + } +} \ No newline at end of file From 114127cf507a8f5e12e0e93476bf90ecd996ad90 Mon Sep 17 00:00:00 2001 From: Anna Kozlova Date: Thu, 24 May 2012 19:09:45 +0400 Subject: [PATCH 28/45] prefer method with more specific return type (IDEA-67729) --- .../psi/impl/PsiSuperMethodImplUtil.java | 32 +++++++++++++++---- .../afterInterfaceAndAbstractClass.java | 16 ++++++++++ .../beforeInterfaceAndAbstractClass.java | 14 ++++++++ .../codeInsight/OverrideImplementTest.java | 1 + 4 files changed, 56 insertions(+), 7 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/overrideImplement/afterInterfaceAndAbstractClass.java create mode 100644 java/java-tests/testData/codeInsight/overrideImplement/beforeInterfaceAndAbstractClass.java diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java index 20c54525a333..76e0672fbb79 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiSuperMethodImplUtil.java @@ -264,13 +264,31 @@ public class PsiSuperMethodImplUtil { PsiMethod superMethod = superSignatureHierarchical.getMethod(); PsiClass superClass = superMethod.getContainingClass(); PsiClass containingClass = hierarchicalMethodSignature.getMethod().getContainingClass(); - return !superMethod.isConstructor() - && !aClass.equals(superClass) - && PsiUtil.isAccessible(superMethod, aClass, aClass) - && MethodSignatureUtil.isSubsignature(superSignatureHierarchical, hierarchicalMethodSignature) - && superClass != null - && (containingClass != null && containingClass.isInterface() == superClass.isInterface() || superClass.isInterface() || "java.lang.Object".equals(superClass.getQualifiedName())) - ; + if (!superMethod.isConstructor()) { + if (!aClass.equals(superClass)) { + if (PsiUtil.isAccessible(superMethod, aClass, aClass)) { + if (MethodSignatureUtil.isSubsignature(superSignatureHierarchical, hierarchicalMethodSignature)) { + if (superClass != null) { + if (superClass.isInterface() || + "java.lang.Object".equals(superClass.getQualifiedName())) { + return true; + } + + if (containingClass != null) { + if (!containingClass.isInterface()) { + return true; + } + + if (!aClass.isInterface() && !InheritanceUtil.isInheritorOrSelf(superClass, containingClass, true)) { + return true; + } + } + } + } + } + } + } + return false; } private static HierarchicalMethodSignatureImpl copy(HierarchicalMethodSignature hi) { diff --git a/java/java-tests/testData/codeInsight/overrideImplement/afterInterfaceAndAbstractClass.java b/java/java-tests/testData/codeInsight/overrideImplement/afterInterfaceAndAbstractClass.java new file mode 100644 index 000000000000..b90134bce991 --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/afterInterfaceAndAbstractClass.java @@ -0,0 +1,16 @@ +abstract class A { + public abstract D foo(); +} + +interface B { + F foo(); +} + +class C extends A implements B { + public F foo() { + return null; //To change body of implemented methods use File | Settings | File Templates. + } +} + +class D {} +class F extends D {} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/overrideImplement/beforeInterfaceAndAbstractClass.java b/java/java-tests/testData/codeInsight/overrideImplement/beforeInterfaceAndAbstractClass.java new file mode 100644 index 000000000000..74b4f0a7bced --- /dev/null +++ b/java/java-tests/testData/codeInsight/overrideImplement/beforeInterfaceAndAbstractClass.java @@ -0,0 +1,14 @@ +abstract class A { + public abstract D foo(); +} + +interface B { + F foo(); +} + +class C extends A implements B { + +} + +class D {} +class F extends D {} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java index 6f08e55d2c11..3d0a160e8094 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplementTest.java @@ -36,6 +36,7 @@ public class OverrideImplementTest extends LightCodeInsightTestCase { public void testTestMissed() throws Exception { doTest(false); } public void testWildcard() throws Exception { doTest(false); } public void testTypeParam() throws Exception { doTest(false); } + public void testInterfaceAndAbstractClass() throws Exception { doTest(false); } public void testLongFinalParameterList() throws Exception { CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject()).clone(); From d0c4f5eb374ba9c6590a5839371a551ca0088b90 Mon Sep 17 00:00:00 2001 From: "Gregory.Shrago" Date: Thu, 24 May 2012 20:14:16 +0400 Subject: [PATCH 29/45] forbid negative diff --- .../platform-api/src/com/intellij/ui/table/TableView.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/platform/platform-api/src/com/intellij/ui/table/TableView.java b/platform/platform-api/src/com/intellij/ui/table/TableView.java index e9a1c7e5fa26..5333bfb89c50 100644 --- a/platform/platform-api/src/com/intellij/ui/table/TableView.java +++ b/platform/platform-api/src/com/intellij/ui/table/TableView.java @@ -138,10 +138,10 @@ public class TableView extends BaseTableView implements ItemsProvider, Sel // and make sure that header will fit as well int viewWidth = getParent() != null? getParent().getWidth() : getWidth(); double gold = 0.5 * (3 - Math.sqrt(5)); - int addendum = - varCount == 0 ? 0 : (int)((allColumnWidth < gold * viewWidth ? gold * viewWidth : - allColumnWidth < (1 - gold) * viewWidth ? (1 - gold) * viewWidth : - viewWidth) - allColumnWidth) / varCount; + int addendum = varCount == 0 || viewWidth < allColumnWidth ? + 0 : (int)((allColumnWidth < gold * viewWidth ? gold * viewWidth : + allColumnWidth < (1 - gold) * viewWidth ? (1 - gold) * viewWidth : + viewWidth) - allColumnWidth) / varCount; for (int i=0 ; i Date: Thu, 24 May 2012 18:17:51 +0200 Subject: [PATCH 30/45] API for setting per-module bytecode target level --- .../compiler/CompilerConfigurationImpl.java | 23 +++++++++++++++++++ .../compiler/CompilerConfiguration.java | 3 ++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index 5c57b8383f66..cbbcb7ac3002 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -29,6 +29,7 @@ import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler; import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; import com.intellij.compiler.impl.javaCompiler.jikes.JikesCompiler; +import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ex.ApplicationManagerEx; @@ -59,6 +60,7 @@ import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import javax.swing.*; import java.io.File; import java.util.*; @@ -169,6 +171,27 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements return myModuleBytecodeTarget; } + public void setBytecodeTargetLevel(Module module, String level) { + final String previous; + if (StringUtil.isEmpty(level)) { + previous = myModuleBytecodeTarget.remove(module.getName()); + } + else { + previous = myModuleBytecodeTarget.put(module.getName(), level); + } + if (!Comparing.equal(previous, level)) { + final Project project = module.getProject(); + SwingUtilities.invokeLater(new Runnable() { + public void run() { + if (!project.isDisposed()) { + CompileServerManager.getInstance().sendReloadRequest(project); + BuildManager.getInstance().clearState(project); + } + } + }); + } + } + @Override @Nullable public String getBytecodeTargetLevel(Module module) { diff --git a/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java b/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java index f2b8d46c24ea..12e5d3354995 100644 --- a/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java +++ b/java/compiler/openapi/src/com/intellij/compiler/CompilerConfiguration.java @@ -33,6 +33,8 @@ public abstract class CompilerConfiguration { @Nullable public abstract String getBytecodeTargetLevel(Module module); + public abstract void setBytecodeTargetLevel(Module module, String level); + public static CompilerConfiguration getInstance(Project project) { return project.getComponent(CompilerConfiguration.class); } @@ -72,5 +74,4 @@ public abstract class CompilerConfiguration { public abstract boolean isAnnotationProcessingEnabled(Module module); public abstract String getGeneratedSourceDirName(Module module); - } \ No newline at end of file From d5602da28f78bdcee3941bfa99e5c78a182dae7c Mon Sep 17 00:00:00 2001 From: Eugene Zhuravlev Date: Thu, 24 May 2012 18:21:45 +0200 Subject: [PATCH 31/45] clear state for server mode only --- .../src/com/intellij/compiler/CompilerConfigurationImpl.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java index cbbcb7ac3002..6ffe1062d18c 100644 --- a/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java +++ b/java/compiler/impl/src/com/intellij/compiler/CompilerConfigurationImpl.java @@ -29,7 +29,6 @@ import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseCompiler; import com.intellij.compiler.impl.javaCompiler.eclipse.EclipseEmbeddedCompiler; import com.intellij.compiler.impl.javaCompiler.javac.JavacCompiler; import com.intellij.compiler.impl.javaCompiler.jikes.JikesCompiler; -import com.intellij.compiler.server.BuildManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.application.ex.ApplicationManagerEx; @@ -185,7 +184,6 @@ public class CompilerConfigurationImpl extends CompilerConfiguration implements public void run() { if (!project.isDisposed()) { CompileServerManager.getInstance().sendReloadRequest(project); - BuildManager.getInstance().clearState(project); } } }); From eea3338114d2f833fc6343aaa46a50212b148be9 Mon Sep 17 00:00:00 2001 From: Alexander Kirillin Date: Wed, 23 May 2012 19:28:13 +0400 Subject: [PATCH 32/45] Don't show safe delete dialog when there's nothing to delete (e.g. the extension returned no primary/secondary elements) --- .../intellij/refactoring/safeDelete/SafeDeleteHandler.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java index 7dc8e6b4238a..92ce9a481739 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteHandler.java @@ -129,8 +129,10 @@ public class SafeDeleteHandler implements RefactoringActionHandler { }; - SafeDeleteDialog dialog = new SafeDeleteDialog(project, elementsToDelete, callback); - dialog.show(); + if (elementsToDelete.length > 0) { + SafeDeleteDialog dialog = new SafeDeleteDialog(project, elementsToDelete, callback); + dialog.show(); + } } } } From 4f841ee46159ffb99d1a3027e5c1ed3d740561d3 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 16:54:18 +0200 Subject: [PATCH 33/45] avoid completing new HashSet(); --- .../completion/ConstructorInsertHandler.java | 14 ++++++++++++++ .../normal/OverwriteGenericsAfterNew.java | 6 ++++++ .../normal/OverwriteGenericsAfterNew_after.java | 6 ++++++ .../completion/NormalCompletionTest.groovy | 1 + 4 files changed, 27 insertions(+) create mode 100644 java/java-tests/testData/codeInsight/completion/normal/OverwriteGenericsAfterNew.java create mode 100644 java/java-tests/testData/codeInsight/completion/normal/OverwriteGenericsAfterNew_after.java diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java index 6cc5e983fc69..d96b05aaf471 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/ConstructorInsertHandler.java @@ -77,6 +77,19 @@ public class ConstructorInsertHandler implements InsertHandler 0 && ((PsiTypeLookupItem)delegate).calcGenerics(position, context).isEmpty() && context.getCompletionChar() != '('; + + if (context.getDocument().getTextLength() > context.getTailOffset() && + context.getDocument().getCharsSequence().charAt(context.getTailOffset()) == '<') { + PsiJavaCodeReferenceElement ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset(), PsiJavaCodeReferenceElement.class, false); + if (ref != null) { + PsiReferenceParameterList parameterList = ref.getParameterList(); + if (parameterList != null && context.getTailOffset() == parameterList.getTextRange().getStartOffset()) { + context.getDocument().deleteString(parameterList.getTextRange().getStartOffset(), parameterList.getTextRange().getEndOffset()); + context.commitDocument(); + } + } + } + delegate.handleInsert(context); PostprocessReformattingAspect.getInstance(context.getProject()).doPostponedFormatting(context.getFile().getViewProvider()); } @@ -85,6 +98,7 @@ public class ConstructorInsertHandler implements InsertHandler hs = new Ko(); + } +} +class Koo {} diff --git a/java/java-tests/testData/codeInsight/completion/normal/OverwriteGenericsAfterNew_after.java b/java/java-tests/testData/codeInsight/completion/normal/OverwriteGenericsAfterNew_after.java new file mode 100644 index 000000000000..9cd9c1b90b94 --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normal/OverwriteGenericsAfterNew_after.java @@ -0,0 +1,6 @@ +class Bar { + { + Koo hs = new Koo(); + } +} +class Koo {} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy index 90bf9bb2877a..bde8a4883d74 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy @@ -1339,6 +1339,7 @@ public class ListUtils { public void testInterfaceImplementationNoCast() { doTest() } public void testStaticallyImportedMethodsBeforeExpression() { doTest() } public void testInnerChainedReturnType() { doTest() } + public void testOverwriteGenericsAfterNew() { doTest('\n') } private CommonCodeStyleSettings getCodeStyleSettings() { return CodeStyleSettingsManager.getSettings(getProject()).getCommonSettings(JavaLanguage.INSTANCE); From e5054c29813d18f0dbc9ac1641fc3f62771d181c Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 17:30:20 +0200 Subject: [PATCH 34/45] unwrap else should be before remove else in groovy, like in java --- .../jetbrains/plugins/groovy/unwrap/GroovyUnwrapDescriptor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/unwrap/GroovyUnwrapDescriptor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/unwrap/GroovyUnwrapDescriptor.java index dcb1002800d0..72b34b39dff4 100644 --- a/plugins/groovy/src/org/jetbrains/plugins/groovy/unwrap/GroovyUnwrapDescriptor.java +++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/unwrap/GroovyUnwrapDescriptor.java @@ -29,8 +29,8 @@ public class GroovyUnwrapDescriptor extends UnwrapDescriptorBase { new GroovyForUnwrapper(), new GroovyCatchRemover(), new GroovyBracesUnwrapper(), - new GroovyElseRemover(), new GroovyElseUnwrapper(), + new GroovyElseRemover(), new GroovyConditionalUnwrapper(), }; } From f5d677b77535e6915bf21ab7ee66a892daf7a65e Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 17:46:15 +0200 Subject: [PATCH 35/45] more concise closure folding placeholder text (IDEA-86134) --- .../folding/impl/JavaFoldingBuilder.java | 27 ++----------------- 1 file changed, 2 insertions(+), 25 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index 939b55ac9ff5..37dbac58ba57 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -43,7 +43,6 @@ import com.intellij.psi.util.PropertyUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.Function; -import com.intellij.util.ObjectUtils; import com.intellij.util.text.CharArrayUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -626,35 +625,13 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar if (lastLineEnd > 0 && seq.charAt(lastLineEnd) == '\n') lastLineEnd--; if (lastLineEnd < firstLineStart) return false; - final String baseClassName = quick ? - anonymousClass.getBaseClassReference().getReferenceName() : - ObjectUtils.assertNotNull(anonymousClass.getBaseClassType().resolve()).getName(); - if (lastLineEnd >= seq.length() || firstLineStart >= seq.length() || firstLineStart < 0) { - LOG.error("llE=" + lastLineEnd + "; fLS=" + firstLineStart + "; len=" + seq.length() + "rE=" + rangeEnd + "; class=" + - baseClassName); - } - final String params = StringUtil.join(method.getParameterList().getParameters(), new Function() { @Override public String fun(final PsiParameter psiParameter) { - String typeName; - if (quick) { - PsiTypeElement typeElement = psiParameter.getTypeElement(); - assert typeElement != null; - typeName = typeElement.getText(); - } - else { - typeName = psiParameter.getType().getPresentableText(); - } - int genStart = typeName.indexOf('<'); - int genEnd = typeName.lastIndexOf('>'); - if (genStart > 0 && genEnd > 0) { - typeName = typeName.substring(0, genStart) + typeName.substring(genEnd + 1); - } - return typeName + " " + psiParameter.getName(); + return psiParameter.getName(); } }, ", "); - @NonNls final String lambdas = baseClassName + "(" + params + ") {"; + @NonNls final String lambdas = "{" + params + " =>"; final int closureStart = expression.getTextRange().getStartOffset(); final int closureEnd = expression.getTextRange().getEndOffset(); From ea9d514c27e99d6f023f2c6241caa01154d80913 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 18:03:24 +0200 Subject: [PATCH 36/45] don't fold lambda if there's an unresolved type in the throws list --- .../folding/impl/JavaFoldingBuilder.java | 19 ++++++++++++++++--- .../folding/JavaFoldingTest.groovy | 17 +++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index 37dbac58ba57..d5adb200b0cf 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -564,7 +564,7 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar } } - private static boolean hasOnlyOneMethod(@NotNull PsiAnonymousClass anonymousClass) { + private static boolean hasOnlyOneMethod(@NotNull PsiAnonymousClass anonymousClass, boolean checkResolve) { if (anonymousClass.getFields().length != 0) { return false; } @@ -575,7 +575,20 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar return false; } - return anonymousClass.getMethods().length == 1; + if (anonymousClass.getMethods().length != 1) { + return false; + } + + if (checkResolve) { + PsiReferenceList throwsList = anonymousClass.getMethods()[0].getThrowsList(); + for (PsiClassType type : throwsList.getReferencedTypes()) { + if (type.resolve() == null) { + return false; + } + } + } + + return true; } private boolean addClosureFolding(final PsiClass aClass, final Document document, final List foldElements, @@ -593,7 +606,7 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar final PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList != null && argumentList.getExpressions().length == 0) { final PsiMethod[] methods = anonymousClass.getMethods(); - if (hasOnlyOneMethod(anonymousClass) && (quick || seemsLikeLambda(anonymousClass.getBaseClassType().resolve()))) { + if (hasOnlyOneMethod(anonymousClass, !quick) && (quick || seemsLikeLambda(anonymousClass.getBaseClassType().resolve()))) { final PsiMethod method = methods[0]; final PsiCodeBlock body = method.getBody(); if (body != null) { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy index fe161e00f75c..341073fbf254 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy @@ -195,6 +195,23 @@ class Test { assert closureStartFold } + public void "test no closure folding when the method throws an unresolved exception"() { + def text = """\ +class Test { + void test() { new Runnable() { + public void run() throws Asadfsdafdfasd { + System.out.println(); + } + }; + } +} +""" + + configure text + def foldingModel = myFixture.editor.foldingModel as FoldingModelImpl + assert !foldingModel.getCollapsedRegionAtOffset(text.indexOf("Runnable")) + } + public void testFindInFolding() { def text = """\ class Test { From 382b5d03f83801b3f5aab69eee6d55c7fc06fc61 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 18:22:36 +0200 Subject: [PATCH 37/45] ignore serialVersionUID field when checking for lambda folding (IDEA-86549) --- .../daemon/impl/analysis/HighlightUtil.java | 2 +- .../codeInsight/folding/impl/JavaFoldingBuilder.java | 11 +++++++++-- .../deadCode/UnusedDeclarationInspection.java | 3 ++- .../codeInsight/folding/JavaFoldingTest.groovy | 1 + .../src/com/siyeh/HardcodedMethodConstants.java | 3 ++- 5 files changed, 15 insertions(+), 5 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index 3a54ada2c167..fbfa4f463cda 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -78,7 +78,7 @@ public class HighlightUtil { private static final Map> ourClassInitializerIncompatibleModifiers; private static final Set ourConstructorNotAllowedModifiers; - @NonNls private static final String SERIAL_VERSION_UID_FIELD_NAME = "serialVersionUID"; + @NonNls public static final String SERIAL_VERSION_UID_FIELD_NAME = "serialVersionUID"; @NonNls private static final String SERIAL_PERSISTENT_FIELDS_FIELD_NAME = "serialPersistentFields"; private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance(); diff --git a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java index d5adb200b0cf..e183c5d8e9da 100644 --- a/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java +++ b/java/java-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilder.java @@ -16,6 +16,7 @@ package com.intellij.codeInsight.folding.impl; import com.intellij.codeInsight.daemon.impl.CollectHighlightsUtil; +import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.folding.JavaCodeFoldingSettings; import com.intellij.codeInsight.generation.OverrideImplementUtil; import com.intellij.lang.ASTNode; @@ -565,8 +566,14 @@ public class JavaFoldingBuilder extends CustomFoldingBuilder implements DumbAwar } private static boolean hasOnlyOneMethod(@NotNull PsiAnonymousClass anonymousClass, boolean checkResolve) { - if (anonymousClass.getFields().length != 0) { - return false; + PsiField[] fields = anonymousClass.getFields(); + if (fields.length != 0) { + if (fields.length == 1 && HighlightUtil.SERIAL_VERSION_UID_FIELD_NAME.equals(fields[0].getName()) && + fields[0].hasModifierProperty(PsiModifier.STATIC)) { + //ok + } else { + return false; + } } if (anonymousClass.getInitializers().length != 0) { return false; diff --git a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java index d4d740f832b7..02dff3f737f1 100644 --- a/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java +++ b/java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspection.java @@ -30,6 +30,7 @@ import com.intellij.analysis.AnalysisScope; import com.intellij.codeInsight.AnnotationUtil; import com.intellij.codeInsight.daemon.GroupNames; import com.intellij.codeInsight.daemon.ImplicitUsageProvider; +import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ex.*; @@ -266,7 +267,7 @@ public class UnusedDeclarationInspection extends FilteringInspectionTool { private static boolean isSerializationImplicitlyUsedField(PsiField field) { @NonNls final String name = field.getName(); - if (!"serialVersionUID".equals(name) && !"serialPersistentFields".equals(name)) return false; + if (!HighlightUtil.SERIAL_VERSION_UID_FIELD_NAME.equals(name) && !"serialPersistentFields".equals(name)) return false; if (!field.hasModifierProperty(PsiModifier.STATIC)) return false; PsiClass aClass = field.getContainingClass(); return aClass == null || isSerializable(aClass, null); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy index 341073fbf254..20830a89f107 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/folding/JavaFoldingTest.groovy @@ -174,6 +174,7 @@ class Test { class Test { void test() { new Runnable() { + static final long serialVersionUID = 42L; public void run() { System.out.println(); } diff --git a/plugins/InspectionGadgets/src/com/siyeh/HardcodedMethodConstants.java b/plugins/InspectionGadgets/src/com/siyeh/HardcodedMethodConstants.java index 2d10d5529ec2..5ab72dbf62ce 100644 --- a/plugins/InspectionGadgets/src/com/siyeh/HardcodedMethodConstants.java +++ b/plugins/InspectionGadgets/src/com/siyeh/HardcodedMethodConstants.java @@ -15,6 +15,7 @@ */ package com.siyeh; +import com.intellij.codeInsight.daemon.impl.analysis.HighlightUtil; import org.jetbrains.annotations.NonNls; /** @@ -57,7 +58,7 @@ public class HardcodedMethodConstants { public static final String PRINT_STACK_TRACE = "printStackTrace"; public static final String REMOVE = "remove"; public static final String RUN = "run"; - public static final String SERIAL_VERSION_UID = "serialVersionUID"; + public static final String SERIAL_VERSION_UID = HighlightUtil.SERIAL_VERSION_UID_FIELD_NAME; public static final String SET = "set"; public static final String SIZE = "size"; public static final String STARTS_WITH = "startsWith"; From efdf0ca923d541a9b65dce622bf98a96136b93f8 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 18:42:40 +0200 Subject: [PATCH 38/45] prefer better matching constants to methods --- .../completion/JavaCompletionSorting.java | 25 +++++++++++-------- ...PreferBetterMatchingConstantToMethods.java | 10 ++++++++ .../NormalCompletionOrderingTest.groovy | 6 ++++- 3 files changed, 29 insertions(+), 12 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/completion/normalSorting/PreferBetterMatchingConstantToMethods.java diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java index 44701a3ab0de..7ab43ceb5fc0 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java @@ -60,7 +60,7 @@ public class JavaCompletionSorting { List afterNegativeStats = new ArrayList(); if (!smart) { - ContainerUtil.addIfNotNull(afterNegativeStats, preferStatics(position)); + ContainerUtil.addIfNotNull(afterNegativeStats, preferStatics(position, expectedTypes)); } afterNegativeStats.add(new PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(type, position)); ContainerUtil.addIfNotNull(afterNegativeStats, recursion(parameters, expectedTypes)); @@ -126,7 +126,7 @@ public class JavaCompletionSorting { } @Nullable - private static LookupElementWeigher preferStatics(PsiElement position) { + private static LookupElementWeigher preferStatics(PsiElement position, final ExpectedTypeInfo[] infos) { if (PsiTreeUtil.getParentOfType(position, PsiDocComment.class) != null) { return null; } @@ -149,7 +149,7 @@ public class JavaCompletionSorting { if (o instanceof PsiKeyword) return -3; if (!(o instanceof PsiMember)) return 0; - if (((PsiMember)o).hasModifierProperty(PsiModifier.STATIC)) { + if (((PsiMember)o).hasModifierProperty(PsiModifier.STATIC) && !hasNonVoid(infos)) { if (o instanceof PsiMethod) return -5; if (o instanceof PsiField) return -4; } @@ -179,14 +179,7 @@ public class JavaCompletionSorting { } } - boolean hasNonVoid = false; - for (ExpectedTypeInfo info : expectedInfos) { - if (!PsiType.VOID.equals(info.getType())) { - hasNonVoid = true; - } - } - - if (hasNonVoid) { + if (hasNonVoid(expectedInfos)) { if (item.getObject() instanceof PsiKeyword) { String keyword = ((PsiKeyword)item.getObject()).getText(); if (PsiKeyword.NEW.equals(keyword) || PsiKeyword.NULL.equals(keyword)) { @@ -201,6 +194,16 @@ public class JavaCompletionSorting { return ExpectedTypeMatching.normal; } + private static boolean hasNonVoid(ExpectedTypeInfo[] expectedInfos) { + boolean hasNonVoid = false; + for (ExpectedTypeInfo info : expectedInfos) { + if (!PsiType.VOID.equals(info.getType())) { + hasNonVoid = true; + } + } + return hasNonVoid; + } + @Nullable private static String getLookupObjectName(Object o) { if (o instanceof PsiVariable) { diff --git a/java/java-tests/testData/codeInsight/completion/normalSorting/PreferBetterMatchingConstantToMethods.java b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferBetterMatchingConstantToMethods.java new file mode 100644 index 000000000000..456e747a3d5d --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferBetterMatchingConstantToMethods.java @@ -0,0 +1,10 @@ +class Foo { + String s = Util.se +} + +class Util { + public static final String serial = "serialVersionUID"; + + public static Runnable superExpressionInIllegalContext() {} + +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy index a3c6273a587a..ac6f6f3766ec 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy @@ -87,7 +87,7 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase { final String path = getTestName(false) + ".java"; myFixture.configureByFile(path); myFixture.complete(CompletionType.BASIC, 2); - assertPreferredItems(0, "booleanMethod", "voidMethod", "registerNatives", "BOOLEAN", "AN_OBJECT"); + assertPreferredItems(0, "BOOLEAN", "booleanMethod", "AN_OBJECT", "voidMethod", "registerNatives"); } public void testDispreferDeclared() throws Throwable { @@ -314,4 +314,8 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase { checkPreferredItems 0, 'noo', 'new', 'null', 'noo2', 'notify', 'notifyAll' } + public void testPreferBetterMatchingConstantToMethods() { + checkPreferredItems 0, 'serial', 'superExpressionInIllegalContext' + } + } From fb1e707d8186f9caa4d3f5d7ac408090652a3eef Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 18:51:55 +0200 Subject: [PATCH 39/45] use expected type statistics in basic completio, too --- .../completion/JavaCompletionStatistician.java | 16 ++++++---------- .../NormalCompletionOrderingTest.groovy | 10 +++++++++- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java index d05c520a1a67..9d0b5d02e854 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionStatistician.java @@ -62,17 +62,13 @@ public class JavaCompletionStatistician extends CompletionStatistician{ if (o instanceof PsiMember) { final boolean isClass = o instanceof PsiClass; if (qualifierType != null) { - if (type == CompletionType.SMART) { - String context; - if (isClass) { - context = JavaStatisticsManager.getAfterNewKey(qualifierType); - } else { - context = JavaStatisticsManager.getMemberUseKey1(qualifierType); - } - return new StatisticsInfo(context, JavaStatisticsManager.getMemberUseKey2((PsiMember)o)); + String context; + if (isClass) { + context = JavaStatisticsManager.getAfterNewKey(qualifierType); + } else { + context = JavaStatisticsManager.getMemberUseKey1(qualifierType); } - if (!isClass && type == CompletionType.BASIC) return JavaStatisticsManager.createInfo(qualifierType, (PsiMember)o); - return StatisticsInfo.EMPTY; + return new StatisticsInfo(context, JavaStatisticsManager.getMemberUseKey2((PsiMember)o)); } if (isClass) { diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy index ac6f6f3766ec..cdea5d74109c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy @@ -8,11 +8,11 @@ package com.intellij.codeInsight.completion; import com.intellij.JavaTestUtil import com.intellij.codeInsight.CodeInsightSettings import com.intellij.codeInsight.lookup.LookupElement +import com.intellij.codeInsight.lookup.LookupElementPresentation import com.intellij.codeInsight.lookup.impl.LookupImpl import com.intellij.ide.ui.UISettings import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod -import com.intellij.codeInsight.lookup.LookupElementPresentation public class NormalCompletionOrderingTest extends CompletionSortingTestCase { private static final String BASE_PATH = "/codeInsight/completion/normalSorting"; @@ -318,4 +318,12 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase { checkPreferredItems 0, 'serial', 'superExpressionInIllegalContext' } + public void testJComponentAddNewWithStats() throws Throwable { + final LookupImpl lookup = invokeCompletion("/../smartTypeSorting/JComponentAddNew.java"); + assertPreferredItems(0, "FooBean3", "JComponent", "Component"); + incUseCount(lookup, 2); //Component + assertPreferredItems(0, "Component", "FooBean3", "JComponent"); + } + + } From ca0caaa6981e08ab78b8dd0d6f3b38b07d009085 Mon Sep 17 00:00:00 2001 From: peter Date: Thu, 24 May 2012 19:02:41 +0200 Subject: [PATCH 40/45] disprefer return before statement --- ...alVariablesLiteralsAndAnnoMethodsWeigher.java | 16 +++++++++++++++- .../DispreferReturnBeforeStatement.java | 7 +++++++ .../NormalCompletionOrderingTest.groovy | 4 ++++ 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 java/java-tests/testData/codeInsight/completion/normalSorting/DispreferReturnBeforeStatement.java diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/PreferLocalVariablesLiteralsAndAnnoMethodsWeigher.java b/java/java-impl/src/com/intellij/codeInsight/completion/PreferLocalVariablesLiteralsAndAnnoMethodsWeigher.java index 7c1a3b877601..d64ab398b42a 100644 --- a/java/java-impl/src/com/intellij/codeInsight/completion/PreferLocalVariablesLiteralsAndAnnoMethodsWeigher.java +++ b/java/java-impl/src/com/intellij/codeInsight/completion/PreferLocalVariablesLiteralsAndAnnoMethodsWeigher.java @@ -21,6 +21,7 @@ import com.intellij.codeInsight.lookup.LookupElementWeigher; import com.intellij.psi.*; import com.intellij.psi.filters.getters.MembersGetter; import com.intellij.psi.util.PropertyUtil; +import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.Set; @@ -30,11 +31,13 @@ import java.util.Set; */ public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupElementWeigher { private final CompletionType myCompletionType; + private final PsiElement myPosition; private final Set myNonInitializedFields; public PreferLocalVariablesLiteralsAndAnnoMethodsWeigher(CompletionType completionType, PsiElement position) { super("local"); myCompletionType = completionType; + myPosition = position; myNonInitializedFields = JavaCompletionProcessor.getNonInitializedFields(position); } @@ -60,7 +63,10 @@ public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupEle if (object instanceof PsiKeyword) { String keyword = ((PsiKeyword)object).getText(); - if (PsiKeyword.RETURN.equals(keyword) || PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) { + if (PsiKeyword.RETURN.equals(keyword) && isLastStatement(PsiTreeUtil.getParentOfType(myPosition, PsiStatement.class))) { + return MyResult.probableKeyword; + } + if (PsiKeyword.ELSE.equals(keyword) || PsiKeyword.FINALLY.equals(keyword)) { return MyResult.probableKeyword; } } @@ -118,4 +124,12 @@ public class PreferLocalVariablesLiteralsAndAnnoMethodsWeigher extends LookupEle return MyResult.normal; } + + private static boolean isLastStatement(PsiStatement statement) { + if (statement == null || !(statement.getParent() instanceof PsiCodeBlock)) { + return true; + } + PsiStatement[] siblings = ((PsiCodeBlock)statement.getParent()).getStatements(); + return statement == siblings[siblings.length - 1]; + } } diff --git a/java/java-tests/testData/codeInsight/completion/normalSorting/DispreferReturnBeforeStatement.java b/java/java-tests/testData/codeInsight/completion/normalSorting/DispreferReturnBeforeStatement.java new file mode 100644 index 000000000000..181d4481c5cc --- /dev/null +++ b/java/java-tests/testData/codeInsight/completion/normalSorting/DispreferReturnBeforeStatement.java @@ -0,0 +1,7 @@ +class Util { + void foo(int reaction, boolean rezet) { + re + System.out.println(); + } + +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy index cdea5d74109c..df62e225be87 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy +++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy @@ -325,5 +325,9 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase { assertPreferredItems(0, "Component", "FooBean3", "JComponent"); } + public void testDispreferReturnBeforeStatement() { + checkPreferredItems 0, 'reaction', 'rezet', 'return' + } + } From df60337ea6382fab034246a69d6366f4d35eb767 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Thu, 24 May 2012 13:54:59 +0400 Subject: [PATCH 41/45] To JB dic --- .../spellchecker/src/com/intellij/spellchecker/jetbrains.dic | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic b/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic index 08ec882113d4..b66cb41a1fe0 100644 --- a/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic +++ b/plugins/spellchecker/src/com/intellij/spellchecker/jetbrains.dic @@ -132,6 +132,7 @@ hardlinks helvetica holdability hostname +hprof href hsqldb html @@ -156,6 +157,7 @@ iphoneos isnull javabean javabeans +javac javadoc javaee javascript @@ -378,12 +380,14 @@ stateful stdarg stdlib stmt +strictfp stylesheet stylesheets sublicense subpackage subpartition subpartitions +subst substring subtree subtrees From 5a7dd9710892f7d3006a2a098dce0c1188c4a997 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Thu, 24 May 2012 18:09:08 +0400 Subject: [PATCH 42/45] Do not highlight extension methods' bodies --- .../impl/analysis/HighlightMethodUtil.java | 29 +-- .../daemon/impl/analysis/HighlightUtil.java | 8 +- .../src/com/intellij/psi/util/PsiUtil.java | 12 +- .../src/messages/JavaErrorMessages.properties | 3 +- .../advHighlighting/UnsupportedFeatures.java | 4 + .../advHighlighting7/ExtensionMethods.java | 21 ++ .../daemon/LightAdvHighlightingJdk7Test.java | 208 ++++-------------- 7 files changed, 104 insertions(+), 181 deletions(-) create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java index 399082d491c6..d124608b2ad3 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java @@ -838,14 +838,19 @@ public class HighlightMethodUtil { return null; } - + @Nullable static HighlightInfo checkMethodCanHaveBody(PsiMethod method) { if (method.getBody() == null) return null; PsiClass aClass = method.getContainingClass(); String message = null; if (aClass != null && aClass.isInterface()) { - message = JavaErrorMessages.message("interface.methods.cannot.have.body"); + if (!PsiUtil.isExtensionMethod(method)) { + message = JavaErrorMessages.message("interface.methods.cannot.have.body"); + } + else { + return HighlightUtil.checkExtensionMethodsFeature(method); + } } else if (method.hasModifierProperty(PsiModifier.ABSTRACT)) { message = JavaErrorMessages.message("abstract.methods.cannot.have.a.body"); @@ -853,21 +858,19 @@ public class HighlightMethodUtil { else if (method.hasModifierProperty(PsiModifier.NATIVE)) { message = JavaErrorMessages.message("native.methods.cannot.have.a.body"); } + if (message == null) return null; - if (message != null) { - TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method); - HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, textRange, message); - QuickFixAction.registerQuickFixAction(info, new DeleteMethodBodyFix(method)); - if (method.hasModifierProperty(PsiModifier.ABSTRACT) && aClass != null && !aClass.isInterface()) { - IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false); - QuickFixAction.registerQuickFixAction(info, fix); - } - return info; + TextRange textRange = HighlightNamesUtil.getMethodDeclarationTextRange(method); + HighlightInfo info = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, textRange, message); + QuickFixAction.registerQuickFixAction(info, new DeleteMethodBodyFix(method)); + if (method.hasModifierProperty(PsiModifier.ABSTRACT) && aClass != null && !aClass.isInterface()) { + IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.ABSTRACT, false, false); + QuickFixAction.registerQuickFixAction(info, fix); } - return null; + return info; } - + @Nullable static HighlightInfo checkConstructorCallMustBeFirstStatement(PsiReferenceExpression expression) { PsiElement methodCall = expression.getParent(); if (!HighlightUtil.isSuperOrThisMethodCall(methodCall)) return null; diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index fbfa4f463cda..9599336f1a87 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -2481,7 +2481,8 @@ public class HighlightUtil { VARARGS(LanguageLevel.JDK_1_5, "feature.varargs"), DIAMOND_TYPES(LanguageLevel.JDK_1_7, "feature.diamond.types"), MULTI_CATCH(LanguageLevel.JDK_1_7, "feature.multi.catch"), - TRY_WITH_RESOURCES(LanguageLevel.JDK_1_7, "feature.try.with.resources"); + TRY_WITH_RESOURCES(LanguageLevel.JDK_1_7, "feature.try.with.resources"), + EXTENSION_METHODS(LanguageLevel.JDK_1_8, "feature.extension.methods"); private final LanguageLevel level; private final String key; @@ -2544,4 +2545,9 @@ public class HighlightUtil { public static HighlightInfo checkTryWithResourcesFeature(final PsiResourceVariable resourceVariable) { return checkFeature(resourceVariable.getParent(), Feature.TRY_WITH_RESOURCES); } + + @Nullable + public static HighlightInfo checkExtensionMethodsFeature(final PsiMethod method) { + return checkFeature(method, Feature.EXTENSION_METHODS); + } } diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java index a6f6ba762f61..278a04df5c65 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java @@ -318,7 +318,9 @@ public final class PsiUtil extends PsiUtilCore { @PsiModifier.ModifierConstant @Nullable public static String getAccessModifier(int accessLevel) { - return accessLevel > accessModifiers.length ? null : accessModifiers[accessLevel - 1]; + @SuppressWarnings("UnnecessaryLocalVariable") @PsiModifier.ModifierConstant + final String modifier = accessLevel > accessModifiers.length ? null : accessModifiers[accessLevel - 1]; + return modifier; } private static final String[] accessModifiers = { @@ -952,4 +954,12 @@ public final class PsiUtil extends PsiUtilCore { public static boolean isIgnoredName(@Nullable final String name) { return "ignore".equals(name) || "ignored".equals(name); } + + public static boolean isExtensionMethod(@Nullable final PsiMethod method) { + if (method == null) return false; + final PsiCodeBlock body = method.getBody(); + if (body == null) return false; + final PsiElement previous = PsiTreeUtil.skipSiblingsBackward(body, PsiComment.class, PsiWhiteSpace.class); + return isJavaToken(previous, JavaTokenType.DEFAULT_KEYWORD); + } } diff --git a/java/java-psi-impl/src/messages/JavaErrorMessages.properties b/java/java-psi-impl/src/messages/JavaErrorMessages.properties index cbbf40de4ceb..3aae6ea3712b 100644 --- a/java/java-psi-impl/src/messages/JavaErrorMessages.properties +++ b/java/java-psi-impl/src/messages/JavaErrorMessages.properties @@ -349,6 +349,7 @@ feature.static.imports=Static imports feature.for.each=For-each loops feature.varargs=Variable arity methods feature.diamond.types=Diamond types -feature.try.with.resources=Try-with-resources feature.multi.catch=Multi-catches +feature.try.with.resources=Try-with-resources +feature.extension.methods=Extension methods insufficient.language.level={0} are not supported at this language level diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnsupportedFeatures.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnsupportedFeatures.java index 9701b4b373b2..0aa0409aa34d 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnsupportedFeatures.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnsupportedFeatures.java @@ -38,4 +38,8 @@ class UnsupportedFeatures { try (Reader r = new FileReader("/dev/null")) { } } + + interface I { + void m() default { } + } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java new file mode 100644 index 000000000000..478b76d6eb8d --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java @@ -0,0 +1,21 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class C { + interface I { + void m1() { } + void m2() default { } + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java index 8165329c5130..acb08fd82d81 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java @@ -57,126 +57,36 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase { }; } - public void testAllJava15Features() throws Exception { - doTest(false, false); - } - - public void testEnumSyntheticMethods() throws Exception { - doTest(false, false); - } - - public void testDuplicateAnnotations() throws Exception { - doTest(false, false); - } - - public void testSwitchByString() throws Exception { - doTest(false, false); - } - - public void testSwitchByInaccessibleEnum() throws Exception { - doTest(false, false); - } - - public void testDiamondPos1() throws Exception { - doTest(false, false); - } - - public void testDiamondPos2() throws Exception { - doTest(false, false); - } - - public void testDiamondPos3() throws Exception { - doTest(false, false); - } - - public void testDiamondPos4() throws Exception { - doTest(false, false); - } - - public void testDiamondPos5() throws Exception { - doTest(false, false); - } - - - public void testDiamondPos6() throws Exception { - doTest(false, false); - } - - public void testDiamondPos7() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg15() throws Exception { - doTest(false, false); - } - - public void testDiamondPos9() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg1() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg2() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg3() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg4() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg5() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg6() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg7() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg8() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg9() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg10() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg11() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg12() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg13() throws Exception { - doTest(false, false); - } - - public void testDiamondNeg14() throws Exception { - doTest(false, false); - } - - public void testDiamondMisc() throws Exception { - doTest(false, false); - } - - public void testHighlightInaccessibleFromClassModifierList() throws Exception { - doTest(false, false); - } + public void testAllJava15Features() throws Exception { doTest(false, false); } + public void testEnumSyntheticMethods() throws Exception { doTest(false, false); } + public void testDuplicateAnnotations() throws Exception { doTest(false, false); } + public void testSwitchByString() throws Exception { doTest(false, false); } + public void testSwitchByInaccessibleEnum() throws Exception { doTest(false, false); } + public void testDiamondPos1() throws Exception { doTest(false, false); } + public void testDiamondPos2() throws Exception { doTest(false, false); } + public void testDiamondPos3() throws Exception { doTest(false, false); } + public void testDiamondPos4() throws Exception { doTest(false, false); } + public void testDiamondPos5() throws Exception { doTest(false, false); } + public void testDiamondPos6() throws Exception { doTest(false, false); } + public void testDiamondPos7() throws Exception { doTest(false, false); } + public void testDiamondNeg15() throws Exception { doTest(false, false); } + public void testDiamondPos9() throws Exception { doTest(false, false); } + public void testDiamondNeg1() throws Exception { doTest(false, false); } + public void testDiamondNeg2() throws Exception { doTest(false, false); } + public void testDiamondNeg3() throws Exception { doTest(false, false); } + public void testDiamondNeg4() throws Exception { doTest(false, false); } + public void testDiamondNeg5() throws Exception { doTest(false, false); } + public void testDiamondNeg6() throws Exception { doTest(false, false); } + public void testDiamondNeg7() throws Exception { doTest(false, false); } + public void testDiamondNeg8() throws Exception { doTest(false, false); } + public void testDiamondNeg9() throws Exception { doTest(false, false); } + public void testDiamondNeg10() throws Exception { doTest(false, false); } + public void testDiamondNeg11() throws Exception { doTest(false, false); } + public void testDiamondNeg12() throws Exception { doTest(false, false); } + public void testDiamondNeg13() throws Exception { doTest(false, false); } + public void testDiamondNeg14() throws Exception { doTest(false, false); } + public void testDiamondMisc() throws Exception { doTest(false, false); } + public void testHighlightInaccessibleFromClassModifierList() throws Exception { doTest(false, false); } public void testDynamicallyAddIgnoredAnnotations() throws Exception { ExtensionPoint point = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL); @@ -242,46 +152,21 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase { } } - public void testNumericLiterals() throws Exception { - doTest(false, false); - } - - public void testMultiCatch() throws Exception { - doTest(false, false); - } - - public void testTryWithResources() throws Exception { - doTest(false, false); - } + public void testNumericLiterals() throws Exception { doTest(false, false); } + public void testMultiCatch() throws Exception { doTest(false, false); } + public void testTryWithResources() throws Exception { doTest(false, false); } public void testTryWithResourcesWarn() throws Exception { enableInspectionTool(new DefUseInspection()); doTest(true, false); } - public void testSafeVarargsApplicability() throws Exception { - doTest(true, false); - } - - public void testUncheckedGenericsArrayCreation() throws Exception { - doTest(true, false); - } - - public void testPreciseRethrow() throws Exception { - doTest(false, false); - } - - public void testImprovedCatchAnalysis() throws Exception { - doTest(true, false); - } - - public void testJavacQuirks() throws Exception { - doTest(true, false); - } - - public void testPolymorphicTypeCast() throws Exception { - doTest(true, false); - } + public void testSafeVarargsApplicability() throws Exception { doTest(true, false); } + public void testUncheckedGenericsArrayCreation() throws Exception { doTest(true, false); } + public void testPreciseRethrow() throws Exception { doTest(false, false); } + public void testImprovedCatchAnalysis() throws Exception { doTest(true, false); } + public void testJavacQuirks() throws Exception { doTest(true, false); } + public void testPolymorphicTypeCast() throws Exception { doTest(true, false); } public void testErasureClashConfusion() throws Exception { enableInspectionTool(new UnusedDeclarationInspection()); @@ -293,16 +178,9 @@ public class LightAdvHighlightingJdk7Test extends LightDaemonAnalyzerTestCase { doTest(true, false); } - public void testSuperBound() throws Exception { - doTest(false, false); - } - - public void testExtendsBound() throws Exception { - doTest(false, false); - } - + public void testSuperBound() throws Exception { doTest(false, false); } + public void testExtendsBound() throws Exception { doTest(false, false); } public void testIDEA84533() throws Exception { doTest(false, false); } - - public void testClassLiteral() throws Exception { doTest(false, false);} + public void testClassLiteral() throws Exception { doTest(false, false); } + public void testExtensionMethods() throws Exception { doTest(false, false); } } - From 3f4aca11bdc100974c651f340a852e2333f3a44d Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Thu, 24 May 2012 19:12:39 +0400 Subject: [PATCH 43/45] Extension methods aren't abstract --- .../psi/impl/cache/ModifierFlags.java | 6 +- .../intellij/psi/impl/cache/RecordUtil.java | 101 +++++------------- .../impl/compiled/StubBuildingVisitor.java | 36 ++++--- .../java/stubs/JavaMethodElementType.java | 15 ++- .../psi/impl/java/stubs/PsiMethodStub.java | 3 +- .../java/stubs/impl/PsiMethodStubImpl.java | 20 +++- .../psi/impl/source/JavaFileElementType.java | 4 +- .../psi/impl/source/PsiModifierListImpl.java | 5 +- .../advHighlighting7/ExtensionMethods.java | 8 +- .../com/intellij/psi/JavaStubBuilderTest.java | 26 ++++- 10 files changed, 112 insertions(+), 112 deletions(-) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/cache/ModifierFlags.java b/java/java-psi-impl/src/com/intellij/psi/impl/cache/ModifierFlags.java index 46d734d549bd..342f4bbbdc6c 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/cache/ModifierFlags.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/cache/ModifierFlags.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ package com.intellij.psi.impl.cache; * @author max */ public interface ModifierFlags { -// ---- The group equal to corresponding in ClsUtil.ACC_* int PUBLIC_MASK = 0x0001; int PRIVATE_MASK = 0x0002; int PROTECTED_MASK = 0x0004; @@ -31,9 +30,8 @@ public interface ModifierFlags { int TRANSIENT_MASK = 0x0080; int NATIVE_MASK = 0x0100; int INTERFACE_MASK = 0x0200; + int DEFENDER_MASK = 0x0200; int ABSTRACT_MASK = 0x0400; -// ---- End of the group equal to corresponding in ClsUtil.ACC_* - int STRICTFP_MASK = 0x0800; int PACKAGE_LOCAL_MASK = 0x1000; int DEPRECATED_MASK = 0x2000; diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/cache/RecordUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/cache/RecordUtil.java index 677c9a002a82..b3f90b70dfd6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/cache/RecordUtil.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/cache/RecordUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,12 +30,8 @@ import com.intellij.psi.tree.IElementType; import com.intellij.util.CharTable; import gnu.trove.TObjectIntHashMap; import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.LinkedHashSet; import java.util.List; -import java.util.Set; /** * @author max @@ -123,7 +119,7 @@ public class RecordUtil { else if (parent instanceof PsiMethodStub) { if (grandParent instanceof PsiClassStub && ((PsiClassStub)grandParent).isInterface()) { alreadyPublic = true; - alreadyAbstract = true; + alreadyAbstract = !((PsiMethodStub)parent).isDefender(); } } else if (parent instanceof PsiFieldStub) { @@ -143,27 +139,37 @@ public class RecordUtil { for (final LighterASTNode child : tree.getChildren(modList)) { final IElementType type = child.getTokenType(); - if(type == JavaTokenType.PUBLIC_KEYWORD) { + if (type == JavaTokenType.PUBLIC_KEYWORD) { alreadyPublic = true; - } else if(type == JavaTokenType.PRIVATE_KEYWORD) { + } + else if (type == JavaTokenType.PRIVATE_KEYWORD) { packed |= ModifierFlags.PRIVATE_MASK; - } else if(type == JavaTokenType.PROTECTED_KEYWORD) { + } + else if (type == JavaTokenType.PROTECTED_KEYWORD) { packed |= ModifierFlags.PROTECTED_MASK; - } else if(type == JavaTokenType.ABSTRACT_KEYWORD) { - alreadyAbstract =true; - } else if (type == JavaTokenType.FINAL_KEYWORD) { + } + else if (type == JavaTokenType.ABSTRACT_KEYWORD) { + alreadyAbstract = true; + } + else if (type == JavaTokenType.FINAL_KEYWORD) { alreadyFinal = true; - } else if (type == JavaTokenType.STATIC_KEYWORD) { + } + else if (type == JavaTokenType.STATIC_KEYWORD) { alreadyStatic = true; - } else if(type == JavaTokenType.NATIVE_KEYWORD) { + } + else if (type == JavaTokenType.NATIVE_KEYWORD) { packed |= ModifierFlags.NATIVE_MASK; - } else if (type == JavaTokenType.SYNCHRONIZED_KEYWORD) { + } + else if (type == JavaTokenType.SYNCHRONIZED_KEYWORD) { packed |= ModifierFlags.SYNCHRONIZED_MASK; - } else if (type == JavaTokenType.TRANSIENT_KEYWORD) { + } + else if (type == JavaTokenType.TRANSIENT_KEYWORD) { packed |= ModifierFlags.TRANSIENT_MASK; - } else if (type == JavaTokenType.VOLATILE_KEYWORD) { + } + else if (type == JavaTokenType.VOLATILE_KEYWORD) { packed |= ModifierFlags.VOLATILE_MASK; - } else if (type == JavaTokenType.STRICTFP_KEYWORD) { + } + else if (type == JavaTokenType.STRICTFP_KEYWORD) { packed |= ModifierFlags.STRICTFP_MASK; } } @@ -175,8 +181,7 @@ public class RecordUtil { if ((packed & ModifierFlags.PRIVATE_MASK) == 0 && (packed & ModifierFlags.PROTECTED_MASK) == 0 && - (packed & ModifierFlags.PUBLIC_MASK) == 0 - ) { + (packed & ModifierFlags.PUBLIC_MASK) == 0) { packed |= ModifierFlags.PACKAGE_LOCAL_MASK; } @@ -217,62 +222,6 @@ public class RecordUtil { return (ourModifierNameToFlagMap.get(psiModifier) & packed) != 0; } - @SuppressWarnings({"unchecked"}) - private static final Set[] SET_INSTANCES = new Set[8 * 4]; - - private static final String[] VISIBILITY_MODIFIERS = {null, PsiModifier.PUBLIC, PsiModifier.PRIVATE, PsiModifier.PROTECTED}; - - private static final int[] MODIFIER_MAP = {0, 1, 2, -1, 3, -1, -1, -1, -1}; - - static { - SET_INSTANCES[0] = Collections.emptySet(); - for (int i = 1; i < 4; i++) { - SET_INSTANCES[i << 3] = Collections.singleton(VISIBILITY_MODIFIERS[i]); - } - - for (int i = 1; i < 8; i++) { - int attr = i << 3; - - Set set = new LinkedHashSet(); - if ((attr & ModifierFlags.STATIC_MASK) != 0) set.add(PsiModifier.STATIC); - if ((attr & ModifierFlags.FINAL_MASK) != 0) set.add(PsiModifier.FINAL); - if ((attr & (4 << 3)) != 0) set.add(PsiModifier.ABSTRACT); - - if (set.size() == 1) set = Collections.singleton(set.iterator().next()); - - SET_INSTANCES[i] = set; - - for (int k = 1; k < 4; k++) { - Set setWithModifier = new LinkedHashSet(); - setWithModifier.add(VISIBILITY_MODIFIERS[k]); - setWithModifier.addAll(set); - assert setWithModifier.size() > 1; - - SET_INSTANCES[(k << 3) + i] = setWithModifier; - } - } - } - - public static Set getModifierSet(int modifiers) { - assert (modifiers & ~(ModifierFlags.PUBLIC_MASK | ModifierFlags.PRIVATE_MASK | ModifierFlags.PROTECTED_MASK | - ModifierFlags.FINAL_MASK | ModifierFlags.ABSTRACT_MASK | ModifierFlags.STATIC_MASK)) == 0; - - int visibilityModifierIndex = MODIFIER_MAP[modifiers & 7]; - int index = ((modifiers >>> 3) & 3) + ((modifiers & ModifierFlags.ABSTRACT_MASK) >>> 8); - if (visibilityModifierIndex != -1) { - return SET_INSTANCES[index + (visibilityModifierIndex << 3)]; - } - - Set res = new LinkedHashSet(); - if ((modifiers & ModifierFlags.PUBLIC_MASK) != 0) res.add(PsiModifier.PUBLIC); - if ((modifiers & ModifierFlags.PRIVATE_MASK) != 0) res.add(PsiModifier.PRIVATE); - if ((modifiers & ModifierFlags.PROTECTED_MASK) != 0) res.add(PsiModifier.PROTECTED); - - res.addAll(SET_INSTANCES[index]); - - return res; - } - public static String intern(final CharTable table, final LighterASTNode node) { assert node instanceof LighterASTTokenNode; return table.intern(((LighterASTTokenNode)node).getText()).toString(); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java index 8ba604ac0ba6..1185d9fe9263 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java @@ -58,6 +58,10 @@ public class StubBuildingVisitor extends ClassVisitor { public static final String FLOAT_NEGATIVE_INF = "-1.0f / 0.0"; public static final String FLOAT_NAN = "0.0f / 0.0"; + @NonNls private static final String SYNTHETIC_CLASS_INIT_METHOD = ""; + @NonNls private static final String SYNTHETIC_INIT_METHOD = ""; + + private static final int ACC_DEFENDER = Opcodes.ACC_INTERFACE; // todo[r.sh] use right constant once ASM gets Java 8 support private final InnerClassSourceStrategy myInnersStrategy; private final StubElement myParent; @@ -65,8 +69,6 @@ public class StubBuildingVisitor extends ClassVisitor { private final T mySource; private PsiModifierListStub myModList; private PsiClassStub myResult; - @NonNls private static final String SYNTHETIC_CLINIT_METHOD = ""; - @NonNls private static final String SYNTHETIC_INIT_METHOD = ""; private JavaLexer myLexer; public StubBuildingVisitor(final T classSource, InnerClassSourceStrategy innersStrategy, final StubElement parent, final int access) { @@ -174,20 +176,25 @@ public class StubBuildingVisitor extends ClassVisitor { return convertedSuper; } + // for lexer, so need not to be precise private static LanguageLevel convertFromVersion(final int version) { - if (version == Opcodes.V1_1 || version == Opcodes.V1_2 || version == Opcodes.V1_3) { - return LanguageLevel.JDK_1_3; - } + switch (version) { + case Opcodes.V1_1: + case Opcodes.V1_2: + case Opcodes.V1_3: + return LanguageLevel.JDK_1_3; - if (version == Opcodes.V1_4) { - return LanguageLevel.JDK_1_4; - } + case Opcodes.V1_4: + return LanguageLevel.JDK_1_4; - if (version == Opcodes.V1_5 || version == Opcodes.V1_6) { - return LanguageLevel.JDK_1_5; - } + case Opcodes.V1_5: + case Opcodes.V1_6: + case Opcodes.V1_7: + return LanguageLevel.JDK_1_5; - return LanguageLevel.HIGHEST; + default: + return LanguageLevel.HIGHEST; + } } private static int packCommonFlags(final int access) { @@ -357,16 +364,17 @@ public class StubBuildingVisitor extends ClassVisitor { // However Scala compiler erroneously generates ACC_BRIDGE instead of ACC_SYNTHETIC flag for in-trait implementation delegation. See IDEA-78649 if (isSynthetic) return null; - if (SYNTHETIC_CLINIT_METHOD.equals(name)) return null; + if (SYNTHETIC_CLASS_INIT_METHOD.equals(name)) return null; boolean isDeprecated = (access & Opcodes.ACC_DEPRECATED) != 0; boolean isConstructor = SYNTHETIC_INIT_METHOD.equals(name); boolean isVarargs = (access & Opcodes.ACC_VARARGS) != 0; boolean isAnnotationMethod = myResult.isAnnotationType(); + boolean isDefender = (access & ACC_DEFENDER) != 0; if (!isConstructor && !isCorrectName(name)) return null; - final byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false); + final byte flags = PsiMethodStubImpl.packFlags(isConstructor, isAnnotationMethod, isVarargs, isDeprecated, false, isDefender); String canonicalMethodName = isConstructor ? myResult.getName() : name; final List args = new ArrayList(); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java index 966832d67bf6..562128f464a8 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaMethodElementType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -73,6 +73,7 @@ public abstract class JavaMethodElementType extends JavaStubElementType { boolean isConstructor(); boolean isVarArgs(); boolean isAnnotationMethod(); + boolean isDefender(); @Nullable String getDefaultValueText(); @NotNull TypeInfo getReturnTypeText(boolean doResolve); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiMethodStubImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiMethodStubImpl.java index 81420296c9dd..f076c8a273e0 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiMethodStubImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/impl/PsiMethodStubImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,6 +43,7 @@ public class PsiMethodStubImpl extends StubBase implements PsiMethodS private static final int ANNOTATION = 0x04; private static final int DEPRECATED = 0x08; private static final int DEPRECATED_ANNOTATION = 0x10; + private static final int DEFENDER = 0x20; public PsiMethodStubImpl(final StubElement parent, @@ -88,6 +89,11 @@ public class PsiMethodStubImpl extends StubBase implements PsiMethodS return isAnnotationMethod(myFlags); } + @Override + public boolean isDefender() { + return (myFlags & DEFENDER) != 0; + } + public static boolean isAnnotationMethod(final byte flags) { return (flags & ANNOTATION) != 0; } @@ -145,13 +151,19 @@ public class PsiMethodStubImpl extends StubBase implements PsiMethodS myDefaultValueText = StringRef.fromString(defaultValueText); } - public static byte packFlags(boolean isConstructor, boolean isAnnotationMethod, boolean isVarargs, boolean isDeprecated, boolean hasDeprecatedAnnotation) { + public static byte packFlags(boolean isConstructor, + boolean isAnnotationMethod, + boolean isVarargs, + boolean isDeprecated, + boolean hasDeprecatedAnnotation, + boolean isDefender) { byte flags = 0; if (isConstructor) flags |= CONSTRUCTOR; if (isAnnotationMethod) flags |= ANNOTATION; if (isVarargs) flags |= VARARGS; if (isDeprecated) flags |= DEPRECATED; if (hasDeprecatedAnnotation) flags |= DEPRECATED_ANNOTATION; + if (isDefender) flags |= DEFENDER; return flags; } @@ -179,6 +191,10 @@ public class PsiMethodStubImpl extends StubBase implements PsiMethodS builder.append(" default=").append(defaultValue); } + if (isDefender()) { + builder.append(" default {}"); + } + builder.append("]"); return builder.toString(); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java index b20b16b5c7d6..97cc4bed2543 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -37,7 +37,7 @@ import java.io.IOException; * @author max */ public class JavaFileElementType extends ILightStubFileElementType { - public static final int STUB_VERSION = 9; + public static final int STUB_VERSION = 10; public JavaFileElementType() { super("java.FILE", JavaLanguage.INSTANCE); diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiModifierListImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiModifierListImpl.java index 17b56ed2c050..f2ecc6853e3b 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiModifierListImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiModifierListImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,7 @@ import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.impl.source.tree.java.PsiAnnotationImpl; import com.intellij.psi.tree.IElementType; +import com.intellij.psi.util.PsiUtil; import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; @@ -151,7 +152,7 @@ public class PsiModifierListImpl extends JavaStubPsiElement return false; } if (type == JavaTokenType.ABSTRACT_KEYWORD) { - return true; + return !PsiUtil.isExtensionMethod((PsiMethod)parent); } } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java index 478b76d6eb8d..909d08a364b9 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ExtensionMethods.java @@ -13,9 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + class C { interface I { - void m1() { } - void m2() default { } + void m() default { } + } + + void test() { + new I(){}.m(); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/psi/JavaStubBuilderTest.java b/java/java-tests/testSrc/com/intellij/psi/JavaStubBuilderTest.java index 58528d12e401..9bd2f1abd2d4 100644 --- a/java/java-tests/testSrc/com/intellij/psi/JavaStubBuilderTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/JavaStubBuilderTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ import org.jetbrains.annotations.Nullable; import java.io.File; import java.security.SecureRandom; - public class JavaStubBuilderTest extends LightIdeaTestCase { private static final StubBuilder NEW_BUILDER = new JavaLightStubBuilder(); @@ -40,7 +39,7 @@ public class JavaStubBuilderTest extends LightIdeaTestCase { public void setUp() throws Exception { super.setUp(); doTest("@interface A { int i() default 42; }\n class C { void m(int p) throws E { } }", null); // warm up - LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7); + LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.HIGHEST); } public void testEmpty() { @@ -112,6 +111,10 @@ public class JavaStubBuilderTest extends LightIdeaTestCase { " public C() throws Exception { }\n" + " public abstract void m(final int i, int[] a1, int a2[], int[] a3[]);\n" + " private static int v2a(int... v) [] { return v; }\n" + + "}\n" + + "interface I {\n" + + " void m1();\n" + + " void m2() default { }\n" + "}", "PsiJavaFileStub []\n" + @@ -160,6 +163,21 @@ public class JavaStubBuilderTest extends LightIdeaTestCase { " PARAMETER_LIST:PsiParameterListStub\n" + " PARAMETER:PsiParameterStub[v:int...]\n" + " MODIFIER_LIST:PsiModifierListStub[mask=4096]\n" + + " THROWS_LIST:PsiRefListStub[THROWS_LIST:]\n" + + " CLASS:PsiClassStub[interface name=I fqn=I]\n" + + " MODIFIER_LIST:PsiModifierListStub[mask=5120]\n" + + " TYPE_PARAMETER_LIST:PsiTypeParameterListStub\n" + + " EXTENDS_LIST:PsiRefListStub[EXTENDS_LIST:]\n" + + " IMPLEMENTS_LIST:PsiRefListStub[IMPLEMENTS_LIST:]\n" + + " METHOD:PsiMethodStub[m1:void]\n" + + " MODIFIER_LIST:PsiModifierListStub[mask=1025]\n" + + " TYPE_PARAMETER_LIST:PsiTypeParameterListStub\n" + + " PARAMETER_LIST:PsiParameterListStub\n" + + " THROWS_LIST:PsiRefListStub[THROWS_LIST:]\n" + + " METHOD:PsiMethodStub[m2:void default {}]\n" + + " MODIFIER_LIST:PsiModifierListStub[mask=1]\n" + + " TYPE_PARAMETER_LIST:PsiTypeParameterListStub\n" + + " PARAMETER_LIST:PsiParameterListStub\n" + " THROWS_LIST:PsiRefListStub[THROWS_LIST:]\n"); } @@ -393,7 +411,7 @@ public class JavaStubBuilderTest extends LightIdeaTestCase { final String lightStr2 = DebugUtil.stubTreeToString(lighterTree2); if (tree != null) { System.out.println("light=" + t1 + "mks, heavy=" + t2 + "mks"); - if (!"".equals(tree)) { + if (!tree.isEmpty()) { assertEquals("light tree differs", tree, lightStr); assertEquals("light tree (2nd) differs", tree, lightStr2); } From 748284c1e28736cdc20b7d8b7ef55f1b913858e5 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Thu, 24 May 2012 19:32:15 +0400 Subject: [PATCH 44/45] Do not pre-load messages --- .../impl/analysis/GenericsHighlightUtil.java | 2 +- .../impl/analysis/HighlightClassUtil.java | 26 +++++++------------ .../daemon/impl/analysis/HighlightUtil.java | 3 +-- 3 files changed, 12 insertions(+), 19 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java index 3a9857459cdc..1626942bd07b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java @@ -390,7 +390,7 @@ public class GenericsHighlightUtil { if (extendFrom == null) return null; HighlightInfo errorResult = null; if (!extendFrom.isInterface() && referenceElements.length != 0 && element != referenceElements[0]) { - final String description = HighlightClassUtil.INTERFACE_EXPECTED; + String description = JavaErrorMessages.message("interface.expected"); errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, element, description); PsiClassType type = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory().createType(extendFrom, resolveResult.getSubstitutor()); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index 9cf235c20dfe..6436215ef340 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -60,9 +60,6 @@ import java.util.HashSet; import java.util.List; public class HighlightClassUtil { - public static final String INTERFACE_EXPECTED = JavaErrorMessages.message("interface.expected"); - public static final String NO_INTERFACE_EXPECTED = JavaErrorMessages.message("no.interface.expected"); - private static final String STATIC_DECLARATION_IN_INNER_CLASS = JavaErrorMessages.message("static.declaration.in.inner.class"); private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance(); /** @@ -280,9 +277,8 @@ public class HighlightClassUtil { if (PsiUtil.isCompileTimeConstant(field)) { return null; } - HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, - keyword, - STATIC_DECLARATION_IN_INNER_CLASS); + String message = JavaErrorMessages.message("static.declaration.in.inner.class"); + HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, keyword, message); IntentionAction fix1 = QUICK_FIX_FACTORY.createModifierListFix(field, PsiModifier.STATIC, false, false); QuickFixAction.registerQuickFixAction(errorResult, fix1); IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(field.getContainingClass(), PsiModifier.STATIC, true, false); @@ -297,9 +293,8 @@ public class HighlightClassUtil { } PsiMethod method = (PsiMethod)keyword.getParent().getParent(); if (PsiUtilCore.hasErrorElementChild(method)) return null; - HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, - keyword, - STATIC_DECLARATION_IN_INNER_CLASS); + String message = JavaErrorMessages.message("static.declaration.in.inner.class"); + HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, keyword, message); IntentionAction fix1 = QUICK_FIX_FACTORY.createModifierListFix(method, PsiModifier.STATIC, false, false); QuickFixAction.registerQuickFixAction(errorResult, fix1); IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix((PsiClass)keyword.getParent().getParent().getParent(), PsiModifier.STATIC, true, false); @@ -314,9 +309,8 @@ public class HighlightClassUtil { } PsiClassInitializer initializer = (PsiClassInitializer)keyword.getParent().getParent(); if (PsiUtilCore.hasErrorElementChild(initializer)) return null; - HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, - keyword, - STATIC_DECLARATION_IN_INNER_CLASS); + String message = JavaErrorMessages.message("static.declaration.in.inner.class"); + HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, keyword, message); IntentionAction fix1 = QUICK_FIX_FACTORY.createModifierListFix(initializer, PsiModifier.STATIC, false, false); QuickFixAction.registerQuickFixAction(errorResult, fix1); PsiClass owner = (PsiClass)keyword.getParent().getParent().getParent(); @@ -364,7 +358,8 @@ public class HighlightClassUtil { if (textRange == null) { textRange = HighlightNamesUtil.getClassDeclarationTextRange(aClass); } - HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, textRange, STATIC_DECLARATION_IN_INNER_CLASS); + String message = JavaErrorMessages.message("static.declaration.in.inner.class"); + HighlightInfo errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, textRange, message); if (context != keyword) { IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(aClass, PsiModifier.STATIC, false, false); QuickFixAction.registerQuickFixAction(errorResult, fix); @@ -425,9 +420,8 @@ public class HighlightClassUtil { HighlightInfo errorResult = null; PsiClass extendFrom = (PsiClass)resolveResult.getElement(); if (extendFrom.isInterface() != mustBeInterface) { - errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, - ref, - mustBeInterface ? INTERFACE_EXPECTED : NO_INTERFACE_EXPECTED); + String message = JavaErrorMessages.message(mustBeInterface ? "interface.expected" : "no.interface.expected"); + errorResult = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, ref, message); PsiClassType type = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory().createType(ref); QuickFixAction.registerQuickFixAction(errorResult, new ChangeExtendsToImplementsFix(aClass, type)); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java index 9599336f1a87..ac3a5df3c7ad 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java @@ -1328,14 +1328,13 @@ public class HighlightUtil { } if (aClass == null) return null; if (qualifier != null && aClass.isInterface()) { - return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, qualifier, HighlightClassUtil.NO_INTERFACE_EXPECTED); + return HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, qualifier, JavaErrorMessages.message("no.interface.expected")); } if (!HighlightClassUtil.hasEnclosingInstanceInScope(aClass, expr, false)) { return HighlightClassUtil.reportIllegalEnclosingUsage(expr, null, aClass, expr); } return null; - } static String buildProblemWithStaticDescription(PsiElement refElement) { From 7a6e19486abfe88abc5d2b416a7798b4efe0c0fb Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Thu, 24 May 2012 21:36:00 +0400 Subject: [PATCH 45/45] Fix error text --- .../impl/analysis/HighlightClassUtil.java | 5 +-- .../advHighlighting/MethodCalls.java | 31 +++++++++++++------ 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java index 6436215ef340..535aee6ea37b 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java @@ -845,8 +845,9 @@ public class HighlightClassUtil { } PsiModifierListOwner staticParent = PsiUtil.getEnclosingStaticElement(place, outerClass); if (staticParent != null) { - String description = JavaErrorMessages.message("cannot.be.referenced.from.static.context", - outerClass == null ? "" : HighlightUtil.formatClass(outerClass) + "." + PsiKeyword.THIS); + String element = outerClass == null ? "" : HighlightUtil.formatClass(outerClass) + "." + + (place instanceof PsiSuperExpression ? PsiKeyword.SUPER : PsiKeyword.THIS); + String description = JavaErrorMessages.message("cannot.be.referenced.from.static.context", element); HighlightInfo highlightInfo = HighlightInfo.createHighlightInfo(HighlightInfoType.ERROR, elementToHighlight, description); // make context not static or referenced class static IntentionAction fix = QUICK_FIX_FACTORY.createModifierListFix(staticParent, PsiModifier.STATIC, false, false); diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MethodCalls.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MethodCalls.java index 74175a7a882c..183e8d01211d 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MethodCalls.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MethodCalls.java @@ -1,3 +1,19 @@ +/* + * Copyright 2000-2012 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // illegal method calls class A { @@ -48,14 +64,12 @@ class CX { class c { - c() { + c() {} - } class inner { class ininner {} } - static void f() { new inner(); } @@ -88,21 +102,20 @@ class DCC { } public DCC(int i, int z) { - DCC(i); + DCC(i); } void f() { DCC(1); new DCC(1); } - { - java.toString(); - } - + { + java.toString(); + } } class ThisExpression { static String foo() { System.out.println(this); - return this.toString(); + return super.toString(); } }