From e261b412a401c9ff8b1027375d837a7826e3de1d Mon Sep 17 00:00:00 2001 From: Alexander Kass Date: Wed, 20 Jul 2016 13:04:24 +0300 Subject: [PATCH 01/67] UiUtils::setEnabled DBE-2858 DBE-2894 --- platform/util/src/com/intellij/util/ui/UIUtil.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index ec24c55d3434c..e56690493597e 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -634,12 +634,12 @@ public static void setEnabled(Component component, boolean enabled, boolean recu public static void setEnabled(Component component, boolean enabled, boolean recursively, final boolean visibleOnly) { JBIterable all = recursively ? uiTraverser(component).expandAndFilter( - visibleOnly ? Conditions.alwaysTrue() : new Condition() { + visibleOnly ? new Condition() { @Override public boolean value(Component c) { return c.isVisible(); } - }).traverse() : JBIterable.of(component); + } : Conditions.alwaysTrue()).traverse() : JBIterable.of(component); Color fg = enabled ? getLabelForeground() : getLabelDisabledForeground(); for (Component c : all) { c.setEnabled(enabled); From 3773948686772243af1c864327a194a924a4dad4 Mon Sep 17 00:00:00 2001 From: Pavel Dolgov Date: Tue, 19 Jul 2016 19:10:32 +0300 Subject: [PATCH 02/67] Java inspection: Added a fix for single-value annotations where the annotation doesn't have a 'value()' method and therefore "Expand Annotation to Normal Form" fix couldn't be applied (IDEA-158456, IDEA-157727) --- .../intention/QuickFixFactory.java | 3 + .../analysis/AnnotationsHighlightUtil.java | 7 +- .../intention/EmptyQuickFixFactory.java | 6 + .../AddAnnotationAttributeNameFix.java | 154 ++++++++++++++++++ .../CreateAnnotationMethodFromUsageFix.java | 2 +- .../impl/config/QuickFixFactoryImpl.java | 6 + .../afterMatchingArrayItem.java | 10 ++ .../afterMatchingType.java | 11 ++ .../afterMultiAttr.java | 11 ++ .../beforeMatchingArrayItem.java | 10 ++ .../beforeMatchingType.java | 11 ++ .../beforeMultiAttr.java | 11 ++ .../beforeMultiAttrUsedName.java | 11 ++ .../beforeNonmatchingArrayItem.java | 10 ++ .../beforeNonmatchingType.java | 10 ++ .../AddAnnotationAttributeNameTest.java | 38 +++++ 16 files changed, 309 insertions(+), 2 deletions(-) create mode 100644 java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingArrayItem.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingType.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMultiAttr.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingArrayItem.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingType.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttr.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttrUsedName.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingArrayItem.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingType.java create mode 100644 java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AddAnnotationAttributeNameTest.java diff --git a/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java b/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java index 56c6cf8ac3e96..a72d087deb767 100644 --- a/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java +++ b/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java @@ -273,4 +273,7 @@ public abstract IntentionAction createAddMissingRequiredAnnotationParametersFix( public abstract IntentionAction createWrapWithOptionalFix(@Nullable PsiType type, @NotNull PsiExpression expression); public abstract IntentionAction createNotIterableForEachLoopFix(PsiExpression expression); + + @NotNull + public abstract List createAddAnnotationAttributeNameFixes(PsiNameValuePair pair); } \ No newline at end of file diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java index 2e8953bb4a38b..4cfa72706ebe4 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java @@ -72,7 +72,12 @@ static HighlightInfo checkNameValuePair(PsiNameValuePair pair) { else { String description = JavaErrorMessages.message("annotation.missing.method", ref.getCanonicalText()); PsiElement element = ref.getElement(); - return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create(); + final HighlightInfo highlightInfo = + HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(element).descriptionAndTooltip(description).create(); + for (IntentionAction action : QuickFixFactory.getInstance().createAddAnnotationAttributeNameFixes(pair)) { + QuickFixAction.registerQuickFixAction(highlightInfo, action); + } + return highlightInfo; } } else { diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/intention/EmptyQuickFixFactory.java b/java/java-analysis-impl/src/com/intellij/codeInsight/intention/EmptyQuickFixFactory.java index 833f6af6a2cc1..d00863a79da82 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/intention/EmptyQuickFixFactory.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/intention/EmptyQuickFixFactory.java @@ -631,4 +631,10 @@ public IntentionAction createWrapWithOptionalFix(@Nullable PsiType type, @NotNul public IntentionAction createNotIterableForEachLoopFix(PsiExpression expression) { return QuickFixes.EMPTY_FIX; } + + @NotNull + @Override + public List createAddAnnotationAttributeNameFixes(PsiNameValuePair pair) { + return Collections.emptyList(); + } } diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java new file mode 100644 index 0000000000000..1fee9fc5c6eed --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java @@ -0,0 +1,154 @@ +/* + * Copyright 2000-2016 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.daemon.impl.quickfix; + +import com.intellij.codeInsight.intention.IntentionAction; +import com.intellij.codeInspection.LocalQuickFixAndIntentionActionOnPsiElement; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.Nls; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; +import java.util.stream.Collectors; + +/** + * @author Pavel.Dolgov + */ +public class AddAnnotationAttributeNameFix extends LocalQuickFixAndIntentionActionOnPsiElement { + private final String myName; + + public AddAnnotationAttributeNameFix(PsiNameValuePair pair, String name) { + super(pair); + myName = name; + } + + @Nls + @NotNull + @Override + public String getText() { + return "Add '" + myName + "='"; + } + + @Nls + @NotNull + @Override + public String getFamilyName() { + return "Add annotation attribute name"; + } + + @Override + public void invoke(@NotNull Project project, + @NotNull PsiFile file, + @Nullable("is null when called from inspection") Editor editor, + @NotNull PsiElement startElement, + @NotNull PsiElement endElement) { + doFix((PsiNameValuePair)startElement, myName); + } + + @Override + public boolean isAvailable(@NotNull Project project, + @NotNull PsiFile file, + @NotNull PsiElement startElement, + @NotNull PsiElement endElement) { + return super.isAvailable(project, file, startElement, endElement) && startElement instanceof PsiNameValuePair; + } + + @NotNull + public static List createFixes(@NotNull PsiNameValuePair pair) { + final PsiAnnotationMemberValue value = pair.getValue(); + if (value == null || pair.getName() != null) { + return Collections.emptyList(); + } + + final Collection methodNames = getAvailableAnnotationMethodNames(pair); + return ContainerUtil.map2List(methodNames, name -> new AddAnnotationAttributeNameFix(pair, name)); + } + + public static void doFix(@NotNull PsiNameValuePair annotationParameter, @NotNull String name) { + final String text = buildReplacementText(annotationParameter, name); + final PsiElementFactory factory = JavaPsiFacade.getElementFactory(annotationParameter.getProject()); + final PsiAnnotation newAnnotation = factory.createAnnotationFromText("@A(" + text + " )", annotationParameter); + annotationParameter.replace(newAnnotation.getParameterList().getAttributes()[0]); + } + + private static String buildReplacementText(@NotNull PsiNameValuePair annotationParameter, @NotNull String name) { + final PsiAnnotationMemberValue value = annotationParameter.getValue(); + return value != null ? name + "=" + value.getText() : name + "="; + } + + private static boolean isCompatibleReturnType(@Nullable PsiType expectedType, @Nullable PsiType valueType) { + if (expectedType == null || valueType == null || expectedType.isAssignableFrom(valueType)) { + return true; + } + if (expectedType instanceof PsiArrayType) { + final PsiType componentType = ((PsiArrayType)expectedType).getComponentType(); + return componentType.isAssignableFrom(valueType); + } + return false; + } + + @NotNull + private static Collection getAvailableAnnotationMethodNames(@NotNull PsiNameValuePair pair) { + final PsiAnnotationMemberValue value = pair.getValue(); + if (value != null && pair.getName() == null) { + final PsiElement parent = pair.getParent(); + if ((parent instanceof PsiAnnotationParameterList)) { + final PsiAnnotationParameterList parameterList = (PsiAnnotationParameterList)parent; + final PsiClass annotationClass = getAnnotationClass(parameterList); + + if (annotationClass != null) { + final Set usedNames = Arrays.stream(parameterList.getAttributes()) + .map(PsiNameValuePair::getName) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + + final Collection availableMethods = Arrays.stream(annotationClass.getMethods()) + .filter(PsiAnnotationMethod.class::isInstance) + .filter(psiMethod -> !usedNames.contains(psiMethod.getName())) + .collect(Collectors.toList()); + + if (!availableMethods.isEmpty()) { + final PsiType valueType = CreateAnnotationMethodFromUsageFix.getAnnotationValueType(value); + return availableMethods.stream() + .filter(psiMethod -> isCompatibleReturnType(psiMethod.getReturnType(), valueType)) + .map(PsiMethod::getName) + .collect(Collectors.toSet()); + } + } + } + } + return Collections.emptyList(); + } + + @Nullable + private static PsiClass getAnnotationClass(@NotNull PsiAnnotationParameterList parameterList) { + final PsiElement parent = parameterList.getParent(); + if (parent instanceof PsiAnnotation) { + final PsiJavaCodeReferenceElement reference = ((PsiAnnotation)parent).getNameReferenceElement(); + if (reference != null) { + final PsiElement resolved = reference.resolve(); + if (resolved instanceof PsiClass && ((PsiClass)resolved).isAnnotationType()) { + return (PsiClass)resolved; + } + } + } + return null; + } +} diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateAnnotationMethodFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateAnnotationMethodFromUsageFix.java index 5027752e47d0c..1968389695372 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateAnnotationMethodFromUsageFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateAnnotationMethodFromUsageFix.java @@ -88,7 +88,7 @@ protected void invokeImpl(final PsiClass targetClass) { } @Nullable - private static PsiType getAnnotationValueType(PsiAnnotationMemberValue value) { + public static PsiType getAnnotationValueType(PsiAnnotationMemberValue value) { PsiType type = null; if (value instanceof PsiExpression) { type = ((PsiExpression)value).getType(); diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java index ed23a87aab1c7..3883be2ee542f 100644 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java +++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java @@ -790,6 +790,12 @@ public IntentionAction createNotIterableForEachLoopFix(PsiExpression expression) return null; } + @NotNull + @Override + public List createAddAnnotationAttributeNameFixes(PsiNameValuePair pair) { + return AddAnnotationAttributeNameFix.createFixes(pair); + } + private static boolean timeToOptimizeImports(@NotNull PsiFile file) { if (!CodeInsightSettings.getInstance().OPTIMIZE_IMPORTS_ON_THE_FLY) return false; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingArrayItem.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingArrayItem.java new file mode 100644 index 0000000000000..8e156f69aae87 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingArrayItem.java @@ -0,0 +1,10 @@ +// "Add 'type='" "true" +class T { + @interface A { + String[] type(); + } + + @A(type = "t") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingType.java new file mode 100644 index 0000000000000..e00f8239502d6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMatchingType.java @@ -0,0 +1,11 @@ +// "Add 'name='" "true" +class T { + @interface A { + int size(); + String name(); + } + + @A(name = "a") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMultiAttr.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMultiAttr.java new file mode 100644 index 0000000000000..2727d0cf73efa --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/afterMultiAttr.java @@ -0,0 +1,11 @@ +// "Add 'type='" "true" +class T { + @interface A { + String name(); + String type(); + } + + @A(type = "a", name = "b") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingArrayItem.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingArrayItem.java new file mode 100644 index 0000000000000..1e4ea779d4409 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingArrayItem.java @@ -0,0 +1,10 @@ +// "Add 'type='" "true" +class T { + @interface A { + String[] type(); + } + + @A("t") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingType.java new file mode 100644 index 0000000000000..889a515247c78 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMatchingType.java @@ -0,0 +1,11 @@ +// "Add 'name='" "true" +class T { + @interface A { + int size(); + String name(); + } + + @A("a") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttr.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttr.java new file mode 100644 index 0000000000000..7ffb63480e730 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttr.java @@ -0,0 +1,11 @@ +// "Add 'type='" "true" +class T { + @interface A { + String name(); + String type(); + } + + @A("a", name = "b") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttrUsedName.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttrUsedName.java new file mode 100644 index 0000000000000..0092bb77845ab --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeMultiAttrUsedName.java @@ -0,0 +1,11 @@ +// "Add 'name='" "false" +class T { + @interface A { + String name(); + String type(); + } + + @A("a", name = "b") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingArrayItem.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingArrayItem.java new file mode 100644 index 0000000000000..3aeaf59688ece --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingArrayItem.java @@ -0,0 +1,10 @@ +// "Add 'type='" "false" +class T { + @interface A { + String[] type(); + } + + @A(42) + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingType.java new file mode 100644 index 0000000000000..58ff1a3c1de38 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName/beforeNonmatchingType.java @@ -0,0 +1,10 @@ +// "Add 'size='" "false" +class T { + @interface A { + int size(); + } + + @A("a") + void foo() { + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AddAnnotationAttributeNameTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AddAnnotationAttributeNameTest.java new file mode 100644 index 0000000000000..f2f27d29cb7cb --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/AddAnnotationAttributeNameTest.java @@ -0,0 +1,38 @@ +/* + * Copyright 2000-2016 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.daemon.quickFix; + +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.testFramework.IdeaTestUtil; + +/** + * @author Pavel.Dolgov + */ +public class AddAnnotationAttributeNameTest extends LightQuickFixParameterizedTestCase { + public void test() throws Exception { + doAllTests(); + } + + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/addAnnotationAttributeName"; + } + + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk18(); + } +} From 40a402b999712801bf2758f1da8488d46ebde94b Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 20 Jul 2016 13:51:19 +0300 Subject: [PATCH 03/67] IDEA-158759 'Run' toolwindow in 'Windowed mode' isn't activated when a new run configuration is started --- .../openapi/wm/impl/ToolWindowManagerImpl.java | 6 +++++- .../util/src/com/intellij/util/ui/UIUtil.java | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java index 89a2180137334..beb77c8eda0a4 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowManagerImpl.java @@ -1017,7 +1017,11 @@ private static boolean isStackEnabled() { */ private void showToolWindowImpl(@NotNull String id, final boolean dirtyMode, @NotNull List commandsList) { final WindowInfoImpl toBeShownInfo = getInfo(id); - if (toBeShownInfo.isVisible() || !getToolWindow(id).isAvailable()) { + ToolWindow window = getToolWindow(id); + if (window != null && toBeShownInfo.isWindowed()) { + UIUtil.toFront(UIUtil.getWindow(window.getComponent())); + } + if (toBeShownInfo.isVisible() || window == null || !window.isAvailable()) { return; } diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java index e56690493597e..4a6f319904888 100644 --- a/platform/util/src/com/intellij/util/ui/UIUtil.java +++ b/platform/util/src/com/intellij/util/ui/UIUtil.java @@ -3598,6 +3598,22 @@ public static Window getWindow(Component component) { return component instanceof Window ? (Window)component : SwingUtilities.getWindowAncestor(component); } + /** + * Places the specified window at the top of the stacking order and shows it in front of any other windows. + * If the window is iconified it will be shown anyway. + * + * @param window the window to activate + */ + public static void toFront(Window window) { + if (window instanceof Frame) { + Frame frame = (Frame)window; + frame.setState(Frame.NORMAL); + } + if (window != null) { + window.toFront(); + } + } + public static Image getDebugImage(Component component) { BufferedImage image = createImage(component.getWidth(), component.getHeight(), BufferedImage.TYPE_INT_ARGB); Graphics2D graphics = image.createGraphics(); From e7bc87cd1ad8571ac9686b6c87fac8eddaa5dc4d Mon Sep 17 00:00:00 2001 From: nik Date: Wed, 20 Jul 2016 13:51:32 +0300 Subject: [PATCH 04/67] build scripts redesign: build cross-platform distribution and copy appletviewer.policy for IDEA only --- .../conf/ideaCE/common/bin}/appletviewer.policy | 0 .../build/IdeaCommunityProperties.groovy | 4 ++++ .../intellij/build/ProductProperties.groovy | 5 +++++ .../intellij/build/impl/BuildTasksImpl.groovy | 16 +++++++++------- 4 files changed, 18 insertions(+), 7 deletions(-) rename {bin => build/conf/ideaCE/common/bin}/appletviewer.policy (100%) diff --git a/bin/appletviewer.policy b/build/conf/ideaCE/common/bin/appletviewer.policy similarity index 100% rename from bin/appletviewer.policy rename to build/conf/ideaCE/common/bin/appletviewer.policy diff --git a/build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.groovy b/build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.groovy index d8706727fac38..080e899b92fcc 100644 --- a/build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.groovy +++ b/build/groovy/org/jetbrains/intellij/build/IdeaCommunityProperties.groovy @@ -26,6 +26,7 @@ class IdeaCommunityProperties extends ProductProperties { applicationInfoModule = "community-resources" additionalIDEPropertiesFilePaths = ["$home/build/conf/ideaCE.properties"] toolsJarRequired = true + buildCrossPlatformDistribution = true } @Override @@ -39,6 +40,9 @@ class IdeaCommunityProperties extends ProductProperties { fileset(file: "$buildContext.paths.communityHome/LICENSE.txt") fileset(file: "$buildContext.paths.communityHome/NOTICE.txt") } + buildContext.ant.copy(todir: "$targetDirectory/bin") { + fileset(dir: "$buildContext.paths.communityHome/build/conf/ideaCE/common/bin") + } } @Override diff --git a/build/groovy/org/jetbrains/intellij/build/ProductProperties.groovy b/build/groovy/org/jetbrains/intellij/build/ProductProperties.groovy index 56d89a174c07a..0e282ab003553 100644 --- a/build/groovy/org/jetbrains/intellij/build/ProductProperties.groovy +++ b/build/groovy/org/jetbrains/intellij/build/ProductProperties.groovy @@ -65,6 +65,11 @@ public abstract class ProductProperties { */ abstract String systemSelector(ApplicationInfoProperties applicationInfo) + /** + * If {@code true} cross-platform ZIP archive containing binaries for all OS will be built + */ + boolean buildCrossPlatformDistribution = false + /** * Paths to properties files the content of which should be appended to idea.properties file */ diff --git a/build/groovy/org/jetbrains/intellij/build/impl/BuildTasksImpl.groovy b/build/groovy/org/jetbrains/intellij/build/impl/BuildTasksImpl.groovy index f805b981d6f2f..9423700566422 100644 --- a/build/groovy/org/jetbrains/intellij/build/impl/BuildTasksImpl.groovy +++ b/build/groovy/org/jetbrains/intellij/build/impl/BuildTasksImpl.groovy @@ -231,14 +231,16 @@ idea.fatal.error.notification=disabled } } - if (windowsBuilder != null && linuxBuilder != null && macBuilder != null) { - buildContext.executeStep("Build cross-platform distribution", BuildOptions.CROSS_PLATFORM_DISTRIBUTION_STEP) { - def crossPlatformBuilder = new CrossPlatformDistributionBuilder(buildContext) - crossPlatformBuilder.buildCrossPlatformZip(windowsBuilder.winDistPath, linuxBuilder.unixDistPath, macBuilder.macDistPath) + if (buildContext.productProperties.buildCrossPlatformDistribution) { + if (windowsBuilder != null && linuxBuilder != null && macBuilder != null) { + buildContext.executeStep("Build cross-platform distribution", BuildOptions.CROSS_PLATFORM_DISTRIBUTION_STEP) { + def crossPlatformBuilder = new CrossPlatformDistributionBuilder(buildContext) + crossPlatformBuilder.buildCrossPlatformZip(windowsBuilder.winDistPath, linuxBuilder.unixDistPath, macBuilder.macDistPath) + } + } + else { + buildContext.messages.info("Skipping building cross-platform distribution because some OS-specific distributions were skipped") } - } - else { - buildContext.messages.info("Skipping building cross-platform distribution because some OS-specific distributions was skipeed") } } From b569e9f837bfbe25eadc8e4c958e617a8c6603ef Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Tue, 19 Jul 2016 19:21:57 +0300 Subject: [PATCH 05/67] Set modality state of the newly created daemon indicator to the current modality state. So that the editor in modal dialog can update its highlighters before close. --- .../intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java index 9a5f9f01b017a..de07a39a839b9 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java @@ -897,6 +897,7 @@ public void stopIfRunning() { myProject.getMessageBus().syncPublisher(DAEMON_EVENT_TOPIC).daemonFinished(); } }; + progress.setModalityProgress(null); progress.start(); myUpdateProgress = progress; return progress; From 8b87739f9c4394442633fbb5b0af017e6ad2f2c1 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 20 Jul 2016 14:14:17 +0300 Subject: [PATCH 06/67] ignore PCE thrown from document commit callback --- .../src/com/intellij/psi/impl/PsiDocumentManagerBase.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java index 4a54b8d643d6c..f745bb7bafee4 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java @@ -36,6 +36,7 @@ import com.intellij.openapi.editor.impl.FrozenDocument; import com.intellij.openapi.editor.impl.event.RetargetRangeMarkers; import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.FileIndexFacade; import com.intellij.openapi.util.*; @@ -618,6 +619,10 @@ private void runAfterCommitActions(@NotNull Document document) { try { action.run(); } + catch (ProcessCanceledException e) { + // some actions are that crazy to use PCE for their own control flow. + // swallow and ignore to not disrupt completely unrelated control flow. + } catch (Throwable e) { LOG.error("During running " + action, e); } From b9e8f2856f53cb79c71b569ee303a744c764d257 Mon Sep 17 00:00:00 2001 From: Alexander Zolotov Date: Wed, 20 Jul 2016 14:09:07 +0300 Subject: [PATCH 07/67] TestSourcesFilter: update after review --- .../com/intellij/util/xml/DomJavaUtil.java | 8 ++---- .../values/ClassValueConverter.java | 6 ++-- .../BackwardDependenciesBuilder.java | 10 ++----- .../file/impl/ResolveScopeManagerImpl.java | 2 +- .../ide/util/PlatformPackageUtil.java | 14 ++++------ .../com/intellij/openapi/roots/FileIndex.java | 9 ++++-- .../openapi/roots/TestSourcesFilter.java | 2 +- .../coverage/JavaCoverageAnnotator.java | 25 ++++++++++++----- .../intellij/coverage/JavaCoverageEngine.java | 28 ++++++++++++++----- .../util/xml/AbstractConvertContext.java | 9 ++---- 10 files changed, 66 insertions(+), 47 deletions(-) diff --git a/java/openapi/src/com/intellij/util/xml/DomJavaUtil.java b/java/openapi/src/com/intellij/util/xml/DomJavaUtil.java index f3e2baca83d66..ea773b2a64e4f 100644 --- a/java/openapi/src/com/intellij/util/xml/DomJavaUtil.java +++ b/java/openapi/src/com/intellij/util/xml/DomJavaUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -16,8 +16,7 @@ package com.intellij.util.xml; import com.intellij.openapi.module.Module; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.JavaPsiFacade; import com.intellij.psi.PsiClass; @@ -89,7 +88,6 @@ private static GlobalSearchScope calcScope(@NotNull PsiFile file, @Nullable Modu return GlobalSearchScope.moduleRuntimeScope(module, true); } - ProjectFileIndex fileIndex = ProjectRootManager.getInstance(file.getProject()).getFileIndex(); - return module.getModuleRuntimeScope(fileIndex.isInTestSourceContent(virtualFile)); + return module.getModuleRuntimeScope(TestSourcesFilter.isTestSources(virtualFile, file.getProject())); } } diff --git a/java/openapi/src/com/intellij/util/xml/converters/values/ClassValueConverter.java b/java/openapi/src/com/intellij/util/xml/converters/values/ClassValueConverter.java index d3a70c761f752..360ccfcc230f7 100644 --- a/java/openapi/src/com/intellij/util/xml/converters/values/ClassValueConverter.java +++ b/java/openapi/src/com/intellij/util/xml/converters/values/ClassValueConverter.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -19,7 +19,7 @@ import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiElement; @@ -62,7 +62,7 @@ public static GlobalSearchScope getScope(Project project, @Nullable Module modul if (file == null) { return ProjectScope.getAllScope(project); } - final boolean inTests = ProjectRootManager.getInstance(project).getFileIndex().isInTestSourceContent(file); + final boolean inTests = TestSourcesFilter.isTestSources(file, project); return module.getModuleRuntimeScope(inTests); } diff --git a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java index 3f72c3fdc55f2..fce508bbc608b 100644 --- a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java +++ b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -23,14 +23,11 @@ import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.util.Computable; -import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; -import com.intellij.util.Processor; import org.jetbrains.annotations.Nullable; import java.util.HashSet; @@ -88,9 +85,8 @@ public void analyze() { try { final int fileCount = getScope().getFileCount(); final boolean includeTestSource = getScope().isIncludeTestSource(); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(getProject()).getFileIndex(); getScope().accept(virtualFile -> { - if (!includeTestSource && fileIndex.isInTestSourceContent(virtualFile)) { + if (!includeTestSource && TestSourcesFilter.isTestSources(virtualFile, getProject())) { return true; } ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java b/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java index b99a71e5b44a7..a6d381a73da90 100644 --- a/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java +++ b/platform/indexing-impl/src/com/intellij/psi/impl/file/impl/ResolveScopeManagerImpl.java @@ -185,7 +185,7 @@ public GlobalSearchScope getUseScope(@NotNull PsiElement element) { return containingFile == null || virtualFile.isDirectory() || result.contains(virtualFile) ? result : GlobalSearchScope.fileScope(containingFile).uniteWith(result); } - boolean isTest = projectFileIndex.isInTestSourceContent(vDirectory); + boolean isTest = TestSourcesFilter.isTestSources(vDirectory, myProject); GlobalSearchScope scope = isTest ? GlobalSearchScope.moduleTestsWithDependentsScope(module) : GlobalSearchScope.moduleWithDependentsScope(module); diff --git a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java index 696e4e711fa02..c07bc47fc86ac 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -22,13 +22,12 @@ import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectBundle; import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.roots.impl.DirectoryIndex; import com.intellij.openapi.roots.ui.configuration.CommonContentEntriesEditor; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.ui.Messages; -import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; @@ -36,7 +35,7 @@ import com.intellij.psi.PsiManager; import com.intellij.psi.impl.source.resolve.FileContextUtil; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.GlobalSearchScopes; +import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.util.*; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; @@ -181,15 +180,14 @@ public static GlobalSearchScope adjustScope(PsiDirectory baseDir, boolean skipSourceDirsForBaseTestDirectory, boolean skipTestDirsForBaseSourceDirectory) { if (baseDir != null) { - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(baseDir.getProject()).getFileIndex(); - if (fileIndex.isInTestSourceContent(baseDir.getVirtualFile())) { + if (TestSourcesFilter.isTestSources(baseDir.getVirtualFile(), baseDir.getProject())) { if (skipSourceDirsForBaseTestDirectory) { - return scope.intersectWith(GlobalSearchScopes.projectTestScope(baseDir.getProject())); + return scope.intersectWith(GlobalSearchScopesCore.projectTestScope(baseDir.getProject())); } } else { if (skipTestDirsForBaseSourceDirectory) { - return scope.intersectWith(GlobalSearchScopes.projectProductionScope(baseDir.getProject())); + return scope.intersectWith(GlobalSearchScopesCore.projectProductionScope(baseDir.getProject())); } } } diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/FileIndex.java b/platform/projectModel-api/src/com/intellij/openapi/roots/FileIndex.java index a53a4bfbc7415..d2182f033471f 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/FileIndex.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/FileIndex.java @@ -78,11 +78,16 @@ public interface FileIndex { /** * Returns true if fileOrDir is a file or directory from the test content source + *

+ * Use this method when you really need to check whether the file is under test roots according to project configuration. + *

+ * If you want to determine whether file should be considered as test (e.g. for implementing SearchScope) + * you'd better use {@link TestSourcesFilter#isTestSources(VirtualFile, Project)} instead + * which includes {@link ProjectFileIndex#isInTestSourceContent(VirtualFile)} invocation. * - * @see TestSourcesFilter#isTestSources(VirtualFile, Project) - * * @param fileOrDir the file or directory to check. * @return true if the file or directory belongs to a test source root, false otherwise. + * @see TestSourcesFilter#isTestSources(VirtualFile, Project) */ boolean isInTestSourceContent(@NotNull VirtualFile fileOrDir); diff --git a/platform/projectModel-api/src/com/intellij/openapi/roots/TestSourcesFilter.java b/platform/projectModel-api/src/com/intellij/openapi/roots/TestSourcesFilter.java index be20208355334..2a5ce8c2db919 100644 --- a/platform/projectModel-api/src/com/intellij/openapi/roots/TestSourcesFilter.java +++ b/platform/projectModel-api/src/com/intellij/openapi/roots/TestSourcesFilter.java @@ -21,7 +21,7 @@ import org.jetbrains.annotations.NotNull; /** - * Implementations of this extension point can tell IDE whether some particular file is a test file despite project roots configuration. + * Implementations of this extension point can tell IDE whether some particular file is a test file. *

* By default, IntelliJ Platform considers files as tests only if they are located under test * sources root {@link FileIndex#isInTestSourceContent(VirtualFile)}. diff --git a/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java b/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java index d3db8c84c6df3..0abed78a1fd87 100644 --- a/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java +++ b/plugins/coverage/src/com/intellij/coverage/JavaCoverageAnnotator.java @@ -1,11 +1,25 @@ +/* + * Copyright 2000-2016 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.coverage; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; @@ -47,16 +61,13 @@ public String getDirCoverageInformationString(@NotNull final PsiDirectory direct final PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(directory); if (psiPackage == null) return null; - final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(directory.getProject()).getFileIndex(); final VirtualFile virtualFile = directory.getVirtualFile(); - final boolean isInTestContent = projectFileIndex.isInTestSourceContent(virtualFile); - + final boolean isInTestContent = TestSourcesFilter.isTestSources(virtualFile, directory.getProject()); if (!currentSuite.isTrackTestFolders() && isInTestContent) { return null; } - return isInTestContent ? getCoverageInformationString(myTestDirCoverageInfos.get(virtualFile), coverageDataManager.isSubCoverageActive()) - : getCoverageInformationString(myDirCoverageInfos.get(virtualFile), coverageDataManager.isSubCoverageActive()); + return getCoverageInformationString(isInTestContent ? myTestDirCoverageInfos.get(virtualFile) : myDirCoverageInfos.get(virtualFile), coverageDataManager.isSubCoverageActive()); } diff --git a/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java b/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java index a10d61c8baf86..e1ff189a47527 100644 --- a/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java +++ b/plugins/coverage/src/com/intellij/coverage/JavaCoverageEngine.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2016 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.coverage; import com.intellij.CommonBundle; @@ -23,7 +38,7 @@ import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.module.Module; -import com.intellij.openapi.module.ModuleUtil; +import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.progress.Task; @@ -32,8 +47,8 @@ import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.CompilerModuleExtension; import com.intellij.openapi.roots.ModuleRootManager; -import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.io.FileUtil; @@ -45,7 +60,7 @@ import com.intellij.psi.controlFlow.*; import com.intellij.psi.impl.source.tree.java.PsiSwitchStatementImpl; import com.intellij.psi.search.GlobalSearchScope; -import com.intellij.psi.search.GlobalSearchScopes; +import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.psi.util.ClassUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.rt.coverage.data.JumpData; @@ -160,7 +175,7 @@ public boolean coverageEditorHighlightingApplicableTo(@NotNull final PsiFile psi final Module module = ApplicationManager.getApplication().runReadAction(new Computable() { @Nullable public Module compute() { - return ModuleUtil.findModuleForPsiElement(psiFile); + return ModuleUtilCore.findModuleForPsiElement(psiFile); } }); return module != null; @@ -170,8 +185,7 @@ public boolean acceptedByFilters(@NotNull final PsiFile psiFile, @NotNull final final VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) return false; final Project project = psiFile.getProject(); - final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); - if (!suite.isTrackTestFolders() && fileIndex.isInTestSourceContent(virtualFile)) { + if (!suite.isTrackTestFolders() && TestSourcesFilter.isTestSources(virtualFile, project)) { return false; } @@ -605,7 +619,7 @@ public Collection getClasses() { final Collection classes = super.getClasses(); if (!currentSuite.isTrackTestFolders()) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project); - final GlobalSearchScope productionScope = GlobalSearchScopes.projectProductionScope(project); + final GlobalSearchScope productionScope = GlobalSearchScopesCore.projectProductionScope(project); for (Iterator iterator = classes.iterator(); iterator.hasNext();) { final ClassInfo aClass = iterator.next(); final PsiClass psiClass = DumbService.getInstance(project).runReadActionInSmartMode(() -> { diff --git a/xml/dom-openapi/src/com/intellij/util/xml/AbstractConvertContext.java b/xml/dom-openapi/src/com/intellij/util/xml/AbstractConvertContext.java index 205da1c0ea69e..4f051b8489671 100644 --- a/xml/dom-openapi/src/com/intellij/util/xml/AbstractConvertContext.java +++ b/xml/dom-openapi/src/com/intellij/util/xml/AbstractConvertContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -17,8 +17,7 @@ import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; -import com.intellij.openapi.roots.ProjectFileIndex; -import com.intellij.openapi.roots.ProjectRootManager; +import com.intellij.openapi.roots.TestSourcesFilter; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; @@ -72,9 +71,7 @@ public GlobalSearchScope getSearchScope() { file = file.getOriginalFile(); VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { - ProjectFileIndex fileIndex = ProjectRootManager.getInstance(file.getProject()).getFileIndex(); - boolean tests = fileIndex.isInTestSourceContent(virtualFile); - + boolean tests = TestSourcesFilter.isTestSources(virtualFile, file.getProject()); for (Module module : modules) { if (scope == null) { scope = module.getModuleRuntimeScope(tests); From 715fd9c8a2034077c0aed806cd74a735fce27ed8 Mon Sep 17 00:00:00 2001 From: Alexander Zolotov Date: Wed, 20 Jul 2016 14:58:28 +0300 Subject: [PATCH 08/67] Remove unused methods + fix yellow code --- .../com/intellij/analysis/AnalysisScope.java | 36 +++++------------ .../BackwardDependenciesBuilder.java | 3 +- .../ide/util/PlatformPackageUtil.java | 40 ++++--------------- 3 files changed, 20 insertions(+), 59 deletions(-) diff --git a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java index 2b25cc0281b64..0cc33c2ef1ed3 100644 --- a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java +++ b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java @@ -16,7 +16,6 @@ package com.intellij.analysis; -import com.intellij.codeInsight.FileModificationService; import com.intellij.codeInsight.daemon.ProblemHighlightFilter; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.application.ApplicationManager; @@ -168,7 +167,6 @@ public void setIncludeTestSource(final boolean includeTestSource) { @NotNull protected PsiElementVisitor createFileSearcher() { - final FileIndex fileIndex = getFileIndex(); final ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator(); if (indicator != null) { indicator.setText(AnalysisScopeBundle.message("scanning.scope.progress.title")); @@ -180,7 +178,7 @@ public void visitFile(@NotNull PsiFile file) { if (mySearchInLibraries || !(file instanceof PsiCompiledElement)) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) return; - if (isFiltered(virtualFile, fileIndex)) { + if (isFiltered(virtualFile)) { return; } if (!shouldHighlightFile(file)) return; @@ -190,7 +188,7 @@ public void visitFile(@NotNull PsiFile file) { }; } - private boolean isFiltered(VirtualFile virtualFile, FileIndex fileIndex) { + private boolean isFiltered(VirtualFile virtualFile) { if (myFilter != null && !myFilter.contains(virtualFile)) { return true; } @@ -229,7 +227,7 @@ public boolean contains(@NotNull VirtualFile file) { } if (myType == PROJECT) { //optimization final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); - return index.isInContent(file) && !isFiltered(file, index); + return index.isInContent(file) && !isFiltered(file); } initFilesSet(); } @@ -282,7 +280,7 @@ private void accept(@NotNull final PsiElementVisitor visitor, final boolean clea accept(file -> { if (file.isDirectory()) return true; if (ProjectCoreUtil.isProjectOrWorkspaceFile(file)) return true; - if (fileIndex.isInContent(file) && !isFiltered(file, fileIndex) + if (fileIndex.isInContent(file) && !isFiltered(file) && !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) { return processFile(file, visitor, psiManager, needReadAction, clearResolveCache); } @@ -293,16 +291,15 @@ private void accept(@NotNull final PsiElementVisitor visitor, final boolean clea public boolean accept(@NotNull final Processor processor) { if (myType == VIRTUAL_FILES) { if (myFilesSet == null) initFilesSet(); - final FileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); for (final VirtualFile file : myFilesSet) { - if (isFiltered(file, index)) continue; + if (isFiltered(file)) continue; if (!processor.process(file)) return false; } return true; } final FileIndex projectFileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); if (myScope instanceof GlobalSearchScope) { - final ContentIterator contentIterator = createScopeIterator(processor, projectFileIndex, myScope); + final ContentIterator contentIterator = createScopeIterator(processor, myScope); if (!projectFileIndex.iterateContent(contentIterator)) return false; if (mySearchInLibraries) { final VirtualFile[] libraryRoots = LibraryUtil.getLibraryRoots(myProject, false, false); @@ -332,7 +329,7 @@ public VirtualFile compute() { if (modules != null) { for (final Module module : modules) { final FileIndex moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex(); - if (!moduleFileIndex.iterateContent(createScopeIterator(processor, moduleFileIndex, null))) { + if (!moduleFileIndex.iterateContent(createScopeIterator(processor, null))) { return false; } } @@ -352,12 +349,11 @@ public VirtualFile compute() { return file == null || processor.process(file); } - return projectFileIndex.iterateContent(createScopeIterator(processor, projectFileIndex, null)); + return projectFileIndex.iterateContent(createScopeIterator(processor, null)); } @NotNull - private ContentIterator createScopeIterator(@NotNull final Processor processor, - @NotNull final FileIndex projectFileIndex, + private ContentIterator createScopeIterator(@NotNull final Processor processor, @Nullable final SearchScope searchScope) { return new ContentIterator() { @Override @@ -365,7 +361,7 @@ public boolean processFile(@NotNull final VirtualFile fileOrDir) { final boolean isInScope = ApplicationManager.getApplication().runReadAction(new Computable() { @Override public Boolean compute() { - if (isFiltered(fileOrDir, projectFileIndex)) return false; + if (isFiltered(fileOrDir)) return false; if (GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(fileOrDir, myProject)) return false; return searchScope == null || ((GlobalSearchScope)searchScope).contains(fileOrDir); } @@ -439,14 +435,13 @@ private static void doProcessFile(@NotNull PsiElementVisitor visitor, @NotNull P protected boolean accept(@NotNull final PsiDirectory dir, @NotNull final Processor processor) { final Project project = dir.getProject(); - final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); //we should analyze generated source files only if the action is explicitly invoked for a directory located under generated roots final boolean processGeneratedFiles = GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(dir.getVirtualFile(), project); return VfsUtilCore.iterateChildrenRecursively(dir.getVirtualFile(), VirtualFileFilter.ALL, new ContentIterator() { @Override @SuppressWarnings({"SimplifiableIfStatement"}) public boolean processFile(@NotNull final VirtualFile fileOrDir) { - if (isFiltered(fileOrDir, index)) return true; + if (isFiltered(fileOrDir)) return true; if (!processGeneratedFiles && GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(fileOrDir, project)) return true; if (!fileOrDir.isDirectory()) { return processor.process(fileOrDir); @@ -560,15 +555,6 @@ public int getFileCount() { return myFilesSet.size(); } - /** - * scope elements should be checked only when needed - */ - @Deprecated - public boolean checkScopeWritable(@NotNull Project project) { - if (myFilesSet == null) initFilesSet(); - return !FileModificationService.getInstance().prepareVirtualFilesForWrite(project, myFilesSet); - } - public void invalidate(){ if (myType == VIRTUAL_FILES) { for (Iterator i = myVFiles.iterator(); i.hasNext();) { diff --git a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java index fce508bbc608b..a0f99e8b8495a 100644 --- a/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java +++ b/platform/analysis-impl/src/com/intellij/packageDependencies/BackwardDependenciesBuilder.java @@ -74,8 +74,7 @@ public boolean isBackward() { @Override public void analyze() { - AnalysisScope scope = myForwardScope; - final DependenciesBuilder builder = new ForwardDependenciesBuilder(getProject(), scope, getScopeOfInterest()); + final DependenciesBuilder builder = new ForwardDependenciesBuilder(getProject(), myForwardScope, getScopeOfInterest()); builder.setTotalFileCount(myTotalFileCount); builder.analyze(); diff --git a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java index c07bc47fc86ac..b751c5373035b 100644 --- a/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java +++ b/platform/lang-impl/src/com/intellij/ide/util/PlatformPackageUtil.java @@ -28,6 +28,7 @@ import com.intellij.openapi.roots.ui.configuration.CommonContentEntriesEditor; import com.intellij.openapi.roots.ui.configuration.ProjectSettingsService; import com.intellij.openapi.ui.Messages; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; @@ -94,7 +95,7 @@ public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull final Projec boolean askUserToCreate, ThreeState chooseFlag) throws IncorrectOperationException { PsiDirectory psiDirectory = null; - if (chooseFlag == ThreeState.UNSURE && !"".equals(packageName)) { + if (chooseFlag == ThreeState.UNSURE && StringUtil.isNotEmpty(packageName)) { String rootPackage = findLongestExistingPackage(project, packageName, scope); if (rootPackage != null) { int beginIndex = rootPackage.length() + 1; @@ -112,7 +113,7 @@ public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull final Projec if (psiDirectory == null) { if (chooseFlag == ThreeState.NO && baseDir != null) { VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(baseDir.getVirtualFile()); - psiDirectory = PsiManager.getInstance(project).findDirectory(sourceRoot); + psiDirectory = sourceRoot != null ? PsiManager.getInstance(project).findDirectory(sourceRoot) : null; } else { if (module != null && !checkSourceRootsConfigured(module)) return null; @@ -125,7 +126,7 @@ public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull final Projec File.separatorChar + packageName.replace('.', File.separatorChar)); if (psiDirectory == null) return null; final VirtualFile sourceRoot = ProjectRootManager.getInstance(project).getFileIndex().getSourceRootForFile(psiDirectory.getVirtualFile()); - psiDirectory = PsiManager.getInstance(project).findDirectory(sourceRoot); + psiDirectory = sourceRoot != null ? PsiManager.getInstance(project).findDirectory(sourceRoot) : null; } } @@ -133,7 +134,7 @@ public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull final Projec boolean askedToCreate = false; while (restOfName.length() > 0) { final String name = getLeftPart(restOfName); - PsiDirectory foundExistingDirectory = psiDirectory.findSubdirectory(name); + PsiDirectory foundExistingDirectory = psiDirectory != null ? psiDirectory.findSubdirectory(name) : null; if (foundExistingDirectory == null) { if (!askedToCreate && askUserToCreate) { if (!ApplicationManager.getApplication().isUnitTestMode()) { @@ -153,7 +154,7 @@ public static PsiDirectory findOrCreateDirectoryForPackage(@NotNull final Projec psiDirectory = ActionRunner.runInsideWriteAction(new ActionRunner.InterruptibleRunnableWithResult() { @Override public PsiDirectory run() throws Exception { - return psiDirectory_.createSubdirectory(name); + return psiDirectory_ != null ? psiDirectory_.createSubdirectory(name) : null; } }); } @@ -198,9 +199,9 @@ private static PsiDirectory[] getPackageDirectories(Project project, String root final PsiManager manager = PsiManager.getInstance(project); Query query = DirectoryIndex.getInstance(scope.getProject()).getDirectoriesByPackageName(rootPackage, true); - query = new FilteredQuery(query, virtualFile -> scope.contains(virtualFile)); + query = new FilteredQuery(query, scope::contains); - List directories = ContainerUtil.mapNotNull(query.findAll(), virtualFile -> manager.findDirectory(virtualFile)); + List directories = ContainerUtil.mapNotNull(query.findAll(), manager::findDirectory); return directories.toArray(new PsiDirectory[directories.size()]); } @@ -234,31 +235,6 @@ private static String cutLeftPart(String packageName) { return index > -1 ? packageName.substring(index + 1) : ""; } - @Nullable - public static PsiDirectory findPossiblePackageDirectoryInModule(Module module, GlobalSearchScope scope, String packageName) { - if (!"".equals(packageName)) { - String rootPackage = findLongestExistingPackage(module.getProject(), packageName, scope); - if (rootPackage != null) { - final PsiDirectory[] psiDirectories = getPackageDirectories(module.getProject(), rootPackage, scope); - if (psiDirectories.length > 0) { - return psiDirectories[0]; - } - } - } - - if (!checkSourceRootsConfigured(module)) return null; - - final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(); - for (VirtualFile sourceRoot : sourceRoots) { - final PsiDirectory directory = PsiManager.getInstance(module.getProject()).findDirectory(sourceRoot); - if (directory != null) { - return directory; - } - } - - return null; - } - @Nullable public static PsiDirectory getDirectory(@Nullable PsiElement element) { if (element == null) return null; From e2d97aefffd833f2cf913146190f00b91326a009 Mon Sep 17 00:00:00 2001 From: irengrig Date: Wed, 20 Jul 2016 14:12:12 +0200 Subject: [PATCH 09/67] WEB-19898 Add code completion for eslintrc section inside package.json file --- .../extension/JsonSchemaFileProvider.java | 2 + .../JsonSchemaImportedProviderFactory.java | 5 ++ .../JsonSchemaProjectSelfProviderFactory.java | 5 ++ .../jsonSchema/impl/JsonSchemaReader.java | 15 +++- .../impl/JsonSchemaServiceImpl.java | 77 ++++++++++--------- .../jsonSchema/JsonSchemaTestProvider.java | 5 ++ 6 files changed, 69 insertions(+), 40 deletions(-) diff --git a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaFileProvider.java b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaFileProvider.java index 2f94b81ed6dd7..96b7ce7bdd2d3 100644 --- a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaFileProvider.java +++ b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaFileProvider.java @@ -14,4 +14,6 @@ public interface JsonSchemaFileProvider { VirtualFile getSchemaFile(); SchemaType getSchemaType(); + + int getOrder(); } diff --git a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java index 9e8dafa1f9e18..7883df39f83e9 100644 --- a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java +++ b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaImportedProviderFactory.java @@ -75,6 +75,11 @@ public SchemaType getSchemaType() { return SchemaType.userSchema; } + @Override + public int getOrder() { + return 1000; + } + @NotNull @Override public String getName() { diff --git a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaProjectSelfProviderFactory.java b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaProjectSelfProviderFactory.java index cb76f288228f0..a4366664e4d18 100644 --- a/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaProjectSelfProviderFactory.java +++ b/json/src/com/jetbrains/jsonSchema/extension/JsonSchemaProjectSelfProviderFactory.java @@ -67,5 +67,10 @@ public VirtualFile getSchemaFile() { public SchemaType getSchemaType() { return SchemaType.schema; } + + @Override + public int getOrder() { + return -1000; + } } } diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java index eeeba1384a498..4a9b4dd406f50 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaReader.java @@ -93,6 +93,7 @@ public static void registerObjectsExportedDefinitions(@NotNull VirtualFile key, }; final HashMap map = new HashMap<>(); + map.put("", object); final Map definitions = object.getDefinitions(); if (definitions != null && !definitions.isEmpty()) { map.putAll(convertor.convert("#/definitions/", definitions)); @@ -160,11 +161,17 @@ private static JsonSchemaObject findAbsoluteDefinition(@Nullable VirtualFile key @NotNull String ref, @Nullable JsonSchemaExportedDefinitions definitions) { if (!ref.startsWith("#/")) { - int idx = ref.indexOf("#/"); - if (idx == -1) throw new RuntimeException("Non-relative or erroneous reference: " + ref); if (definitions == null || key == null) return null; - final String url = ref.substring(0, idx); - final String relative = ref.substring(idx); + int idx = ref.indexOf("#/"); + final String url; + final String relative; + if (idx == -1) { + url = ref.endsWith("#") ? ref.substring(0, ref.length() - 1) : ref; + relative = ""; + } else { + url = ref.substring(0, idx); + relative = ref.substring(idx); + } return definitions.findDefinition(key, url, relative); } return null; diff --git a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java index 52684e0058c83..5812d8701b2f7 100644 --- a/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java +++ b/json/src/com/jetbrains/jsonSchema/impl/JsonSchemaServiceImpl.java @@ -43,6 +43,12 @@ public class JsonSchemaServiceImpl implements JsonSchemaServiceEx { private static final Logger LOGGER = Logger.getInstance(JsonSchemaServiceImpl.class); private static final Logger RARE_LOGGER = RareLogger.wrap(LOGGER, false); + public static final Comparator FILE_PROVIDER_COMPARATOR = new Comparator() { + @Override + public int compare(JsonSchemaFileProvider o1, JsonSchemaFileProvider o2) { + return Integer.compare(o1.getOrder(), o2.getOrder()); + } + }; @NotNull private final Project myProject; private final Object myLock; @@ -57,7 +63,7 @@ public JsonSchemaServiceImpl(@NotNull Project project) { myDefinitions = new JsonSchemaExportedDefinitions(this::iterateSchemas); ApplicationManager .getApplication().getMessageBus().connect(project).subscribe(VirtualFileManager.VFS_CHANGES, new JsonSchemaVfsListener(project, this)); - ensureSchemaFiles(project); + ensureSchemaFiles(); } @NotNull @@ -65,6 +71,15 @@ protected JsonSchemaProviderFactory[] getProviderFactories() { return JsonSchemaProviderFactory.EP_NAME.getExtensions(); } + private List getProviders() { + final List providers = new ArrayList<>(); + for (JsonSchemaProviderFactory factory : getProviderFactories()) { + providers.addAll(factory.getProviders(myProject)); + } + Collections.sort(providers, FILE_PROVIDER_COMPARATOR); + return providers; + } + @Nullable public Annotator getAnnotator(@Nullable VirtualFile file) { @@ -86,22 +101,18 @@ public boolean hasSchema(@Nullable VirtualFile file) { @Override public boolean isRegisteredSchemaFile(@NotNull Project project, @NotNull VirtualFile file) { if (!initialized) { - ensureSchemaFiles(project); + ensureSchemaFiles(); } return mySchemaFiles.contains(file); } - private void ensureSchemaFiles(@NotNull final Project project) { + private void ensureSchemaFiles() { synchronized (myLock) { if (!initialized) { - final JsonSchemaProviderFactory[] factories = getProviderFactories(); - for (JsonSchemaProviderFactory factory : factories) { - final List providers = factory.getProviders(project); - for (JsonSchemaFileProvider provider : providers) { - final VirtualFile schemaFile = provider.getSchemaFile(); - if (schemaFile != null) { - mySchemaFiles.add(schemaFile); - } + for (JsonSchemaFileProvider provider : getProviders()) { + final VirtualFile schemaFile = provider.getSchemaFile(); + if (schemaFile != null) { + mySchemaFiles.add(schemaFile); } } initialized = true; @@ -226,17 +237,14 @@ private CodeInsightProviders getWrapper(@Nullable VirtualFile file) { } public void iterateSchemas(@NotNull final PairConsumer> consumer) { - final JsonSchemaProviderFactory[] factories = getProviderFactories(); - for (JsonSchemaProviderFactory factory : factories) { - for (JsonSchemaFileProvider provider : factory.getProviders(myProject)) { - consumer.consume(provider.getSchemaFile(), - new NullableLazyValue() { - @Override - protected JsonSchemaObject compute() { - return readObject(provider, null); - } - }); - } + for (JsonSchemaFileProvider provider : getProviders()) { + consumer.consume(provider.getSchemaFile(), + new NullableLazyValue() { + @Override + protected JsonSchemaObject compute() { + return readObject(provider, null); + } + }); } } @@ -255,22 +263,19 @@ public void dropProviderFromCache(@NotNull final VirtualFile key) { private List getWrappers(@Nullable VirtualFile file) { if (file == null) return null; final List wrappers = new ArrayList<>(); - JsonSchemaProviderFactory[] factories = getProviderFactories(); synchronized (myLock) { final Set files = mySchemaFiles.isEmpty() ? new HashSet<>() : null; - for (JsonSchemaProviderFactory factory : factories) { - for (JsonSchemaFileProvider provider : factory.getProviders(myProject)) { - final VirtualFile key = provider.getSchemaFile(); - if (files != null) files.add(key); - if (provider.isAvailable(myProject, file)) { - JsonSchemaObjectCodeInsightWrapper wrapper = myWrappers.get(key); - if (wrapper == null) { - wrapper = createWrapper(provider); - if (wrapper == null) return null; - myWrappers.putIfAbsent(key, wrapper); - } - wrappers.add(wrapper); + for (JsonSchemaFileProvider provider : getProviders()) { + final VirtualFile key = provider.getSchemaFile(); + if (files != null) files.add(key); + if (provider.isAvailable(myProject, file)) { + JsonSchemaObjectCodeInsightWrapper wrapper = myWrappers.get(key); + if (wrapper == null) { + wrapper = createWrapper(provider); + if (wrapper == null) return null; + myWrappers.putIfAbsent(key, wrapper); } + wrappers.add(wrapper); } } if (files != null) mySchemaFiles.addAll(files); @@ -354,7 +359,7 @@ public boolean checkFileForId(@NotNull final String id, @NotNull final VirtualFi @Override public Set getSchemaFiles() { if (!initialized) { - ensureSchemaFiles(myProject); + ensureSchemaFiles(); } return Collections.unmodifiableSet(mySchemaFiles); } diff --git a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaTestProvider.java b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaTestProvider.java index 9c9b27ad3ddf6..e598f876b1975 100644 --- a/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaTestProvider.java +++ b/json/tests/test/com/jetbrains/jsonSchema/JsonSchemaTestProvider.java @@ -36,4 +36,9 @@ public VirtualFile getSchemaFile() { public SchemaType getSchemaType() { return SchemaType.userSchema; } + + @Override + public int getOrder() { + return 10; + } } From 23175fa0d5286e2df582291ab6bc724a9542cfaa Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Wed, 20 Jul 2016 14:18:31 +0200 Subject: [PATCH 10/67] [platform] fault-tolerant diagnostic composition for HttpRequests (IDEA-156936) --- .../com/intellij/util/io/HttpRequests.java | 33 ++++++++++++++----- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/platform/platform-api/src/com/intellij/util/io/HttpRequests.java b/platform/platform-api/src/com/intellij/util/io/HttpRequests.java index 567cf4d685013..acbdc552ab7cd 100644 --- a/platform/platform-api/src/com/intellij/util/io/HttpRequests.java +++ b/platform/platform-api/src/com/intellij/util/io/HttpRequests.java @@ -64,6 +64,9 @@ private HttpRequests() { } public interface Request { + @NotNull + String getURL(); + @NotNull URLConnection getConnection() throws IOException; @@ -129,17 +132,23 @@ public static RequestBuilder request(@NotNull String url) { } @NotNull - public static String createErrorMessage(@NotNull IOException e, @NotNull Request request, boolean includeHeaders) throws IOException { - URLConnection connection = request.getConnection(); + public static String createErrorMessage(@NotNull IOException e, @NotNull Request request, boolean includeHeaders) { StringBuilder builder = new StringBuilder(); - builder.append("Cannot download '").append(connection.getURL().toExternalForm()).append("': ").append(e.getMessage()); - if (includeHeaders) { - builder.append("\n, headers: ").append(connection.getHeaderFields()); - } - if (connection instanceof HttpURLConnection) { - HttpURLConnection httpConnection = (HttpURLConnection)connection; - builder.append("\n, response: ").append(httpConnection.getResponseCode()).append(' ').append(httpConnection.getResponseMessage()); + + builder.append("Cannot download '").append(request.getURL()).append("': ").append(e.getMessage()); + + try { + URLConnection connection = request.getConnection(); + if (includeHeaders) { + builder.append("\n, headers: ").append(connection.getHeaderFields()); + } + if (connection instanceof HttpURLConnection) { + HttpURLConnection httpConnection = (HttpURLConnection)connection; + builder.append("\n, response: ").append(httpConnection.getResponseCode()).append(' ').append(httpConnection.getResponseMessage()); + } } + catch (Throwable ignored) { } + return builder.toString(); } @@ -249,6 +258,12 @@ private RequestImpl(RequestBuilderImpl builder) { myBuilder = builder; } + @NotNull + @Override + public String getURL() { + return myBuilder.myUrl; + } + @NotNull @Override public URLConnection getConnection() throws IOException { From 9a19c43084fac32826e61b8c0e1f744f778f1163 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 20 Jul 2016 14:24:27 +0300 Subject: [PATCH 11/67] data race --- .../openapi/util/registry/Registry.java | 14 +++++++------ .../openapi/util/registry/RegistryValue.java | 20 ++++++++++--------- 2 files changed, 19 insertions(+), 15 deletions(-) diff --git a/platform/util/src/com/intellij/openapi/util/registry/Registry.java b/platform/util/src/com/intellij/openapi/util/registry/Registry.java index 89c60b09f70c2..6f067458054c2 100644 --- a/platform/util/src/com/intellij/openapi/util/registry/Registry.java +++ b/platform/util/src/com/intellij/openapi/util/registry/Registry.java @@ -15,6 +15,7 @@ */ package com.intellij.openapi.util.registry; +import com.intellij.util.ConcurrencyUtil; import com.intellij.util.containers.HashMap; import org.jdom.Element; import org.jetbrains.annotations.NonNls; @@ -27,6 +28,7 @@ import java.util.*; import java.util.List; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; public class Registry { private static Reference ourBundle; @@ -35,7 +37,7 @@ public class Registry { public static final String REGISTRY_BUNDLE = "misc.registry"; private final Map myUserProperties = new LinkedHashMap(); - private final Map myValues = new ConcurrentHashMap(); + private final ConcurrentMap myValues = new ConcurrentHashMap(); private static final Registry ourInstance = new Registry(); @@ -45,8 +47,7 @@ public static RegistryValue get(@PropertyKey(resourceBundle = REGISTRY_BUNDLE) @ RegistryValue value = registry.myValues.get(key); if (value == null) { - value = new RegistryValue(registry, key); - registry.myValues.put(key, value); + value = ConcurrencyUtil.cacheOrGet(registry.myValues, key, new RegistryValue(registry, key)); } return value; } @@ -101,6 +102,7 @@ static ResourceBundle getBundle() { } + @NotNull public static Registry getInstance() { return ourInstance; } @@ -153,7 +155,7 @@ public static List getAll() { return result; } - public void restoreDefaults() { + void restoreDefaults() { Map old = new HashMap(); old.putAll(myUserProperties); for (String each : old.keySet()) { @@ -167,11 +169,11 @@ public void restoreDefaults() { } } - public boolean isInDefaultState() { + boolean isInDefaultState() { return myUserProperties.isEmpty(); } - public boolean isRestartNeeded() { + boolean isRestartNeeded() { return isRestartNeeded(myUserProperties); } diff --git a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java index 266470b2dc160..64f0f78b3dad8 100644 --- a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java +++ b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java @@ -98,7 +98,7 @@ public double asDouble() { return myDoubleCachedValue.doubleValue(); } - public Color asColor(Color defaultValue) { + Color asColor(Color defaultValue) { final String s = get(myKey, null, true); if (s != null) { final String[] rgb = s.split(","); @@ -106,7 +106,7 @@ public Color asColor(Color defaultValue) { try { return new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])); } - catch (Exception e) {// + catch (Exception e) { } } } @@ -118,7 +118,7 @@ public String getDescription() { return get(myKey + ".description", "", false); } - public boolean isRestartRequired() { + boolean isRestartRequired() { return Boolean.valueOf(get(myKey + ".restartRequired", "false", false)); } @@ -132,15 +132,17 @@ boolean isChangedFromDefault(@NotNull String newValue) { private String get(@NotNull String key, String defaultValue, boolean isValue) throws MissingResourceException { if (isValue) { - if (myStringCachedValue == null) { - myStringCachedValue = _get(key, defaultValue, isValue); + String stringCachedValue = myStringCachedValue; + if (stringCachedValue == null) { + stringCachedValue = _get(key, defaultValue, true); if (isBoolean()) { - myStringCachedValue = Boolean.valueOf(myStringCachedValue).toString(); + stringCachedValue = Boolean.valueOf(stringCachedValue).toString(); } + myStringCachedValue = stringCachedValue; } - return myStringCachedValue; + return stringCachedValue; } - return _get(key, defaultValue, isValue); + return _get(key, defaultValue, false); } private String _get(@NotNull String key, String defaultValue, boolean mustExistInBundle) throws MissingResourceException { @@ -200,7 +202,7 @@ public void setValue(String value) { myChangedSinceStart = true; } - public boolean isChangedSinceAppStart() { + boolean isChangedSinceAppStart() { return myChangedSinceStart; } From 51d808f559648da8e35cec292063df229aaa0152 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 20 Jul 2016 14:25:09 +0300 Subject: [PATCH 12/67] assertions replaced with non-suppressable checks --- .../src/com/intellij/psi/search/GlobalSearchScope.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java b/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java index 5d30ba8f960cb..4b1ca8c8de9f3 100644 --- a/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java +++ b/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java @@ -15,7 +15,6 @@ */ package com.intellij.psi.search; -import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; @@ -39,7 +38,6 @@ import java.util.*; public abstract class GlobalSearchScope extends SearchScope implements ProjectAwareFileFilter { - private static final Logger LOG = Logger.getInstance("#com.intellij.psi.search.GlobalSearchScope"); @Nullable private final Project myProject; protected GlobalSearchScope(@Nullable Project project) { @@ -462,7 +460,7 @@ public Project fun(GlobalSearchScope scope) { return scope.getProject(); } }), null)); - assert scopes.length > 1 : Arrays.asList(scopes); + if (scopes.length <= 1) throw new IllegalArgumentException("Too few scopes: "+ Arrays.asList(scopes)); myScopes = scopes; final int[] nested = {0}; ContainerUtil.process(scopes, new Processor() { @@ -515,7 +513,7 @@ public boolean process(GlobalSearchScope scope) { result[0] = res1; return true; } - if ((result[0] > 0) != (res1 > 0)) { + if (result[0] > 0 != res1 > 0) { result[0] = 0; return false; } @@ -592,7 +590,7 @@ public static GlobalSearchScope getScopeRestrictedByFileTypes(@NotNull GlobalSea if (scope == EMPTY_SCOPE) { return EMPTY_SCOPE; } - LOG.assertTrue(fileTypes.length > 0); + if (fileTypes.length == 0) throw new IllegalArgumentException("empty fileTypes"); return new FileTypeRestrictionScope(scope, fileTypes); } From 6b15812a4ee6c1e2764f450ece969a3d451a58a4 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 20 Jul 2016 14:48:47 +0300 Subject: [PATCH 13/67] assertion --- .../com/intellij/openapi/util/registry/RegistryValue.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java index 64f0f78b3dad8..2e7476759421a 100644 --- a/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java +++ b/platform/util/src/com/intellij/openapi/util/registry/RegistryValue.java @@ -135,7 +135,7 @@ private String get(@NotNull String key, String defaultValue, boolean isValue) th String stringCachedValue = myStringCachedValue; if (stringCachedValue == null) { stringCachedValue = _get(key, defaultValue, true); - if (isBoolean()) { + if (isBoolean(stringCachedValue)) { stringCachedValue = Boolean.valueOf(stringCachedValue).toString(); } myStringCachedValue = stringCachedValue; @@ -232,6 +232,9 @@ void resetCache() { } public boolean isBoolean() { - return "true".equals(asString()) || "false".equals(asString()); + return isBoolean(asString()); + } + private static boolean isBoolean(String s) { + return "true".equals(s) || "false".equals(s); } } From db48c64473adba2ec0819681631fa36cb56e9764 Mon Sep 17 00:00:00 2001 From: Alexey Kudravtsev Date: Wed, 20 Jul 2016 15:40:52 +0300 Subject: [PATCH 14/67] use mockJdk18 by default in LightCodeInsightTestCase; remove dependency on swing/net classes in some tests --- .../codeInsight/ExpectedTypesProvider.java | 17 ++++-- .../impl/quickfix/CreateFromUsageUtils.java | 52 ++++++++-------- .../completion/style/AfterNew15-out.java | 4 +- .../advHighlighting/AccessInner.java | 15 +++-- .../advHighlighting/AssignToFinal.java | 2 +- .../advHighlighting/AssignmentCompatible.java | 2 +- .../advHighlighting/CyclicInheritance.java | 2 +- .../DuplicateSwitchLabels.java | 2 +- .../advHighlighting/ExceptionNeverThrown.java | 5 +- .../ExceptionNeverThrownInTry.java | 2 +- .../FieldDoubleInitialization.java | 2 +- .../advHighlighting/FinalFieldInit.java | 6 +- .../IllegalForwardReference.java | 2 +- .../InitializerCompletion.java | 10 +++- .../advHighlighting/Labels.java | 4 +- .../LocalVariableInitialization.java | 1 - .../advHighlighting/MissingReturn.java | 2 +- .../advHighlighting/OverrideConflicts.java | 12 ++-- .../ReferenceMemberBeforeCtrCalled.java | 1 - .../advHighlighting/SillyAssignment.java | 5 +- .../SingleTypeImportConflicts.java | 6 +- .../advHighlighting/StaticOverride.java | 2 +- .../advHighlighting/UnclosedComment.java | 1 - .../advHighlighting/UndefinedLabel.java | 2 - .../UnhandledExceptionsInSuperclass.java | 2 +- .../advHighlighting/Unreachable.java | 17 ++++-- .../VarDoubleInitialization.java | 2 +- .../quickFix/createClassFromNew/after8.java | 6 +- .../quickFix/createClassFromNew/before8.java | 7 ++- .../afterExpectedTypes.java | 11 ++-- .../beforeExpectedTypes.java | 9 ++- .../createInnerClassFromNew/after8.java | 8 ++- .../createInnerClassFromNew/before8.java | 7 ++- .../refactoring/extractMethod/AnonInner.java | 11 ++-- .../extractMethod/AnonInner_after.java | 11 ++-- .../extractMethod/ArrayAccess1_after.java | 4 +- ...tractUnresolvedLambdaExpression_after.java | 3 + .../FoldedWithNestedExpressions_after.java | 6 +- ...stChangeSignatureSameParamNames_after.java | 6 +- ...gnatureWithChangedParameterName_after.java | 4 +- ...ggestChangeSignatureWithFolding_after.java | 4 +- .../ImplementsInterface.java | 7 ++- .../ImplementsInterface.java.after | 7 ++- .../RedundantImplementsInterface.java | 7 ++- .../RedundantImplementsInterface.java.after | 7 ++- .../refactoring/introduceField/after1.java | 4 +- .../refactoring/makeMethodStatic/after20.java | 13 ++-- .../makeMethodStatic/before20.java | 13 ++-- .../TypesGenericsConcrete2Super.java | 4 +- .../TypesGenericsConcrete2Super.java.after | 4 +- .../RenameVarLocalToAlien.java | 4 +- .../RenameVarLocalToAlien.java.after | 6 +- .../RenameVarParamToAlien.java | 4 +- .../RenameVarParamToAlien.java.after | 6 +- .../daemon/GenericsHighlightingTest.java | 11 ---- .../daemon/HighlightStressTest.java | 16 +++-- .../daemon/LightAdvHighlightingJdk7Test.java | 20 +++++++ .../LightAdvHighlightingPerformanceTest.java | 14 +++-- .../daemon/LightAdvHighlightingTest.java | 49 ++++++++++++++- .../quickFix/CreateFieldFromUsageTest.java | 6 +- .../refactoring/RenameCollisionsTest.java | 4 +- .../inline/InlineConstantFieldTest.java | 7 +++ .../refactoring/inline/InlineLocalTest.java | 7 +++ .../LightCodeInsightTestCase.java | 2 +- .../afterWithZeroIntInitializer.java | 3 +- .../afterWithZeroLongInitializer.java | 3 +- .../longAdder/afterWithoutInitializer.java | 3 +- .../LightPlatformCodeInsightTestCase.java | 59 +++++++++++-------- 68 files changed, 358 insertions(+), 209 deletions(-) diff --git a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java index 1f09a42310c11..84d58fb6818ab 100644 --- a/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/ExpectedTypesProvider.java @@ -78,9 +78,14 @@ public PsiField[] findDeclaredFields(@NotNull final PsiManager manager, @NotNull @Override @NotNull public PsiMethod[] findDeclaredMethods(@NotNull final PsiManager manager, @NotNull String name) { - final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(manager.getProject()); - GlobalSearchScope scope = GlobalSearchScope.allScope(manager.getProject()); - return cache.getMethodsByNameIfNotMoreThan(name, scope, MAX_COUNT); + Project project = manager.getProject(); + final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project); + GlobalSearchScope sources = GlobalSearchScope.projectScope(project); + GlobalSearchScope libraries = GlobalSearchScope.notScope(sources); + PsiMethod[] sourceMethods = cache.getMethodsByNameIfNotMoreThan(name, sources, MAX_COUNT); + if (sourceMethods.length == MAX_COUNT) return sourceMethods; + PsiMethod[] libraryMethods = cache.getMethodsByNameIfNotMoreThan(name, libraries, MAX_COUNT-sourceMethods.length); + return ArrayUtil.mergeArrays(sourceMethods, libraryMethods); } }; private static final PsiType[] PRIMITIVE_TYPES = {PsiType.BYTE, PsiType.CHAR, PsiType.SHORT, PsiType.INT, PsiType.LONG, PsiType.FLOAT, PsiType.DOUBLE}; @@ -1274,9 +1279,11 @@ private ExpectedTypeInfo[] findClassesWithDeclaredField(@NotNull PsiReferenceExp * By default searches in the global scope (see ourGlobalScopeClassProvider), but caller can provide its own algorithm e.g. to narrow search scope */ public interface ExpectedClassProvider { - PsiField[] findDeclaredFields(final PsiManager manager, String name); + @NotNull + PsiField[] findDeclaredFields(@NotNull PsiManager manager, @NotNull String name); - PsiMethod[] findDeclaredMethods(final PsiManager manager, String name); + @NotNull + PsiMethod[] findDeclaredMethods(@NotNull PsiManager manager, @NotNull String name); } @NotNull diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java index 2ca7932f26b0d..e4d6e190ec275 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateFromUsageUtils.java @@ -64,6 +64,7 @@ import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.proximity.PsiProximityComparator; import com.intellij.refactoring.util.RefactoringUtil; +import com.intellij.util.ArrayUtil; import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NonNls; @@ -226,7 +227,7 @@ static void setupMethodParameters(PsiMethod method, TemplateBuilder builder, Psi public static void setupMethodParameters(final PsiMethod method, final TemplateBuilder builder, final PsiElement contextElement, final PsiSubstitutor substitutor, final PsiExpression[] arguments) { - setupMethodParameters(method, builder, contextElement, substitutor, ContainerUtil.map2List(arguments, Pair.createFunction(null))); + setupMethodParameters(method, builder, contextElement, substitutor, ContainerUtil.map2List(arguments, Pair.createFunction(null))); } static void setupMethodParameters(final PsiMethod method, final TemplateBuilder builder, final PsiElement contextElement, @@ -480,10 +481,12 @@ public static void scheduleFileOrPackageCreationFailedMessageBox(final Incorrect isPackage ? "cannot.create.java.package.error.title" : "cannot.create.java.file.error.title"))); } - public static PsiReferenceExpression[] collectExpressions(final PsiExpression expression, Class... scopes) { + @SafeVarargs + @NotNull + public static PsiReferenceExpression[] collectExpressions(final PsiExpression expression, @NotNull Class... scopes) { PsiElement parent = PsiTreeUtil.getParentOfType(expression, scopes); - final List result = new ArrayList(); + final List result = new ArrayList<>(); JavaRecursiveElementWalkingVisitor visitor = new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(PsiReferenceExpression expr) { if (expression instanceof PsiReferenceExpression) { @@ -512,13 +515,13 @@ public static PsiReferenceExpression[] collectExpressions(final PsiExpression ex } static PsiVariable[] guessMatchingVariables(final PsiExpression expression) { - List typesList = new ArrayList(); - List expectedMethodNames = new ArrayList(); - List expectedFieldNames = new ArrayList(); + List typesList = new ArrayList<>(); + List expectedMethodNames = new ArrayList<>(); + List expectedFieldNames = new ArrayList<>(); getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames); - final List list = new ArrayList(); + final List list = new ArrayList<>(); VariablesProcessor varproc = new VariablesProcessor("", true, list){ @Override public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) { @@ -534,7 +537,7 @@ public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) ExpectedTypeInfo[] infos = ExpectedTypeUtil.intersect(typesList); - List result = new ArrayList(); + List result = new ArrayList<>(); nextVar: for (PsiVariable variable : allVars) { PsiType varType = variable.getType(); @@ -631,13 +634,14 @@ private static ExpectedTypeInfo[] equalsExpectedTypes(PsiMethodCallExpression me return new ExpectedTypeInfo[]{ExpectedTypesProvider.createInfo(type, ExpectedTypeInfo.TYPE_STRICTLY, type, TailType.NONE)}; } - static ExpectedTypeInfo[] guessExpectedTypes(PsiExpression expression, boolean allowVoidType) { - PsiManager manager = expression.getManager(); + @NotNull + static ExpectedTypeInfo[] guessExpectedTypes(@NotNull PsiExpression expression, boolean allowVoidType) { + PsiManager manager = expression.getManager(); GlobalSearchScope resolveScope = expression.getResolveScope(); - List typesList = new ArrayList(); - List expectedMethodNames = new ArrayList(); - List expectedFieldNames = new ArrayList(); + List typesList = new ArrayList<>(); + List expectedMethodNames = new ArrayList<>(); + List expectedFieldNames = new ArrayList<>(); getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames); @@ -660,14 +664,16 @@ static ExpectedTypeInfo[] guessExpectedTypes(PsiExpression expression, boolean a } for (String methodName : expectedMethodNames) { - PsiMethod[] methods = cache.getMethodsByNameIfNotMoreThan(methodName, resolveScope, MAX_RAW_GUESSED_MEMBERS_COUNT); + PsiMethod[] projectMethods = cache.getMethodsByNameIfNotMoreThan(methodName, resolveScope.intersectWith(GlobalSearchScope.projectScope(manager.getProject())), MAX_RAW_GUESSED_MEMBERS_COUNT); + PsiMethod[] libraryMethods = cache.getMethodsByNameIfNotMoreThan(methodName, resolveScope.intersectWith(GlobalSearchScope.notScope(GlobalSearchScope.projectScope(manager.getProject()))), MAX_RAW_GUESSED_MEMBERS_COUNT); + PsiMethod[] methods = ArrayUtil.mergeArrays(projectMethods, libraryMethods); addMemberInfo(methods, expression, typesList, factory); } } ExpectedTypeInfo[] expectedTypes = ExpectedTypeUtil.intersect(typesList); if (expectedTypes.length == 0 && !typesList.isEmpty()) { - List union = new ArrayList(); + List union = new ArrayList<>(); for (ExpectedTypeInfo[] aTypesList : typesList) { ContainerUtil.addAll(union, (ExpectedTypeInfo[])aTypesList); } @@ -688,9 +694,9 @@ static PsiType[] guessType(PsiExpression expression, final boolean allowVoidType final PsiManager manager = expression.getManager(); final GlobalSearchScope resolveScope = expression.getResolveScope(); - List typesList = new ArrayList(); - final List expectedMethodNames = new ArrayList(); - final List expectedFieldNames = new ArrayList(); + List typesList = new ArrayList<>(); + final List expectedMethodNames = new ArrayList<>(); + final List expectedFieldNames = new ArrayList<>(); getExpectedInformation(expression, typesList, expectedMethodNames, expectedFieldNames); @@ -719,7 +725,7 @@ static PsiType[] guessType(PsiExpression expression, final boolean allowVoidType ExpectedTypeInfo[] expectedTypes = ExpectedTypeUtil.intersect(typesList); if (expectedTypes.length == 0 && !typesList.isEmpty()) { - List union = new ArrayList(); + List union = new ArrayList<>(); for (ExpectedTypeInfo[] aTypesList : typesList) { ContainerUtil.addAll(union, (ExpectedTypeInfo[])aTypesList); } @@ -731,7 +737,7 @@ static PsiType[] guessType(PsiExpression expression, final boolean allowVoidType } else { //Double check to avoid expensive operations on PsiClassTypes - final Set typesSet = new HashSet(); + final Set typesSet = new HashSet<>(); PsiTypeVisitor visitor = new PsiTypeVisitor() { @Override @@ -786,7 +792,7 @@ private static void addMemberInfo(PsiMember[] members, PsiElementFactory factory) { Arrays.sort(members, (m1, m2) -> compareMembers(m1, m2, expression)); - List l = new ArrayList(); + List l = new ArrayList<>(); PsiManager manager = expression.getManager(); JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject()); for (PsiMember member : members) { @@ -1026,13 +1032,13 @@ public LookupElement[] calculateLookupItems(ExpressionContext context) { PsiParameter parameter = PsiTreeUtil.getParentOfType(elementAt, PsiParameter.class); - Set parameterNames = new HashSet(); + Set parameterNames = new HashSet<>(); for (PsiParameter psiParameter : parameterList.getParameters()) { if (psiParameter == parameter) continue; parameterNames.add(psiParameter.getName()); } - Set set = new LinkedHashSet(); + Set set = new LinkedHashSet<>(); for (String name : myNames) { if (parameterNames.contains(name)) { diff --git a/java/java-tests/testData/codeInsight/completion/style/AfterNew15-out.java b/java/java-tests/testData/codeInsight/completion/style/AfterNew15-out.java index bcf00264728a1..bc7ec4e96e167 100644 --- a/java/java-tests/testData/codeInsight/completion/style/AfterNew15-out.java +++ b/java/java-tests/testData/codeInsight/completion/style/AfterNew15-out.java @@ -4,8 +4,8 @@ class A { { new java.io.File("aaa").list(new FilenameFilter() { - public boolean accept(File dir, String name) { - return false; + public boolean accept(File file, String s) { + return false; } }); } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AccessInner.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AccessInner.java index a89666ceb11ab..186b47fd2cb42 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AccessInner.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AccessInner.java @@ -1,14 +1,13 @@ // access problems in inner classes -import java.awt.*; -import java.beans.beancontext.BeanContextServicesSupport; -import java.beans.beancontext.BeanContextServicesSupport.BCSSChild; +import x.BeanContextServicesSupport; +import x.BeanContextServicesSupport.BCSSChild; -class a extends Component { +class a extends x.Component { void f() { FlipBufferStrategy s = null; - int i = s.numBuffers; - s.createBuffers(1,null); + int i = s.numBuffers; + s.createBuffers(1); // TODO // now cannot distinquish private from package-private in class files @@ -19,9 +18,9 @@ void f() { class ddd extends BeanContextServicesSupport { - BCSSChild.BCSSCServiceClassRef fd = null; + BCSSChild.BCSSCServiceClassRef fd = null; void ff() { - fd.addRequestor(null,null); + fd.addRequestor(null,null); } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignToFinal.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignToFinal.java index de5212a4bf870..e879391009fef 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignToFinal.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignToFinal.java @@ -1,6 +1,6 @@ // assign to final import java.io.*; -import java.net.*; + public class a21 { final int fi; { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignmentCompatible.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignmentCompatible.java index ebcf43e077729..478aa8ba76330 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignmentCompatible.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/AssignmentCompatible.java @@ -1,6 +1,6 @@ /// assignment compatible types import java.io.*; -import java.net.*; + public class a { final int FI = 2; final int FIBIG = 200000000; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/CyclicInheritance.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/CyclicInheritance.java index 141b59274c19c..1d838db9221fb 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/CyclicInheritance.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/CyclicInheritance.java @@ -1,6 +1,6 @@ // cyclic inhertiance import java.io.*; -import java.net.*; + class Foo extends Foo { } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/DuplicateSwitchLabels.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/DuplicateSwitchLabels.java index d2f7c626be460..e73a99d998982 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/DuplicateSwitchLabels.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/DuplicateSwitchLabels.java @@ -1,6 +1,6 @@ // duplicate labels import java.io.*; -import java.net.*; + public class a { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrown.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrown.java index ae86e0d54288a..01c8ac7978a8e 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrown.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrown.java @@ -1,7 +1,8 @@ // Exception is never thrown in method import java.io.*; -import java.sql.*; + +class SQLException extends Exception {} class a { private void f() throws IOException { @@ -50,7 +51,7 @@ protected void f2() throws java.io.IOException, SQLException{ + a1() throws java.io.IOException, SQLException{ } } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrownInTry.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrownInTry.java index 38782c3bd9330..9144be5a4acd4 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrownInTry.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ExceptionNeverThrownInTry.java @@ -1,5 +1,5 @@ import java.io.*; -import java.sql.*; + //////////// class x { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FieldDoubleInitialization.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FieldDoubleInitialization.java index c3de37be1aa4a..0bce77b22be1b 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FieldDoubleInitialization.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FieldDoubleInitialization.java @@ -1,6 +1,6 @@ // fields double initialization import java.io.*; -import java.net.*; + class Foo { final int k; final int ff = 5; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java index 560e595affd54..9e0d2be82a031 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/FinalFieldInit.java @@ -1,7 +1,5 @@ // final Fields initialization import java.io.*; -import java.net.*; -import java.awt.event.*; class a { /** @@ -87,8 +85,8 @@ class s { } private final String text; public Test() { - new ActionListener() { - public void actionPerformed(ActionEvent e) { + new Runnable() { + public void run() { doSomething(text);//// } }; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalForwardReference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalForwardReference.java index 45663a186dda3..05aee4dc14988 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalForwardReference.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalForwardReference.java @@ -1,6 +1,6 @@ /// forward references import java.io.*; -import java.net.*; + public class a { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/InitializerCompletion.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/InitializerCompletion.java index 2e270c0db875b..ff202b59fec1f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/InitializerCompletion.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/InitializerCompletion.java @@ -1,6 +1,5 @@ /// initalizers completion import java.io.*; -import java.net.*; public class a { @@ -26,12 +25,17 @@ class a2 { a2() {} } +class SocketException extends IOException { +} +class ConnectException extends SocketException { +} + class a3 { { - if (1==2) throw new SocketException(); + if (1==2) throw new SocketException(); } - a3() throws ConnectException {} + a3() throws ConnectException {} } class b { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Labels.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Labels.java index b98824c3da0fe..8017b820ef0cf 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Labels.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Labels.java @@ -1,6 +1,6 @@ // labels import java.io.*; -import java.net.*; + class a { void f() { @@ -66,4 +66,4 @@ void f() { } }; } -} \ No newline at end of file +} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/LocalVariableInitialization.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/LocalVariableInitialization.java index cee122f9a51c2..a867a4c6d5a8f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/LocalVariableInitialization.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/LocalVariableInitialization.java @@ -1,5 +1,4 @@ import java.io.*; -import java.net.*; import java.util.*; public class a { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MissingReturn.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MissingReturn.java index 5a3b705d1aebf..6024dba5632f4 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MissingReturn.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/MissingReturn.java @@ -1,6 +1,6 @@ //Missing return statement import java.io.*; -import java.net.*; + public class a { interface ii {} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/OverrideConflicts.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/OverrideConflicts.java index ef7cc7511756c..195030d67fdfc 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/OverrideConflicts.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/OverrideConflicts.java @@ -1,13 +1,17 @@ // throws conflicts on overriding/ override final import java.io.*; -import java.net.*; + public class a extends c3 { public void f() throws Exception { } } +class SocketException extends IOException { +} +class ConnectException extends SocketException { +} interface i { - void f() throws java.net.SocketException; + void f() throws SocketException; } class c2 implements i { public void f() throws java.io.IOException {} @@ -17,11 +21,11 @@ class c2i implements i { } class c3 implements i { - public void f() throws java.net.ConnectException {} + public void f() throws ConnectException {} } class c4 extends c3 { - public void f() throws java.net.ConnectException {} + public void f() throws ConnectException {} } interface MethodsFromObject { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ReferenceMemberBeforeCtrCalled.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ReferenceMemberBeforeCtrCalled.java index 691b9e47906b6..c59cb32c67132 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ReferenceMemberBeforeCtrCalled.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/ReferenceMemberBeforeCtrCalled.java @@ -2,7 +2,6 @@ import java.io.*; import java.lang.Override; import java.lang.String; -import java.net.*; class A { A(int i) {} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SillyAssignment.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SillyAssignment.java index 512efd3e1b0b8..6d4cc639b1f2f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SillyAssignment.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SillyAssignment.java @@ -1,6 +1,9 @@ // silly asignment -import javax.swing.*; +class JPanel { + JPanel getSize() { return this; } + int height; +} class a { int f; JPanel fpanel; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SingleTypeImportConflicts.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SingleTypeImportConflicts.java index 21013a5bc89dc..fc41d6ef0c3df 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SingleTypeImportConflicts.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/SingleTypeImportConflicts.java @@ -1,7 +1,7 @@ // single import conflict -import java.sql.Date; -import java.util.Date; -import java.sql.*; +import sql.Date; +import java.util.Date; +import sql.*; import java.util.*; // multiple single-type import of the same class is fine import java.io.IOException; diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/StaticOverride.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/StaticOverride.java index 157f2bda166a3..1ae5808438fcb 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/StaticOverride.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/StaticOverride.java @@ -1,6 +1,6 @@ // method override import java.io.*; -import java.net.*; + class a extends a1 { public static void f() { } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnclosedComment.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnclosedComment.java index 24870ee08896e..44efee662ae1d 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnclosedComment.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnclosedComment.java @@ -2,7 +2,6 @@ import java.io.*; -import java.net.*; /** class a { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UndefinedLabel.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UndefinedLabel.java index f4630d2486172..c4e350c6dff9f 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UndefinedLabel.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UndefinedLabel.java @@ -1,6 +1,4 @@ /// labels -import java.io.*; -import java.net.*; public class a { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnhandledExceptionsInSuperclass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnhandledExceptionsInSuperclass.java index fb12c28646ed1..fe0058af9099e 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnhandledExceptionsInSuperclass.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/UnhandledExceptionsInSuperclass.java @@ -1,6 +1,6 @@ // unhandled exceptions from superclases/etc import java.io.*; -import java.net.*; + class a { a(int i) {} } diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Unreachable.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Unreachable.java index 3eed64027e46a..7638e82809514 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Unreachable.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Unreachable.java @@ -1,6 +1,6 @@ // unreachables import java.io.*; -import java.net.*; + public class a { interface ii {} @@ -135,16 +135,21 @@ void cf3() { int i = 6; } } - void cf4() throws java.net.SocketException { + void cf4() throws SocketException { try { bind(); - } catch (java.net.SocketException se) { + } catch (SocketException se) { throw se; - } catch(java.io.IOException e) { - throw new java.net.SocketException(e.getMessage()); + } catch(IOException e) { + throw new SocketException(e.getMessage()); } } - void bind() throws java.net.SocketException {} + static class SocketException extends IOException { + public SocketException(String message) { + super(message); + } + } + void bind() throws SocketException {} void cf5() { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/VarDoubleInitialization.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/VarDoubleInitialization.java index de0f4f0f6d6db..3577fee0018a8 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/VarDoubleInitialization.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/VarDoubleInitialization.java @@ -1,6 +1,6 @@ // vars double initialization import java.io.*; -import java.net.*; + public class a21 { void f1(int i) { diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after8.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after8.java index 32e5c7327efc2..1481a62bde582 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after8.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/after8.java @@ -1,12 +1,14 @@ // "Create class 'MyTableModel'" "true" -import javax.swing.*; -import javax.swing.table.TableModel; public class Test { public static void main() { JTable table = new JTable(new MyTableModel()); } } +class JTable { + JTable(TableModel t) {} +} +interface TableModel {} public class MyTableModel implements TableModel { } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/before8.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/before8.java index 419fcf96ea078..67bee3691fb62 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/before8.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createClassFromNew/before8.java @@ -1,8 +1,11 @@ // "Create class 'MyTableModel'" "true" -import javax.swing.*; public class Test { public static void main() { JTable table = new JTable(new MyTableModel()); } -} \ No newline at end of file +} +class JTable { + JTable(TableModel t) {} +} +interface TableModel {} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/afterExpectedTypes.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/afterExpectedTypes.java index 1e68bf47d2d8e..1602d72bf0036 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/afterExpectedTypes.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/afterExpectedTypes.java @@ -1,14 +1,13 @@ // "Create field 'panel'" "true" -import javax.swing.*; +import java.io.*; class Test { - private JPanel panel; + private File panel; - void foo(JPanel container) { + Object foo(File container) { if (panel == null) { - panel = new JPanel(); - panel.setOpaque(true); - container.add(panel); + panel = new File(); + return new File(container, panel.getName()); } } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/beforeExpectedTypes.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/beforeExpectedTypes.java index a57e165c43178..07f6d513206d3 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/beforeExpectedTypes.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createFieldFromUsage/beforeExpectedTypes.java @@ -1,12 +1,11 @@ // "Create field 'panel'" "true" -import javax.swing.*; +import java.io.*; class Test { - void foo(JPanel container) { + Object foo(File container) { if (panel == null) { - panel = new JPanel(); - panel.setOpaque(true); - container.add(panel); + panel = new File(); + return new File(container, panel.getName()); } } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java index 441ab889b797d..bda1de0fc8f97 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/after8.java @@ -1,6 +1,4 @@ // "Create inner class 'MyTableModel'" "true" -import javax.swing.*; -import javax.swing.table.TableModel; public class Test { public static void main() { @@ -9,4 +7,8 @@ public static void main() { private static class MyTableModel implements TableModel { } -} \ No newline at end of file +} +class JTable { + JTable(TableModel t) {} +} +interface TableModel {} \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/before8.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/before8.java index b4f27a4a75fe8..c998739c387a8 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/before8.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createInnerClassFromNew/before8.java @@ -1,8 +1,11 @@ // "Create inner class 'MyTableModel'" "true" -import javax.swing.*; public class Test { public static void main() { JTable table = new JTable(new MyTableModel()); } -} \ No newline at end of file +} +class JTable { + JTable(TableModel t) {} +} +interface TableModel {} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/AnonInner.java b/java/java-tests/testData/refactoring/extractMethod/AnonInner.java index 34a32465f82e0..6431f5b2c48f7 100644 --- a/java/java-tests/testData/refactoring/extractMethod/AnonInner.java +++ b/java/java-tests/testData/refactoring/extractMethod/AnonInner.java @@ -1,7 +1,4 @@ -import javax.swing.*; -import java.awt.event.ActionEvent; - public class ExtractMethods { } abstract class MyButton extends JButton @@ -13,9 +10,15 @@ protected MyButton( String text ) { class Foo { private JButton createOKButton() { return new MyButton( "OK" ) { - public void actionPerformed( ActionEvent e ) { + public void actionPerformed( int e ) { setVisible( false ); } }; } } + +class JButton { + public JButton(String text) { + } + public void setVisible(boolean b) {} +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/AnonInner_after.java b/java/java-tests/testData/refactoring/extractMethod/AnonInner_after.java index c63341f6dc46f..86c3f649be03a 100644 --- a/java/java-tests/testData/refactoring/extractMethod/AnonInner_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/AnonInner_after.java @@ -1,7 +1,4 @@ -import javax.swing.*; -import java.awt.event.ActionEvent; - public class ExtractMethods { } abstract class MyButton extends JButton @@ -13,7 +10,7 @@ protected MyButton( String text ) { class Foo { private JButton createOKButton() { return new MyButton( "OK" ) { - public void actionPerformed( ActionEvent e ) { + public void actionPerformed( int e ) { newMethod(); } @@ -23,3 +20,9 @@ private void newMethod() { }; } } + +class JButton { + public JButton(String text) { + } + public void setVisible(boolean b) {} +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/ArrayAccess1_after.java b/java/java-tests/testData/refactoring/extractMethod/ArrayAccess1_after.java index 1203bc98f7c24..a7148c29d7388 100644 --- a/java/java-tests/testData/refactoring/extractMethod/ArrayAccess1_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/ArrayAccess1_after.java @@ -7,8 +7,8 @@ void foo(String[] ss, String[] bb) { } } - private void newMethod(String s, String x) { + private void newMethod(String s, String s1) { System.out.println(s); - System.out.println(x); + System.out.println(s1); } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/ExtractUnresolvedLambdaExpression_after.java b/java/java-tests/testData/refactoring/extractMethod/ExtractUnresolvedLambdaExpression_after.java index 668bc271b59d6..4e179290fe530 100644 --- a/java/java-tests/testData/refactoring/extractMethod/ExtractUnresolvedLambdaExpression_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/ExtractUnresolvedLambdaExpression_after.java @@ -1,3 +1,5 @@ +import org.jetbrains.annotations.NotNull; + import java.util.function.Supplier; class Test { @@ -6,6 +8,7 @@ private void a() b(newMethod()); } + @NotNull private Supplier newMethod() { return (s) -> { System.out.println(s); diff --git a/java/java-tests/testData/refactoring/extractMethod/FoldedWithNestedExpressions_after.java b/java/java-tests/testData/refactoring/extractMethod/FoldedWithNestedExpressions_after.java index 3c28513617cfc..4cc18b440aff7 100644 --- a/java/java-tests/testData/refactoring/extractMethod/FoldedWithNestedExpressions_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/FoldedWithNestedExpressions_after.java @@ -4,8 +4,8 @@ void h(int i, String[] s, String[] t) { System.out.println(s1); } - private String newMethod(String x, String s) { - System.out.println(x); - return s; + private String newMethod(String s, String s2) { + System.out.println(s2); + return s2; } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureSameParamNames_after.java b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureSameParamNames_after.java index 47d1ed9ed8c6d..d2665950376c2 100644 --- a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureSameParamNames_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureSameParamNames_after.java @@ -7,9 +7,9 @@ public class Test { newMethod(x, 3, 4); } - private void newMethod(int x, int x2, int x3) { - System.out.println(x2); - System.out.println(x3); + private void newMethod(int x, int i, int i2) { + System.out.println(i); + System.out.println(i2); System.out.println(x); } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithChangedParameterName_after.java b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithChangedParameterName_after.java index b3e5880154f3b..a30130b8df81c 100644 --- a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithChangedParameterName_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithChangedParameterName_after.java @@ -9,8 +9,8 @@ public class Test { newMethod(x, x + 2); } - private void newMethod(int p, int x) { + private void newMethod(int p, int i) { System.out.println(p); - System.out.println(x); + System.out.println(i); } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithFolding_after.java b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithFolding_after.java index 3c20ee9cc49a6..5ce16f25514ee 100644 --- a/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithFolding_after.java +++ b/java/java-tests/testData/refactoring/extractMethod/SuggestChangeSignatureWithFolding_after.java @@ -4,7 +4,7 @@ public static void main(String[] args, int i) { newMethod("world, " + args[i]); } - private static void newMethod(String x) { - System.out.println(x); + private static void newMethod(String s) { + System.out.println(s); } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java b/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java index fd9de11baf1f5..12e53ce5b3e20 100644 --- a/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java +++ b/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java @@ -1,10 +1,13 @@ -import java.awt.event.*; class A { private ActionListener b = new Inner(); private class Inner implements ActionListener { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(int e) { } } +} +interface ActionListener { + public void actionPerformed(int e); + } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java.after b/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java.after index c59ba2b240067..9f32992f906c3 100644 --- a/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java.after +++ b/java/java-tests/testData/refactoring/inlineToAnonymousClass/ImplementsInterface.java.after @@ -1,9 +1,12 @@ -import java.awt.event.*; class A { private ActionListener b = new ActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(int e) { } }; +} +interface ActionListener { + public void actionPerformed(int e); + } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java b/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java index 858459a551159..16c2735226e51 100644 --- a/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java +++ b/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java @@ -1,4 +1,3 @@ -import java.awt.event.*; class A { private ActionListener b = new Inner(); @@ -7,7 +6,11 @@ private abstract class MyActionListener implements ActionListener { } private class Inner extends MyActionListener implements ActionListener { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(int e) { } } +} +interface ActionListener { + public void actionPerformed(int e); + } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java.after b/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java.after index 7505f7843e3b8..f42afc0b0a1df 100644 --- a/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java.after +++ b/java/java-tests/testData/refactoring/inlineToAnonymousClass/RedundantImplementsInterface.java.after @@ -1,12 +1,15 @@ -import java.awt.event.*; class A { private ActionListener b = new MyActionListener() { - public void actionPerformed(ActionEvent e) { + public void actionPerformed(int e) { } }; private abstract class MyActionListener implements ActionListener { } +} +interface ActionListener { + public void actionPerformed(int e); + } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceField/after1.java b/java/java-tests/testData/refactoring/introduceField/after1.java index 033edeaac1661..7773423f553d1 100644 --- a/java/java-tests/testData/refactoring/introduceField/after1.java +++ b/java/java-tests/testData/refactoring/introduceField/after1.java @@ -1,8 +1,8 @@ class InStaticInitializer { - public static final String x = "Hello World"; + public static final String s = "Hello World"; static { - System.out.println(x); + System.out.println(s); } //Field must be placed before initializer or illegal forward reference will happen } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/makeMethodStatic/after20.java b/java/java-tests/testData/refactoring/makeMethodStatic/after20.java index e650a46f6ef33..191f66da6b40f 100644 --- a/java/java-tests/testData/refactoring/makeMethodStatic/after20.java +++ b/java/java-tests/testData/refactoring/makeMethodStatic/after20.java @@ -1,6 +1,3 @@ -import javax.swing.*; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; final class Bug extends JFrame { @@ -14,7 +11,15 @@ public static void foo(Bug anObject) { private class MyWindowListener extends WindowAdapter { - public void windowActivated(WindowEvent e) { + public void windowActivated(int e) { + } + } +} + +class JFrame { + public void addWindowListener(WindowAdapter e) {} + static class WindowAdapter { + public void windowActivated(int e) { } } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/makeMethodStatic/before20.java b/java/java-tests/testData/refactoring/makeMethodStatic/before20.java index 7e31c82738327..2d648b44266f0 100644 --- a/java/java-tests/testData/refactoring/makeMethodStatic/before20.java +++ b/java/java-tests/testData/refactoring/makeMethodStatic/before20.java @@ -1,6 +1,3 @@ -import javax.swing.*; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; final class Bug extends JFrame { @@ -14,7 +11,15 @@ public Bug() { private class MyWindowListener extends WindowAdapter { - public void windowActivated(WindowEvent e) { + public void windowActivated(int e) { + } + } +} + +class JFrame { + public void addWindowListener(WindowAdapter e) {} + static class WindowAdapter { + public void windowActivated(int e) { } } } \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java b/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java index 8ebd4a7e1c410..21c271429ba2f 100644 --- a/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java +++ b/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java @@ -1,5 +1,3 @@ -import java.awt.Component; -import javax.swing.JComponent; import java.util.ArrayList; import java.util.List; @@ -12,3 +10,5 @@ public void context() { Object o = list.get(0); } } +class JComponent extends Component {} +class Component {} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java.after b/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java.after index 94d7e5285f9cf..1dbfa8673c0eb 100644 --- a/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java.after +++ b/java/java-tests/testData/refactoring/methodDuplicates/TypesGenericsConcrete2Super.java.after @@ -1,5 +1,3 @@ -import java.awt.Component; -import javax.swing.JComponent; import java.util.ArrayList; import java.util.List; @@ -12,3 +10,5 @@ class Types { method(list); } } +class JComponent extends Component {} +class Component {} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java b/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java index 8e37f928e7e26..4087126f034ad 100644 --- a/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java +++ b/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java @@ -1,10 +1,10 @@ -import static javax.swing.SwingConstants.BOTTOM; +import static java.io.File.separatorChar; public class RenameCollisions { public static class StaticInnerClass { public static void staticContext() { int localVar = 0; - int var1 = BOTTOM; + int var1 = separatorChar; } } } diff --git a/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java.after b/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java.after index 6260732fe5016..3aa760e143ce4 100644 --- a/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java.after +++ b/java/java-tests/testData/refactoring/renameCollisions/RenameVarLocalToAlien.java.after @@ -1,10 +1,10 @@ -import javax.swing.*; +import java.io.File; public class RenameCollisions { public static class StaticInnerClass { public static void staticContext() { - int BOTTOM = 0; - int var1 = SwingConstants.BOTTOM; + int separatorChar = 0; + int var1 = File.separatorChar; } } } diff --git a/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java b/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java index 0aaf16e62546b..3014c60311be9 100644 --- a/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java +++ b/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java @@ -1,9 +1,9 @@ -import static javax.swing.SwingConstants.BOTTOM; +import static java.io.File.separatorChar; public class RenameCollisions { public static class StaticInnerClass { public static void staticContext(int param) { - int var1 = BOTTOM; + int var1 = separatorChar; } } } diff --git a/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java.after b/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java.after index 17f66c77a1948..a99314659cbe1 100644 --- a/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java.after +++ b/java/java-tests/testData/refactoring/renameCollisions/RenameVarParamToAlien.java.after @@ -1,9 +1,9 @@ -import javax.swing.*; +import java.io.File; public class RenameCollisions { public static class StaticInnerClass { - public static void staticContext(int BOTTOM) { - int var1 = SwingConstants.BOTTOM; + public static void staticContext(int separatorChar) { + int var1 = File.separatorChar; } } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java index 76a517c4e176a..ad5ffe02031c9 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java @@ -22,10 +22,8 @@ import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.LanguageLevelProjectExtension; -import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.GenericsUtil; -import com.intellij.psi.PsiClass; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiType; import com.intellij.psi.search.GlobalSearchScope; @@ -589,15 +587,6 @@ public void testLeastUpperBoundWithRecursiveTypes() throws Exception { assertEquals("Number & Comparable>", leastUpperBound.getPresentableText()); } - public void testJavaUtilCollections_NoVerify() throws Exception { - PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule())); - assertNotNull(collectionsClass); - collectionsClass = (PsiClass)collectionsClass.getNavigationElement(); - final String text = collectionsClass.getContainingFile().getText(); - configureFromFileText("Collections.java", StringUtil.convertLineSeparators(StringUtil.replace(text, "package java.util;", "package java.utilx; import java.util.*;"))); - doTestConfiguredFile(false, false, null); - } - public void testReturnTypeSubstitutableForSameOverrideEquivalentMethods() throws Exception { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java index 07078dc5868cf..12d72c9ed2469 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/HighlightStressTest.java @@ -221,7 +221,8 @@ public void testRandomEditingForUnused() throws Exception { final StringBuilder imports = new StringBuilder(); final StringBuilder usages = new StringBuilder(); int v = 0; - List aclasses = new ArrayList<>(); + List aClasses = new ArrayList<>(); + outer: for (String name : names) { PsiClass[] classes = cache.getClassesByName(name, GlobalSearchScope.allScope(getProject())); if (classes.length == 0) continue; @@ -229,12 +230,17 @@ public void testRandomEditingForUnused() throws Exception { if (!aClass.hasModifierProperty(PsiModifier.PUBLIC)) continue; if (aClass.getSuperClass() == null) continue; PsiClassType[] superTypes = aClass.getSuperTypes(); - if (superTypes.length == 0 || superTypes[0].resolve() == null) continue; + if (superTypes.length == 0) continue; + for (PsiClassType superType : superTypes) { + PsiClass superClass = superType.resolve(); + if (superClass == null || !superClass.hasModifierProperty(PsiModifier.PUBLIC)) continue outer; + } String qualifiedName = aClass.getQualifiedName(); if (qualifiedName.startsWith("java.lang.invoke")) continue; // java.lang.invoke.MethodHandle has weird access attributes in recent rt.jar which causes spurious highlighting errors + if ("Sink".equals(aClass.getName())) continue; imports.append("import " + qualifiedName + ";\n"); usages.append("/**/ "+aClass.getName() + " var" + v + " = null; var" + v + ".toString();\n"); - aclasses.add(aClass); + aClasses.add(aClass); v++; if (v>100) break; } @@ -278,7 +284,7 @@ public void visitElement(PsiElement element) { } }); - System.out.println("i = " + i + " " + next + " at "+offset); + //System.out.println("i = " + i + " " + next + " at "+offset); List infos = doHighlighting(); errors = DaemonAnalyzerTestCase.filter(infos, HighlightSeverity.ERROR); @@ -290,6 +296,4 @@ public void visitElement(PsiElement element) { } FileEditorManagerEx.getInstanceEx(getProject()).closeAllFiles(); } - - } 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 e29a3ebf30813..c7611febe7f08 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java @@ -30,8 +30,13 @@ import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.extensions.Extensions; import com.intellij.openapi.projectRoots.JavaSdkVersion; +import com.intellij.openapi.projectRoots.Sdk; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.pom.java.LanguageLevel; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiElement; +import com.intellij.psi.search.GlobalSearchScope; import com.intellij.testFramework.IdeaTestUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; @@ -49,6 +54,11 @@ protected void setUp() throws Exception { IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_7, getModule(), getTestRootDisposable()); } + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk17(); // has to have src.zip and weird method handle signatures + } + private void doTest(boolean checkWarnings, boolean checkInfos, InspectionProfileEntry... inspections) { enableInspectionTools(inspections); doTest(BASE_PATH + "/" + getTestName(false) + ".java", checkWarnings, checkInfos); @@ -170,4 +180,14 @@ public void testDynamicallyAddIgnoredAnnotations() { public void testUncheckedExtendedWarnings() { doTest(true, false); } public void testInaccessibleInferredTypeForVarargsArgument() { doTest(false, false);} public void testRuntimeClassCast() { doTest(true, false);} + + public void testJavaUtilCollections_NoVerify() throws Exception { + PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule())); + assertNotNull(collectionsClass); + collectionsClass = (PsiClass)collectionsClass.getNavigationElement(); + assertTrue(!(collectionsClass instanceof PsiCompiledElement)); + final String text = collectionsClass.getContainingFile().getText(); + configureFromFileText("Collections.java", StringUtil.convertLineSeparators(StringUtil.replace(text, "package java.util;", "package java.utilx; import java.util.*;"))); + doTestConfiguredFile(false, false, null); + } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java index 1f2f0a821c11c..ecfd1e7976ee7 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingPerformanceTest.java @@ -24,15 +24,15 @@ import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.util.Disposer; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.impl.source.tree.injected.JavaConcatenationInjectorManager; +import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.PlatformTestUtil; import com.intellij.testFramework.SkipSlowTestLocally; import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl; -import com.intellij.util.ThrowableRunnable; -import java.util.ArrayList; import java.util.List; @SkipSlowTestLocally @@ -51,6 +51,11 @@ protected void setUp() throws Exception { PathManagerEx.getTestDataPath(); // to cache stuff } + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk17(); // has to have awt + } + @Override protected void tearDown() throws Exception { Disposer.dispose(my); @@ -101,12 +106,9 @@ private List startTest(int maxMillis) { getFile().getText(); //to load text CodeInsightTestFixtureImpl.ensureIndexesUpToDate(getProject()); - final List infos = new ArrayList(); PlatformTestUtil.startPerformanceTest(getTestName(false), maxMillis, () -> { - infos.clear(); DaemonCodeAnalyzer.getInstance(getProject()).restart(); - List h = doHighlighting(); - infos.addAll(h); + doHighlighting(); }).cpuBound().usesAllCPUCores().useLegacyScaling().assertTiming(); return highlightErrors(); diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java index 8048bbfaaff82..aa75ed1b26286 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java @@ -39,9 +39,12 @@ import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; +import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.extensions.ExtensionPoint; import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.projectRoots.JavaSdkVersion; import com.intellij.openapi.roots.LanguageLevelProjectExtension; @@ -54,6 +57,8 @@ import com.intellij.psi.xml.XmlToken; import com.intellij.psi.xml.XmlTokenType; import com.intellij.testFramework.IdeaTestUtil; +import com.intellij.testFramework.VfsTestUtil; +import com.intellij.util.ui.UIUtil; import org.jdom.Element; import org.jetbrains.annotations.NotNull; @@ -161,7 +166,42 @@ public void testSillyAssignment() { public void testDeprecated() { doTest(true, false); } public void testJavadoc() { enableInspectionTool(new JavaDocLocalInspection()); doTest(true, false); } public void testExpressionsInSwitch () { doTest(false, false); } - public void testAccessInner () { doTest(false, false); } + public void testAccessInner() throws IOException { + Editor e = createSaveAndOpenFile("x/BeanContextServicesSupport.java", + "" + + "package x;\n" + + "public class BeanContextServicesSupport {" + + " protected class BCSSChild {" + + " class BCSSCServiceClassRef {" + + " void addRequestor(Object requestor) {" + + " }" + + " }" + + " }" + + "}"); + Editor e2 = createSaveAndOpenFile("x/Component.java", + "" + + "package x;\n" + + "public class Component {" + + " protected class FlipBufferStrategy {" + + " protected int numBuffers;" + + " protected void createBuffers(int numBuffers){}" + + " }" + + "}"); + try { + UIUtil.dispatchAllInvocationEvents(); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + doTest(false, false); + } + finally { + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + VirtualFile file = FileDocumentManager.getInstance().getFile(e.getDocument()); + FileEditorManager.getInstance(getProject()).closeFile(file); + VfsTestUtil.deleteFile(file); + VirtualFile file2 = FileDocumentManager.getInstance().getFile(e2.getDocument()); + FileEditorManager.getInstance(getProject()).closeFile(file2); + VfsTestUtil.deleteFile(file2); + } + } public void testExceptionNeverThrown() { doTest(true, false); } public void testExceptionNeverThrownInTry() { doTest(false, false); } @@ -173,7 +213,12 @@ public void testSillyAssignment() { public void testExtendMultipleClasses() { doTest(false, false); } public void testRecursiveConstructorInvocation() { doTest(false, false); } public void testMethodCalls() { doTest(false, false); } - public void testSingleTypeImportConflicts() { doTest(false, false); } + public void testSingleTypeImportConflicts() throws IOException { + createSaveAndOpenFile("sql/Date.java", "package sql; public class Date{}"); + UIUtil.dispatchAllInvocationEvents(); + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + doTest(false, false); + } public void testMultipleSingleTypeImports() { doTest(true, false); } //duplicate imports public void testNotAllowedInInterface() { doTest(false, false); } public void testQualifiedNew() { doTest(false, false); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/CreateFieldFromUsageTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/CreateFieldFromUsageTest.java index 35ffeb5a4990b..63309d6e21836 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/CreateFieldFromUsageTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/CreateFieldFromUsageTest.java @@ -20,9 +20,12 @@ import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; +import com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.annotations.NotNull; /** @@ -63,7 +66,8 @@ protected void run(@NotNull Result result) throws Exception { PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); } }.execute(); - + PsiClass aClass = JavaPsiFacade.getInstance(getProject()).findClass("foo.Foo", GlobalSearchScope.allScope(getProject())); + assertNotNull(aClass); doSingleTest(); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java index ff25480f187a7..c7d5e16b83737 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java @@ -119,7 +119,7 @@ public void testRenameVarInnerFieldToOuterField() throws Exception { } public void testRenameVarLocalToAlien() throws Exception { - doTest("BOTTOM"); + doTest("separatorChar"); } public void testRenameVarLocalToConst() throws Exception { @@ -151,7 +151,7 @@ public void testRenameVarOuterFieldToParam() throws Exception { } public void testRenameVarParamToAlien() throws Exception { - doTest("BOTTOM"); + doTest("separatorChar"); } public void testRenameVarParamToField() throws Exception { diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java index 8bf3fc3f76f08..f2bc5e06286ad 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineConstantFieldTest.java @@ -2,8 +2,10 @@ import com.intellij.JavaTestUtil; import com.intellij.codeInsight.TargetElementUtil; +import com.intellij.openapi.projectRoots.Sdk; import com.intellij.psi.*; import com.intellij.refactoring.LightRefactoringTestCase; +import com.intellij.testFramework.IdeaTestUtil; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; @@ -14,6 +16,11 @@ protected String getTestDataPath() { return JavaTestUtil.getJavaTestDataPath(); } + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk17(); // has to have src.zip + } + public void testQualifiedExpression() throws Exception { doTest(); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java index dfae3086b5055..57bb07abd2258 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java @@ -19,12 +19,14 @@ import com.intellij.codeInsight.TargetElementUtil; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; +import com.intellij.openapi.projectRoots.Sdk; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiLocalVariable; import com.intellij.psi.PsiReference; import com.intellij.psi.PsiReferenceExpression; import com.intellij.refactoring.RefactoringBundle; +import com.intellij.testFramework.IdeaTestUtil; import com.intellij.testFramework.LightCodeInsightTestCase; import org.jetbrains.annotations.NotNull; @@ -62,6 +64,11 @@ public void testIdeaDEV9404 () throws Exception { doTest(false); } + @Override + protected Sdk getProjectJDK() { + return IdeaTestUtil.getMockJdk17(); // there is JPanel inside + } + public void testIDEADEV12244 () throws Exception { doTest(false); } diff --git a/java/testFramework/src/com/intellij/testFramework/LightCodeInsightTestCase.java b/java/testFramework/src/com/intellij/testFramework/LightCodeInsightTestCase.java index 54be2cbd38210..1e8dd7535e1be 100644 --- a/java/testFramework/src/com/intellij/testFramework/LightCodeInsightTestCase.java +++ b/java/testFramework/src/com/intellij/testFramework/LightCodeInsightTestCase.java @@ -47,7 +47,7 @@ protected static void setLanguageLevel(final LanguageLevel level) { @Override protected Sdk getProjectJDK() { - return IdeaTestUtil.getMockJdk17(); + return IdeaTestUtil.getMockJdk18(); } @NotNull diff --git a/java/typeMigration/testData/intentions/longAdder/afterWithZeroIntInitializer.java b/java/typeMigration/testData/intentions/longAdder/afterWithZeroIntInitializer.java index 28c342dea1ee1..241aca9dc0f7a 100644 --- a/java/typeMigration/testData/intentions/longAdder/afterWithZeroIntInitializer.java +++ b/java/typeMigration/testData/intentions/longAdder/afterWithZeroIntInitializer.java @@ -1,8 +1,9 @@ // "Convert variable to 'java.util.concurrent.atomic.LongAdder'" "true" +import java.util.concurrent.atomic.LongAdder; public class Main10 { void m() { - java.util.concurrent.atomic.LongAdder i = new java.util.concurrent.atomic.LongAdder(); + LongAdder i = new LongAdder(); i.increment(); diff --git a/java/typeMigration/testData/intentions/longAdder/afterWithZeroLongInitializer.java b/java/typeMigration/testData/intentions/longAdder/afterWithZeroLongInitializer.java index 06d53f4f0efa1..6771e02752ca6 100644 --- a/java/typeMigration/testData/intentions/longAdder/afterWithZeroLongInitializer.java +++ b/java/typeMigration/testData/intentions/longAdder/afterWithZeroLongInitializer.java @@ -1,8 +1,9 @@ // "Convert variable to 'java.util.concurrent.atomic.LongAdder'" "true" +import java.util.concurrent.atomic.LongAdder; public class Main10 { void m() { - java.util.concurrent.atomic.LongAdder l = new java.util.concurrent.atomic.LongAdder(); + LongAdder l = new LongAdder(); l.decrement(); diff --git a/java/typeMigration/testData/intentions/longAdder/afterWithoutInitializer.java b/java/typeMigration/testData/intentions/longAdder/afterWithoutInitializer.java index aebc8553e97c7..29cd558668eb9 100644 --- a/java/typeMigration/testData/intentions/longAdder/afterWithoutInitializer.java +++ b/java/typeMigration/testData/intentions/longAdder/afterWithoutInitializer.java @@ -1,8 +1,9 @@ // "Convert variable to 'java.util.concurrent.atomic.LongAdder'" "true" +import java.util.concurrent.atomic.LongAdder; public class Main10 { void m() { - java.util.concurrent.atomic.LongAdder l = new java.util.concurrent.atomic.LongAdder(); + LongAdder l = new LongAdder(); String asString = l.toString(); diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index d67c4d4653843..b89f8d49c509a 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -150,18 +150,6 @@ protected static Document configureFromFileText(@NonNls @NotNull final String fi return new WriteCommandAction(null) { @Override protected void run(@NotNull Result result) throws Throwable { - if (myVFile != null) { - // avoid messing with invalid files, in case someone calls configureXXX() several times - PsiDocumentManager.getInstance(ourProject).commitAllDocuments(); - FileEditorManager.getInstance(ourProject).closeFile(myVFile); - try { - myVFile.delete(this); - } - catch (IOException e) { - LOG.error(e); - } - myVFile = null; - } final Document fakeDocument = new DocumentImpl(fileText); EditorTestUtil.CaretAndSelectionState caretsState = EditorTestUtil.extractCaretAndSelectionMarkers(fakeDocument); @@ -216,22 +204,37 @@ private static Document setupFileEditorAndDocument(@NotNull String fileName, @No EncodingProjectManager.getInstance(ProjectManager.getInstance().getDefaultProject()).setEncoding(null, CharsetToolkit.UTF8_CHARSET); PostprocessReformattingAspect.getInstance(ourProject).doPostponedFormatting(); deleteVFile(); - myVFile = getSourceRoot().createChildData(null, fileName); - VfsUtil.saveText(myVFile, fileText); - final FileDocumentManager manager = FileDocumentManager.getInstance(); - final Document document = manager.getDocument(myVFile); - assertNotNull("Can't create document for '" + fileName + "'", document); - manager.reloadFromDisk(document); - document.insertString(0, " "); - document.deleteString(0, 1); + + myEditor = createSaveAndOpenFile(fileName, fileText); + myVFile = FileDocumentManager.getInstance().getFile(myEditor.getDocument()); myFile = getPsiManager().findFile(myVFile); - assertNotNull("Can't create PsiFile for '" + fileName + "'. Unknown file type most probably.", myFile); - assertTrue(myFile.isPhysical()); - myEditor = createEditor(myVFile); - myVFile.setCharset(CharsetToolkit.UTF8_CHARSET); - PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); - return document; + return myEditor.getDocument(); + } + + @NotNull + protected static Editor createSaveAndOpenFile(@NotNull String relativePath, @NotNull String fileText) throws IOException { + return WriteCommandAction.runWriteCommandAction(getProject(), new ThrowableComputable() { + @Override + public Editor compute() throws IOException { + VirtualFile myVFile = VfsTestUtil.createFile(getSourceRoot(),relativePath); + VfsUtil.saveText(myVFile, fileText); + final FileDocumentManager manager = FileDocumentManager.getInstance(); + final Document document = manager.getDocument(myVFile); + assertNotNull("Can't create document for '" + relativePath + "'", document); + manager.reloadFromDisk(document); + document.insertString(0, " "); + document.deleteString(0, 1); + PsiFile myFile = getPsiManager().findFile(myVFile); + assertNotNull("Can't create PsiFile for '" + relativePath + "'. Unknown file type most probably.", myFile); + assertTrue(myFile.isPhysical()); + Editor myEditor = createEditor(myVFile); + myVFile.setCharset(CharsetToolkit.UTF8_CHARSET); + + PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); + return myEditor; + } + }); } private static void setupEditorForInjectedLanguage() { @@ -255,6 +258,10 @@ private static void deleteVFile() throws IOException { ApplicationManager.getApplication().runWriteAction(new ThrowableComputable() { @Override public Void compute() throws IOException { + // avoid messing with invalid files, in case someone calls configureXXX() several times + PsiDocumentManager.getInstance(ourProject).commitAllDocuments(); + FileEditorManager.getInstance(ourProject).closeFile(myVFile); + myVFile.delete(this); return null; } From e01291e91c6528d3a36e33b4f086cb10b1712d4b Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 20 Jul 2016 15:53:59 +0300 Subject: [PATCH 15/67] IDEA-145540 revert changes because of IDEA-158759 --- .../wm/impl/commands/RequestFocusInToolWindowCmd.java | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java index acc83f362be01..a274e91f9fd30 100644 --- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java +++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java @@ -28,14 +28,11 @@ import com.intellij.openapi.wm.impl.WindowManagerImpl; import com.intellij.openapi.wm.impl.WindowWatcher; import com.intellij.util.Alarm; -import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; -import static com.intellij.openapi.wm.ToolWindowType.WINDOWED; - /** * Requests focus for the specified tool window. * @@ -156,13 +153,6 @@ public void run() { return; } if (c.isShowing()) { - if (WINDOWED == myToolWindow.getType()) { - Window window = UIUtil.getWindow(c); - if (window instanceof Frame) { - Frame frame = (Frame)window; - frame.setState(Frame.NORMAL); - } - } final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner(); if (owner != null && owner == c) { myManager.getFocusManager().requestFocus(new FocusCommand() { From 2e9a30ee5874b48403cea2cde6d7563708332d24 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Wed, 20 Jul 2016 14:54:40 +0200 Subject: [PATCH 16/67] Cleanup (formatting) --- .../application/PermanentInstallationID.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java b/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java index 8eab31d0a9e3d..44c3c094a1a53 100644 --- a/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java +++ b/platform/platform-impl/src/com/intellij/openapi/application/PermanentInstallationID.java @@ -17,6 +17,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.io.FileUtilRt; +import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.CharsetToolkit; import org.jetbrains.annotations.NotNull; @@ -32,6 +33,7 @@ public class PermanentInstallationID { private static final String INSTALLATION_ID_KEY = "user_id_on_machine"; private static final String INSTALLATION_ID = calculateInstallationId(); + @NotNull public static String get() { return INSTALLATION_ID; } @@ -42,8 +44,8 @@ private static String calculateInstallationId() { final Preferences prefs = Preferences.userRoot().node("jetbrains"); String installationId = prefs.get(INSTALLATION_ID_KEY, null); - if (installationId == null || installationId.isEmpty()) { - installationId = oldValue != null && !oldValue.isEmpty() ? oldValue : UUID.randomUUID().toString(); + if (StringUtil.isEmpty(installationId)) { + installationId = !StringUtil.isEmpty(oldValue) ? oldValue : UUID.randomUUID().toString(); prefs.put(INSTALLATION_ID_KEY, installationId); } @@ -69,8 +71,7 @@ private static String calculateInstallationId() { writeToFile(permanentIdFile, installationId); } } - catch (IOException ignored) { - } + catch (IOException ignored) { } } } } @@ -85,25 +86,16 @@ private static String calculateInstallationId() { @NotNull private static String loadFromFile(@NotNull File file) throws IOException { - final FileInputStream is = new FileInputStream(file); - try { + try (FileInputStream is = new FileInputStream(file)) { final byte[] bytes = FileUtilRt.loadBytes(is); final int offset = CharsetToolkit.hasUTF8Bom(bytes) ? CharsetToolkit.UTF8_BOM.length : 0; return new String(bytes, offset, bytes.length - offset, CharsetToolkit.UTF8_CHARSET); } - finally { - is.close(); - } } private static void writeToFile(@NotNull File file, @NotNull String text) throws IOException { - final DataOutputStream stream = new DataOutputStream(new FileOutputStream(file)); - try { + try (DataOutputStream stream = new DataOutputStream(new FileOutputStream(file))) { stream.write(text.getBytes(CharsetToolkit.UTF8_CHARSET)); } - finally { - stream.close(); - } } - -} +} \ No newline at end of file From bb374505a43575dbddc6c72f9d03b7459e0c946a Mon Sep 17 00:00:00 2001 From: Nadya Zabrodina Date: Wed, 20 Jul 2016 15:58:36 +0300 Subject: [PATCH 17/67] [vcs]: IDEA-158645 do not notify about Unregistered Excluded directories; cleanUp --- .../vcs/roots/VcsRootProblemNotifier.java | 54 ++++++------------- 1 file changed, 17 insertions(+), 37 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootProblemNotifier.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootProblemNotifier.java index 3722aefcb7ab8..5438364993877 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootProblemNotifier.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootProblemNotifier.java @@ -21,7 +21,7 @@ import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.project.Project; -import com.intellij.openapi.util.Condition; +import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.*; @@ -29,6 +29,7 @@ import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Function; +import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import com.intellij.vcsUtil.VcsUtil; @@ -44,22 +45,16 @@ /** * Searches for Vcs roots problems via {@link VcsRootErrorsFinder} and notifies about them. - * - * @author Nadya Zabrodina */ public class VcsRootProblemNotifier { - public static final Function PATH_FROM_ROOT_ERROR = new Function() { - @Override - public String fun(@NotNull VcsRootError error) { - return error.getMapping(); - } - }; + public static final Function PATH_FROM_ROOT_ERROR = VcsRootError::getMapping; @NotNull private final Project myProject; @NotNull private final VcsConfiguration mySettings; @NotNull private final ProjectLevelVcsManager myVcsManager; @NotNull private final ChangeListManager myChangeListManager; + @NotNull private final ProjectFileIndex myProjectFileIndex; @NotNull private final Set myReportedUnregisteredRoots; @@ -74,6 +69,7 @@ private VcsRootProblemNotifier(@NotNull Project project) { myProject = project; mySettings = VcsConfiguration.getInstance(myProject); myChangeListManager = ChangeListManager.getInstance(project); + myProjectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject); myVcsManager = ProjectLevelVcsManager.getInstance(project); myReportedUnregisteredRoots = new HashSet(mySettings.IGNORED_UNREGISTERED_ROOTS); } @@ -110,26 +106,21 @@ public void rescanAndNotifyIfNeeded() { } private boolean isUnderOrAboveProjectDir(@NotNull String mapping) { - String projectDir = myProject.getBasePath(); + String projectDir = ObjectUtils.assertNotNull(myProject.getBasePath()); return mapping.equals(VcsDirectoryMapping.PROJECT_CONSTANT) || FileUtil.isAncestor(projectDir, mapping, false) || FileUtil.isAncestor(mapping, projectDir, false); } - private boolean isIgnored(@NotNull String mapping) { + private boolean isIgnoredOrExcluded(@NotNull String mapping) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(mapping); - return file != null && myChangeListManager.isIgnoredFile(file); + return file != null && (myChangeListManager.isIgnoredFile(file) || myProjectFileIndex.isExcluded(file)); } private void expireNotification() { if (myNotification != null) { final Notification notification = myNotification; - ApplicationManager.getApplication().invokeLater(new Runnable() { - @Override - public void run() { - notification.expire(); - } - }); + ApplicationManager.getApplication().invokeLater(notification::expire); myNotification = null; } @@ -144,14 +135,11 @@ private Collection scan() { @NotNull private static String makeDescription(@NotNull Collection unregisteredRoots, @NotNull Collection invalidRoots) { - Function rootToDisplayableString = new Function() { - @Override - public String fun(VcsRootError rootError) { - if (rootError.getMapping().equals(VcsDirectoryMapping.PROJECT_CONSTANT)) { - return StringUtil.escapeXml(rootError.getMapping()); - } - return FileUtil.toSystemDependentName(rootError.getMapping()); + Function rootToDisplayableString = rootError -> { + if (rootError.getMapping().equals(VcsDirectoryMapping.PROJECT_CONSTANT)) { + return StringUtil.escapeXml(rootError.getMapping()); } + return FileUtil.toSystemDependentName(rootError.getMapping()); }; StringBuilder description = new StringBuilder(); @@ -207,23 +195,15 @@ else if (invalidRoots.isEmpty()) { @NotNull private List getImportantUnregisteredMappings(@NotNull Collection errors) { - return ContainerUtil.filter(errors, new Condition() { - @Override - public boolean value(VcsRootError error) { - String mapping = error.getMapping(); - return error.getType() == VcsRootError.Type.UNREGISTERED_ROOT && isUnderOrAboveProjectDir(mapping) && !isIgnored(mapping); - } + return ContainerUtil.filter(errors, error -> { + String mapping = error.getMapping(); + return error.getType() == VcsRootError.Type.UNREGISTERED_ROOT && isUnderOrAboveProjectDir(mapping) && !isIgnoredOrExcluded(mapping); }); } @NotNull private static Collection getInvalidRoots(@NotNull Collection errors) { - return ContainerUtil.filter(errors, new Condition() { - @Override - public boolean value(VcsRootError error) { - return error.getType() == VcsRootError.Type.EXTRA_MAPPING; - } - }); + return ContainerUtil.filter(errors, error -> error.getType() == VcsRootError.Type.EXTRA_MAPPING); } private static class MyNotificationListener extends NotificationListener.Adapter { From 14a925e2caacb74e6b38d0ba8eed715ce5748b6e Mon Sep 17 00:00:00 2001 From: Denis Fokin Date: Wed, 20 Jul 2016 13:02:19 +0300 Subject: [PATCH 18/67] IDEA-158422 Keymap: for non-QWERTY keyboard layouts Ctrl is processed as Ctrl+Alt (Windows) or Alt (Mac OS) when combined with symbols --- .../platform-impl/src/com/intellij/ide/IdeEventQueue.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java index 885292be3d7a0..ce09b77acbe0c 100644 --- a/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java +++ b/platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java @@ -458,7 +458,7 @@ private static AWTEvent fixNonEnglishKeyboardLayouts(AWTEvent e) { else if (ke.getID() == KeyEvent.KEY_RELEASED) { switch (ke.getKeyCode()) { case KeyEvent.VK_CONTROL: - ctrlIsPressedCount--; + ctrlIsPressedCount = 0; break; case KeyEvent.VK_ALT: if (ke.getKeyLocation() == KeyEvent.KEY_LOCATION_LEFT) { @@ -495,7 +495,7 @@ else if (ke.getID() == KeyEvent.KEY_RELEASED) { // On German keyboard layout on Windows we are getting on key press // ctrl + alt instead of AltGr - int modifiers = ke.getModifiersEx() ^ InputEvent.ALT_DOWN_MASK ^ InputEvent.CTRL_DOWN_MASK; + int modifiers = ke.getModifiers() ^ InputEvent.ALT_DOWN_MASK ^ InputEvent.CTRL_DOWN_MASK; if (ctrlIsPressedCount > 1) { modifiers |= InputEvent.CTRL_DOWN_MASK; From d350ba7be2291cb0da0881424e51d978f7b6156c Mon Sep 17 00:00:00 2001 From: Pavel Dolgov Date: Wed, 20 Jul 2016 15:22:53 +0300 Subject: [PATCH 19/67] Java inspection: Converted "Expand Annotation to Normal Form" intention into an INFORMATION-level inspection. Don't offer the fix if the annotation doesn't have the 'value()' method. Added more test data. (IDEA-158456, IDEA-157727) --- .../AddAnnotationAttributeNameFix.java | 18 ++- .../src/META-INF/InspectionGadgets.xml | 4 + .../siyeh/InspectionGadgetsBundle.properties | 5 +- .../ExpandToNormalAnnotationInspection.java | 115 ++++++++++++++++++ .../ExpandToNormalAnnotation.html | 6 + .../expand_annotation}/AlreadyHasName.java | 0 .../AnnotationAttr.after.java | 8 ++ .../expand_annotation/AnnotationAttr.java | 8 ++ .../expand_annotation/ArrayAttr.after.java | 9 ++ .../style/expand_annotation/ArrayAttr.java | 9 ++ .../ArrayItemAttr.after.java | 10 ++ .../expand_annotation/ArrayItemAttr.java | 10 ++ .../IncompatibleArrayItemType.java | 9 ++ .../expand_annotation/IncompatibleType.java | 9 ++ .../expand_annotation/MultiAttr.after.java} | 0 .../style/expand_annotation}/MultiAttr.java | 0 .../expand_annotation/NameAlreadyUsed.java | 10 ++ .../style/expand_annotation/NoValueAttr.java | 10 ++ .../expand_annotation/OneAttr.after.java} | 0 .../style/expand_annotation}/OneAttr.java | 0 ...xpandToNormalAnnotationInspectionTest.java | 71 +++++++++++ .../src/META-INF/IntentionPowerPack.xml | 6 - .../siyeh/IntentionPowerPackBundle.properties | 2 - .../ExpandToNormalAnnotationIntention.java | 55 --------- .../ExpandToNormalAnnotationPredicate.java | 37 ------ .../after.java.template | 4 - .../before.java.template | 4 - .../description.html | 7 -- ...ExpandToNormalAnnotationIntentionTest.java | 45 ------- 29 files changed, 304 insertions(+), 167 deletions(-) create mode 100644 plugins/InspectionGadgets/src/com/siyeh/ig/annotation/ExpandToNormalAnnotationInspection.java create mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/ExpandToNormalAnnotation.html rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/expandToNormal => InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation}/AlreadyHasName.java (100%) create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/AnnotationAttr.after.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/AnnotationAttr.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/ArrayAttr.after.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/ArrayAttr.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/ArrayItemAttr.after.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/ArrayItemAttr.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/IncompatibleArrayItemType.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/IncompatibleType.java rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/expandToNormal/MultiAttr_after.java => InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/MultiAttr.after.java} (100%) rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/expandToNormal => InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation}/MultiAttr.java (100%) create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/NameAlreadyUsed.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/NoValueAttr.java rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/expandToNormal/OneAttr_after.java => InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation/OneAttr.after.java} (100%) rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/expandToNormal => InspectionGadgets/test/com/siyeh/igfixes/style/expand_annotation}/OneAttr.java (100%) create mode 100644 plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/ExpandToNormalAnnotationInspectionTest.java delete mode 100644 plugins/IntentionPowerPak/src/com/siyeh/ipp/annotation/ExpandToNormalAnnotationIntention.java delete mode 100644 plugins/IntentionPowerPak/src/com/siyeh/ipp/annotation/ExpandToNormalAnnotationPredicate.java delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/ExpandToNormalAnnotationIntention/after.java.template delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/ExpandToNormalAnnotationIntention/before.java.template delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/ExpandToNormalAnnotationIntention/description.html delete mode 100644 plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/annotation/ExpandToNormalAnnotationIntentionTest.java diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java index 1fee9fc5c6eed..f72211e76b8c5 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddAnnotationAttributeNameFix.java @@ -93,7 +93,8 @@ private static String buildReplacementText(@NotNull PsiNameValuePair annotationP return value != null ? name + "=" + value.getText() : name + "="; } - private static boolean isCompatibleReturnType(@Nullable PsiType expectedType, @Nullable PsiType valueType) { + public static boolean isCompatibleReturnType(@NotNull PsiMethod psiMethod, @Nullable PsiType valueType) { + final PsiType expectedType = psiMethod.getReturnType(); if (expectedType == null || valueType == null || expectedType.isAssignableFrom(valueType)) { return true; } @@ -114,10 +115,7 @@ private static Collection getAvailableAnnotationMethodNames(@NotNull Psi final PsiClass annotationClass = getAnnotationClass(parameterList); if (annotationClass != null) { - final Set usedNames = Arrays.stream(parameterList.getAttributes()) - .map(PsiNameValuePair::getName) - .filter(Objects::nonNull) - .collect(Collectors.toSet()); + final Set usedNames = getUsedAttributeNames(parameterList); final Collection availableMethods = Arrays.stream(annotationClass.getMethods()) .filter(PsiAnnotationMethod.class::isInstance) @@ -127,7 +125,7 @@ private static Collection getAvailableAnnotationMethodNames(@NotNull Psi if (!availableMethods.isEmpty()) { final PsiType valueType = CreateAnnotationMethodFromUsageFix.getAnnotationValueType(value); return availableMethods.stream() - .filter(psiMethod -> isCompatibleReturnType(psiMethod.getReturnType(), valueType)) + .filter(psiMethod -> isCompatibleReturnType(psiMethod, valueType)) .map(PsiMethod::getName) .collect(Collectors.toSet()); } @@ -137,6 +135,14 @@ private static Collection getAvailableAnnotationMethodNames(@NotNull Psi return Collections.emptyList(); } + @NotNull + public static Set getUsedAttributeNames(@NotNull PsiAnnotationParameterList parameterList) { + return Arrays.stream(parameterList.getAttributes()) + .map(PsiNameValuePair::getName) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); + } + @Nullable private static PsiClass getAnnotationClass(@NotNull PsiAnnotationParameterList parameterList) { final PsiElement parent = parameterList.getParent(); diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml index 3d44b1829183c..8beed8aedac4e 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml @@ -2564,6 +2564,10 @@ key="split.multi.catch.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.code.style.issues" enabledByDefault="true" level="INFORMATION" implementationClass="com.siyeh.ig.exceptions.SplitMultiCatchInspection"/> + Date: Wed, 20 Jul 2016 16:29:56 +0200 Subject: [PATCH 28/67] [java] fixes receiver highlighting in local classes (IDEA-158752) --- .../daemon/impl/analysis/AnnotationsHighlightUtil.java | 5 +++-- .../src/com/intellij/psi/util/ClassUtil.java | 10 +++++++--- .../annotations/receiverParameters.java | 6 ++++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java index 4cfa72706ebe4..ca0bdef14229c 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java +++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java @@ -33,6 +33,7 @@ import com.intellij.psi.impl.PsiImplUtil; import com.intellij.psi.impl.source.PsiClassReferenceType; import com.intellij.psi.impl.source.PsiImmediateClassType; +import com.intellij.psi.util.ClassUtil; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.psi.util.TypeConversionUtil; @@ -157,7 +158,7 @@ static HighlightInfo checkMemberValueType(@Nullable PsiAnnotationMemberValue val final PsiClass psiClass = PsiUtil.resolveClassInType(type); if (psiClass != null && psiClass.isEnum() && !(expr instanceof PsiReferenceExpression && ((PsiReferenceExpression)expr).resolve() instanceof PsiEnumConstant)) { String description = JavaErrorMessages.message("annotation.non.enum.constant.attribute.value"); - return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create(); + return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(value).descriptionAndTooltip(description).create(); } if (type != null && TypeConversionUtil.areTypesAssignmentCompatible(expectedType, expr) || @@ -754,7 +755,7 @@ static HighlightInfo checkReceiverType(PsiReceiverParameter parameter) { private static boolean isStatic(PsiModifierListOwner owner) { if (owner == null) return false; - if (owner instanceof PsiClass && ((PsiClass)owner).getContainingClass() == null) return true; + if (owner instanceof PsiClass && ClassUtil.isTopLevelClass((PsiClass)owner)) return true; PsiModifierList modifierList = owner.getModifierList(); return modifierList != null && modifierList.hasModifierProperty(PsiModifier.STATIC); } diff --git a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java index 98085e944c5ba..9daf181b10342 100644 --- a/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/util/ClassUtil.java @@ -267,8 +267,12 @@ public static boolean isTopLevelClass(@NotNull PsiClass aClass) { return false; } - final PsiFile parentFile = aClass.getContainingFile(); - // do not select JspClass - return parentFile != null && parentFile.getLanguage() == JavaLanguage.INSTANCE; + PsiElement parent = aClass.getParent(); + if (parent instanceof PsiDeclarationStatement && parent.getParent() instanceof PsiCodeBlock) { + return false; + } + + PsiFile parentFile = aClass.getContainingFile(); + return parentFile != null && parentFile.getLanguage() == JavaLanguage.INSTANCE; // do not select JspClass } } \ No newline at end of file diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/receiverParameters.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/receiverParameters.java index d678332618189..d86ef51302169 100644 --- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/receiverParameters.java +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/receiverParameters.java @@ -29,6 +29,12 @@ void m3b(@TA C.X.this) { } + void m5() { + class L { + L(C C.this) { } + } + } + static void sm1(@TA Object this) { } C(C this) { } From ffd60882df3f3ea29764a2798a46a07d47f30937 Mon Sep 17 00:00:00 2001 From: Alexander Lobas Date: Wed, 20 Jul 2016 17:40:49 +0300 Subject: [PATCH 29/67] IDEA-157041 New notifications: link click area not working IDEA-158717 Notification link cannot be clicked --- .../impl/NotificationsManagerImpl.java | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java index 262a9b1be7045..7bfd9e5995e19 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java @@ -68,9 +68,8 @@ import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.UIResource; import javax.swing.text.*; -import javax.swing.text.html.HTMLEditorKit; +import javax.swing.text.html.*; import javax.swing.text.html.ParagraphView; -import javax.swing.text.html.StyleSheet; import java.awt.*; import java.awt.event.*; import java.awt.geom.Rectangle2D; @@ -791,6 +790,10 @@ protected void paintComponent(Graphics g) { hoverAdapter.addSource(text); hoverAdapter.addSource(pane); + if (buttons == null && actions) { + createActionPanel(notification, centerPanel, layoutData.configuration.actionGap, hoverAdapter); + } + if (expandAction != null) { hoverAdapter.addComponent(expandAction, component -> { Rectangle bounds; @@ -809,10 +812,6 @@ protected void paintComponent(Graphics g) { }); } - if (buttons == null && actions) { - createActionPanel(notification, centerPanel, layoutData.configuration.actionGap, hoverAdapter); - } - hoverAdapter.initListeners(); if (layoutData.mergeData != null) { @@ -981,6 +980,18 @@ public void mouseExited(MouseEvent e) { } private void handleEvent(MouseEvent e, boolean pressed, boolean moved) { + if (e.getSource() instanceof JEditorPane) { + JEditorPane pane = (JEditorPane)e.getSource(); + int pos = pane.viewToModel(e.getPoint()); + if (pos >= 0) { + HTMLDocument document = (HTMLDocument)pane.getDocument(); + AttributeSet attributes = document.getCharacterElement(pos).getAttributes(); + if (attributes.getAttribute(HTML.Tag.A) != null) { + return; + } + } + } + for (Pair p : myComponents) { Component component = p.first; Rectangle bounds; @@ -989,6 +1000,7 @@ private void handleEvent(MouseEvent e, boolean pressed, boolean moved) { JBInsets.addTo(bounds, (Insets)p.second); } else { + //noinspection unchecked bounds = ((Function)p.second).fun(component); } if (bounds.contains(SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), component.getParent()))) { From ab0db9b789503d091f7c15bf7d7b4bcf751494d7 Mon Sep 17 00:00:00 2001 From: Yaroslav Lepenkin Date: Wed, 20 Jul 2016 17:30:11 +0300 Subject: [PATCH 30/67] [java-formatter] chained method calls - align on enter press by dot --- .../formatter/java/SyntheticCodeBlock.java | 50 ++++++++++++++++++- .../formatter/java/JavaEnterActionTest.java | 29 +++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java b/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java index 30f1960119e3f..e1eb9c546eeb9 100644 --- a/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java +++ b/java/java-impl/src/com/intellij/psi/formatter/java/SyntheticCodeBlock.java @@ -19,12 +19,14 @@ import com.intellij.lang.ASTNode; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.TextRange; +import com.intellij.psi.JavaTokenType; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.codeStyle.JavaCodeStyleSettings; import com.intellij.psi.formatter.common.AbstractBlock; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; @@ -56,7 +58,7 @@ public SyntheticCodeBlock(List subBlocks, if (subBlocks.isEmpty()) { LOG.assertTrue(false); } - mySubBlocks = new ArrayList(subBlocks); + mySubBlocks = new ArrayList<>(subBlocks); myAlignment = alignment; mySettings = settings; myWrap = wrap; @@ -145,10 +147,56 @@ public ChildAttributes getChildAttributes(final int newChildIndex) { Block block = mySubBlocks.get(newChildIndex); alignment = block.getAlignment(); } + else if (mySubBlocks.size() == newChildIndex) { + if (isRParenth(getRightMostBlock())) { + alignment = getDotAlignment(); + } + } + return new ChildAttributes(getIndent(), alignment); } } + private static boolean isRParenth(Block sibling) { + if (sibling instanceof LeafBlock) { + ASTNode node = ((LeafBlock)sibling).getNode(); + return node != null && node.getElementType() == JavaTokenType.RPARENTH; + } + return false; + } + + @Nullable + private Alignment getDotAlignment() { + if (mySubBlocks.size() > 1) { + Block block = mySubBlocks.get(1); + if (isDotFirst(block)) { + return block.getAlignment(); + } + } + return null; + } + + private static boolean isDotFirst(final Block block) { + Block current = block; + while (!current.getSubBlocks().isEmpty()) { + current = block.getSubBlocks().get(0); + } + ASTNode node = current instanceof LeafBlock ? ((LeafBlock)current).getNode() : null; + return node != null && node.getElementType() == JavaTokenType.DOT; + } + + @Nullable + private Block getRightMostBlock() { + Block rightMost = null; + List subBlocks = getSubBlocks(); + while (!subBlocks.isEmpty()) { + int lastIndex = subBlocks.size() - 1; + rightMost = subBlocks.get(lastIndex); + subBlocks = rightMost.getSubBlocks(); + } + return rightMost; + } + @Override public boolean isIncomplete() { if (myIsIncomplete) return true; diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaEnterActionTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaEnterActionTest.java index af65e34e8fa31..b0a9cdae52d85 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaEnterActionTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaEnterActionTest.java @@ -169,4 +169,33 @@ public void testEnter_BetweenAlignedChainedMethodCalls() throws IOException { " }\n" + "}"); } + + public void testEnter_AfterLastChainedCall() throws IOException { + CodeStyleSettings settings = getCodeStyleSettings(); + CommonCodeStyleSettings javaCommon = settings.getCommonSettings(JavaLanguage.INSTANCE); + javaCommon.ALIGN_MULTILINE_CHAINED_METHODS = true; + setCodeStyleSettings(settings); + + doTextTest("java", + "class T {\n" + + " public void main() {\n" + + " ActionBarPullToRefresh.from(getActivity())\n" + + " .theseChildrenArePullable(eventsListView)\n" + + " .listener(this)\n" + + " .useViewDelegate(StickyListHeadersListView.class, new AbsListViewDelegate())\n" + + " }\n" + + "}", + "class T {\n" + + " public void main() {\n" + + " ActionBarPullToRefresh.from(getActivity())\n" + + " .theseChildrenArePullable(eventsListView)\n" + + " .listener(this)\n" + + " .useViewDelegate(StickyListHeadersListView.class, new AbsListViewDelegate())\n" + + " \n" + + " }\n" + + "}"); + } + + + } \ No newline at end of file From 4bf9dd514bd82580038f4a385a395dffbb3f529c Mon Sep 17 00:00:00 2001 From: Dmitry Batkovich Date: Wed, 20 Jul 2016 15:15:06 +0300 Subject: [PATCH 31/67] ConvertEqualsMethodToStaticIntention merged with EqualsReplaceableByObjectsCallInspection to become a informational level inspection IDEA-157727 --- .../ConvertEqualsMethodToStaticIntention.java | 102 ------------------ .../ConvertEqualsMethodToStaticTest.java | 62 ----------- .../src/META-INF/InspectionGadgets.xml | 2 +- .../siyeh/InspectionGadgetsBundle.properties | 1 + ...alsReplaceableByObjectsCallInspection.java | 55 +++++++--- .../siyeh/ig/psiutils/ExpressionUtils.java | 2 +- .../EqualsReplaceableByObjectsCall.java | 4 + ...ualsReplaceableByObjectsCallCheckNull.java | 11 ++ ...eplaceableByObjectsCallInspectionTest.java | 28 ++++- resources/src/META-INF/IdeaPlugin.xml | 4 - 10 files changed, 85 insertions(+), 186 deletions(-) delete mode 100644 java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertEqualsMethodToStaticIntention.java delete mode 100644 java/java-tests/testSrc/com/intellij/codeInsight/intention/ConvertEqualsMethodToStaticTest.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCallCheckNull.java diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertEqualsMethodToStaticIntention.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertEqualsMethodToStaticIntention.java deleted file mode 100644 index cc3f08e45a64c..0000000000000 --- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/ConvertEqualsMethodToStaticIntention.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2000-2015 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.intention.impl; - -import com.intellij.codeInsight.FileModificationService; -import com.intellij.codeInsight.intention.BaseElementAtCaretIntentionAction; -import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.Editor; -import com.intellij.openapi.project.Project; -import com.intellij.psi.*; -import com.intellij.psi.util.PsiUtil; -import com.intellij.util.IncorrectOperationException; -import org.jetbrains.annotations.Nls; -import org.jetbrains.annotations.NotNull; - -/** - * @author Dmitry Batkovich - */ -public class ConvertEqualsMethodToStaticIntention extends BaseElementAtCaretIntentionAction { - private static final Logger LOG = Logger.getInstance(ConvertEqualsMethodToStaticIntention.class); - private static final String REPLACE_TEMPLATE = "java.util.Objects.equals(%s, %s)"; - public static final String TEXT = "Convert '.equals()' to 'java.util.Objects.equals()'"; - - @Override - public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { - if (!(element instanceof PsiIdentifier)) { - return false; - } - if (!PsiUtil.isLanguageLevel7OrHigher(element)) { - return false; - } - final PsiElement referenceExpression = element.getParent(); - if (!(referenceExpression instanceof PsiReferenceExpression)) { - return false; - } - if (!"equals".equals(((PsiReferenceExpression)referenceExpression).getReferenceName())) { - return false; - } - final PsiElement methodCallExpression = referenceExpression.getParent(); - if (!(methodCallExpression instanceof PsiMethodCallExpression)) { - return false; - } - final int argumentsCount = ((PsiMethodCallExpression)methodCallExpression).getArgumentList().getExpressions().length; - if (argumentsCount != 1) { - return false; - } - final PsiMethod method = ((PsiMethodCallExpression)methodCallExpression).resolveMethod(); - if (method == null) { - return false; - } - PsiClass javaLangObject = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_OBJECT, element.getResolveScope()); - if (javaLangObject == null) { - return false; - } - if (javaLangObject.isEquivalentTo(method.getContainingClass())) { - return true; - } - final PsiMethod[] superMethods = method.findSuperMethods(javaLangObject); - return superMethods.length == 1; - } - - @Override - public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { - if (!FileModificationService.getInstance().preparePsiElementsForWrite(element)) { - return; - } - final PsiElement parent = element.getParent().getParent(); - LOG.assertTrue(parent instanceof PsiMethodCallExpression); - PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parent; - final PsiExpression qualifier = methodCall.getMethodExpression().getQualifierExpression(); - final String qualifierText = qualifier == null ? PsiKeyword.THIS : qualifier.getText(); - final PsiExpression parameter = methodCall.getArgumentList().getExpressions()[0]; - final String expressionText = String.format(REPLACE_TEMPLATE, qualifierText, parameter.getText()); - methodCall.replace(JavaPsiFacade.getElementFactory(project).createExpressionFromText(expressionText, null)); - } - - @Nls - @NotNull - @Override - public String getFamilyName() { - return TEXT; - } - - @NotNull - @Override - public String getText() { - return getFamilyName(); - } -} diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/ConvertEqualsMethodToStaticTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/ConvertEqualsMethodToStaticTest.java deleted file mode 100644 index 5377fe688dc3f..0000000000000 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/ConvertEqualsMethodToStaticTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2000-2015 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.intention; - -import com.intellij.JavaTestUtil; -import com.intellij.codeInsight.intention.impl.ConvertCompareToToEqualsIntention; -import com.intellij.codeInsight.intention.impl.ConvertEqualsMethodToStaticIntention; -import com.intellij.openapi.roots.LanguageLevelProjectExtension; -import com.intellij.pom.java.LanguageLevel; -import com.intellij.testFramework.fixtures.CodeInsightTestUtil; -import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase; - -/** - * @author Dmitry Batkovich - */ -public class ConvertEqualsMethodToStaticTest extends JavaCodeInsightFixtureTestCase { - @Override - protected String getTestDataPath() { - return JavaTestUtil.getJavaTestDataPath() + "/codeInsight/convertEqualsMethodToStatic/"; - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7); - } - - public void testSimple() { - doTest(); - } - - public void testComplexQualifierAndArgument() { - doTest(); - } - - public void testNotAvailable() { - doTestNotAvailable(); - } - - private void doTest() { - final String name = getTestName(true); - CodeInsightTestUtil.doIntentionTest(myFixture, ConvertEqualsMethodToStaticIntention.TEXT, name + ".java", name + "_after.java"); - } - - private void doTestNotAvailable() { - myFixture.configureByFile(getTestName(true) + ".java"); - assertEmpty(myFixture.filterAvailableIntentions(ConvertEqualsMethodToStaticIntention.TEXT)); - } -} diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml index 8beed8aedac4e..3c969aec81530 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml @@ -1312,7 +1312,7 @@ implementationClass="com.siyeh.ig.migration.BigDecimalLegacyMethodInspection"/> #ref replaceable by 'Objects.equals()' expression #loc equals.replaceable.by.objects.call.quickfix=Replace with 'Objects.equals()' expression +equals.replaceable.by.objects.check.not.null.option=Report only null safe 'equals' calls array.objects.equals.display.name='Objects.equals()' called on arrays array.objects.equals.problem.descriptor=Objects.#ref() on arrays should probably be 'Arrays.equals()' #loc array.objects.deep.equals.problem.descriptor=Objects.#ref() on arrays should probably be 'Arrays.deepEquals()' #loc diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspection.java index 75b59118fee75..e95e536ceb233 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspection.java @@ -16,6 +16,7 @@ package com.siyeh.ig.migration; import com.intellij.codeInspection.ProblemDescriptor; +import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; @@ -34,10 +35,19 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import javax.swing.*; + /** * @author Bas Leijdekkers */ public class EqualsReplaceableByObjectsCallInspection extends BaseInspection { + public boolean checkNotNull; + + @NotNull + @Override + public JComponent createOptionsPanel() { + return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("equals.replaceable.by.objects.check.not.null.option"), this, "checkNotNull"); + } @Nls @NotNull @@ -86,10 +96,10 @@ public String getFamilyName() { @Override protected void doFix(Project project, ProblemDescriptor descriptor) { final PsiElement element = descriptor.getPsiElement(); - if (!(element instanceof PsiBinaryExpression)) { + if (!(element instanceof PsiBinaryExpression || element instanceof PsiMethodCallExpression)) { return; } - final PsiBinaryExpression expression = (PsiBinaryExpression)element; + final PsiExpression expression = (PsiExpression)element; if (myEquals) { PsiReplacementUtil.replaceExpressionAndShorten(expression, "java.util.Objects.equals(" + myName1 + "," + myName2 + ")"); } @@ -109,41 +119,62 @@ public BaseInspectionVisitor buildVisitor() { return new EqualsReplaceableByObjectsCallVisitor(); } - private static class EqualsReplaceableByObjectsCallVisitor extends BaseInspectionVisitor { + private class EqualsReplaceableByObjectsCallVisitor extends BaseInspectionVisitor { @Override - public void visitBinaryExpression(PsiBinaryExpression expression) { + public void visitMethodCallExpression(PsiMethodCallExpression expression) { + final PsiElement maybeBinary = PsiTreeUtil.skipParentsOfType(expression, PsiParenthesizedExpression.class, PsiPrefixExpression.class); + if (maybeBinary instanceof PsiBinaryExpression) { + if (processNotNullCheck((PsiBinaryExpression)maybeBinary)) { + return; + } + } + if (!checkNotNull) { + final PsiVariable variable = ExpressionUtils.getVariable(expression.getMethodExpression().getQualifierExpression()); + if (variable == null) { + return; + } + final PsiVariable otherVariable = getArgumentFromEqualsCallOn(expression, variable); + if (otherVariable == null) { + return; + } + registerError(expression, variable.getName(), otherVariable.getName(), true); + } + } + + private boolean processNotNullCheck(PsiBinaryExpression expression) { final IElementType tokenType = expression.getOperationTokenType(); if (JavaTokenType.ANDAND.equals(tokenType)) { final PsiVariable variable = ExpressionUtils.getVariableFromNullComparison(expression.getLOperand(), false); if (variable == null) { - return; + return false; } final PsiVariable otherVariable = getArgumentFromEqualsCallOn(expression.getROperand(), variable); if (otherVariable == null) { - return; + return false; } checkEqualityBefore(expression, true, variable, otherVariable); } else if (JavaTokenType.OROR.equals(tokenType)) { final PsiVariable variable = ExpressionUtils.getVariableFromNullComparison(expression.getLOperand(), true); if (variable == null) { - return; + return false; } final PsiExpression rhs = ParenthesesUtils.stripParentheses(expression.getROperand()); if (!(rhs instanceof PsiPrefixExpression)) { - return; + return false; } final PsiPrefixExpression prefixExpression = (PsiPrefixExpression)rhs; if (!JavaTokenType.EXCL.equals(prefixExpression.getOperationTokenType())) { - return; + return false; } final PsiVariable otherVariable = getArgumentFromEqualsCallOn(prefixExpression.getOperand(), variable); if (otherVariable == null) { - return; + return false; } checkEqualityBefore(expression, false, variable, otherVariable); } + return true; } private void checkEqualityBefore(PsiExpression expression, boolean equals, PsiVariable variable1, PsiVariable variable2) { @@ -161,7 +192,7 @@ private void checkEqualityBefore(PsiExpression expression, boolean equals, PsiVa registerError(expression, variable1.getName(), variable2.getName(), Boolean.valueOf(equals)); } - private static boolean isEquality(PsiExpression expression, boolean equals, PsiVariable variable1, PsiVariable variable2) { + private boolean isEquality(PsiExpression expression, boolean equals, PsiVariable variable1, PsiVariable variable2) { expression = ParenthesesUtils.stripParentheses(expression); if (!(expression instanceof PsiBinaryExpression)) { return false; @@ -183,7 +214,7 @@ private static boolean isEquality(PsiExpression expression, boolean equals, PsiV (VariableAccessUtils.evaluatesToVariable(lhs, variable2) && VariableAccessUtils.evaluatesToVariable(rhs, variable1)); } - private static PsiVariable getArgumentFromEqualsCallOn(PsiExpression expression, @NotNull PsiVariable variable) { + private PsiVariable getArgumentFromEqualsCallOn(PsiExpression expression, PsiVariable variable) { expression = ParenthesesUtils.stripParentheses(expression); if (!(expression instanceof PsiMethodCallExpression)) { return null; diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpressionUtils.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpressionUtils.java index 7d234614067ff..c72f1991f3b9c 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpressionUtils.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/ExpressionUtils.java @@ -635,7 +635,7 @@ else if (PsiType.NULL.equals(operands[1].getType())) { return null; } - public static PsiVariable getVariable(PsiExpression expression) { + public static PsiVariable getVariable(@Nullable PsiExpression expression) { expression = ParenthesesUtils.stripParentheses(expression); if (!(expression instanceof PsiReferenceExpression)) { return null; diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCall.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCall.java index fa187d7305131..49b9afbef78f5 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCall.java +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCall.java @@ -4,4 +4,8 @@ void yyy(Object a, Object b) { boolean d = (a != b) && (a == null || !a.equals(b)); boolean e = ((a) == (b)) || ((a) != (null) && (a).equals((b))); } + + void ignoreNullityCheck(Object a, Object b) { + boolean c = a.equals(b); + } } \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCallCheckNull.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCallCheckNull.java new file mode 100644 index 0000000000000..5d4f1fdbe9248 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/equals_replaceable_by_objects_call/EqualsReplaceableByObjectsCallCheckNull.java @@ -0,0 +1,11 @@ +class EqualsReplaceableByObjectsCall { + void yyy(Object a, Object b) { + boolean c = (a != null) && a.equals(b); + boolean d = (a != b) && (a == null || !a.equals(b)); + boolean e = ((a) == (b)) || ((a) != (null) && (a).equals((b))); + } + + void ignoreNullityCheck(Object a, Object b) { + boolean c = a.equals(b); + } +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspectionTest.java index 38e5b432ddbc7..27d6202dbcabd 100644 --- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspectionTest.java +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/migration/EqualsReplaceableByObjectsCallInspectionTest.java @@ -15,23 +15,43 @@ */ package com.siyeh.ig.migration; -import com.intellij.codeInspection.InspectionProfileEntry; +import com.intellij.codeHighlighting.HighlightDisplayLevel; +import com.intellij.codeInsight.daemon.HighlightDisplayKey; +import com.intellij.codeInspection.LocalInspectionTool; +import com.intellij.codeInspection.ex.InspectionProfileImpl; +import com.intellij.profile.codeInspection.InspectionProjectProfileManager; import com.siyeh.ig.LightInspectionTestCase; -import junit.framework.TestCase; import org.jetbrains.annotations.Nullable; /** * @author Bas Leijdekkers */ public class EqualsReplaceableByObjectsCallInspectionTest extends LightInspectionTestCase { + private EqualsReplaceableByObjectsCallInspection myInspection = new EqualsReplaceableByObjectsCallInspection(); + + @Override + public void setUp() throws Exception { + super.setUp(); + final InspectionProfileImpl profile = (InspectionProfileImpl)InspectionProjectProfileManager.getInstance(getProject()).getInspectionProfile(); + profile.setErrorLevel(HighlightDisplayKey.find("EqualsReplaceableByObjectsCall"), HighlightDisplayLevel.WARNING, getProject()); + } public void testEqualsReplaceableByObjectsCall() { doTest(); } + public void testEqualsReplaceableByObjectsCallCheckNull() { + try { + myInspection.checkNotNull = true; + doTest(); + } finally { + myInspection.checkNotNull = false; + } + } + @Nullable @Override - protected InspectionProfileEntry getInspection() { - return new EqualsReplaceableByObjectsCallInspection(); + protected LocalInspectionTool getInspection() { + return myInspection; } } \ No newline at end of file diff --git a/resources/src/META-INF/IdeaPlugin.xml b/resources/src/META-INF/IdeaPlugin.xml index fb6a351caaf8a..ad80bf08d27d0 100644 --- a/resources/src/META-INF/IdeaPlugin.xml +++ b/resources/src/META-INF/IdeaPlugin.xml @@ -882,10 +882,6 @@ com.intellij.codeInsight.intention.impl.ConvertCompareToToEqualsIntention Java/Control Flow - - com.intellij.codeInsight.intention.impl.ConvertEqualsMethodToStaticIntention - Java/Control Flow - com.intellij.codeInsight.intention.impl.CreateFieldFromParameterAction From 039add426cd2606356d6c10272e63f7e13a2bc81 Mon Sep 17 00:00:00 2001 From: Dmitry Batkovich Date: Wed, 20 Jul 2016 17:10:36 +0300 Subject: [PATCH 32/67] inspection view: do not use line number in node text --- .../intellij/codeInspection/ui/ProblemDescriptionNode.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/ProblemDescriptionNode.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/ProblemDescriptionNode.java index c28ac8ef99fa1..a4d7bb6bdb148 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/ProblemDescriptionNode.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/ProblemDescriptionNode.java @@ -35,7 +35,6 @@ import java.util.function.IntSupplier; -import static com.intellij.codeInspection.ProblemDescriptorUtil.APPEND_LINE_NUMBER; import static com.intellij.codeInspection.ProblemDescriptorUtil.TRIM_AT_TREE_END; /** @@ -167,8 +166,7 @@ protected String calculatePresentableName() { if (descriptor == null) return ""; PsiElement element = descriptor instanceof ProblemDescriptor ? ((ProblemDescriptor)descriptor).getPsiElement() : null; - return XmlStringUtil.stripHtml(ProblemDescriptorUtil.renderDescriptionMessage(descriptor, element, - APPEND_LINE_NUMBER | TRIM_AT_TREE_END)); + return XmlStringUtil.stripHtml(ProblemDescriptorUtil.renderDescriptionMessage(descriptor, element, TRIM_AT_TREE_END)); } public boolean isQuickFixAppliedFromView() { From ec05aa8b8566113c7e2faff2bd731b97c22bc10c Mon Sep 17 00:00:00 2001 From: Alexey Ushakov Date: Wed, 20 Jul 2016 18:35:05 +0300 Subject: [PATCH 33/67] BootJDK switcher update to handle new IDEA bundle structure on OSX --- .../src/com/intellij/openapi/util/SwitchBootJdkAction.java | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java b/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java index 4d4411069e43a..71870cb579b95 100644 --- a/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java +++ b/platform/lang-impl/src/com/intellij/openapi/util/SwitchBootJdkAction.java @@ -59,11 +59,7 @@ public class SwitchBootJdkAction extends AnAction implements DumbAware { @NotNull private static File getBundledJDKFile() { - StringBuilder bundledJDKPath = new StringBuilder("jre"); - if (SystemInfo.isMac) { - bundledJDKPath.append(File.separator).append("jdk"); - } - return new File(bundledJDKPath.toString()); + return new File(SystemInfo.isMac ? "jdk" : "jre"); } @Override From b525e80a879c866d514b4b092a8d86a1a3551615 Mon Sep 17 00:00:00 2001 From: Pavel Dolgov Date: Wed, 20 Jul 2016 18:50:05 +0300 Subject: [PATCH 34/67] Java inspection: Returned back RemoveRedundantElseAction intention, because it turns out it's useful in some cases (IDEA-157727) --- .../quickfix/RemoveRedundantElseAction.java | 109 ++++++++++++++++++ .../quickFix/removeRedundantElse/after1.java | 13 +++ .../quickFix/removeRedundantElse/before1.java | 14 +++ .../beforeCanThrowException.java | 15 +++ .../beforeIfElseChain.java | 17 +++ .../RemoveRedundantElseActionTest.java | 32 +++++ .../after.java.template | 8 ++ .../before.java.template | 10 ++ .../description.html | 7 ++ resources/src/META-INF/IdeaPlugin.xml | 4 + 10 files changed, 229 insertions(+) create mode 100644 java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveRedundantElseAction.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/after1.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/before1.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeCanThrowException.java create mode 100644 java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeIfElseChain.java create mode 100644 java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantElseActionTest.java create mode 100644 resources-en/src/intentionDescriptions/RemoveRedundantElseAction/after.java.template create mode 100644 resources-en/src/intentionDescriptions/RemoveRedundantElseAction/before.java.template create mode 100644 resources-en/src/intentionDescriptions/RemoveRedundantElseAction/description.html diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveRedundantElseAction.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveRedundantElseAction.java new file mode 100644 index 0000000000000..28db235e1e1bb --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/RemoveRedundantElseAction.java @@ -0,0 +1,109 @@ +/* + * Copyright 2000-2009 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.daemon.impl.quickfix; + +import com.intellij.codeInsight.FileModificationService; +import com.intellij.codeInsight.daemon.QuickFixBundle; +import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction; +import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.Project; +import com.intellij.psi.*; +import com.intellij.psi.controlFlow.*; +import com.intellij.psi.util.PsiTreeUtil; +import com.intellij.util.BitUtil; +import com.intellij.util.IncorrectOperationException; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * @author ven + */ +public class RemoveRedundantElseAction extends PsiElementBaseIntentionAction { + private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.RemoveRedundantElseAction"); + + @Override + @NotNull + public String getText() { + return QuickFixBundle.message("remove.redundant.else.fix"); + } + + @Override + @NotNull + public String getFamilyName() { + return QuickFixBundle.message("remove.redundant.else.fix"); + } + + @Override + public boolean isAvailable(@NotNull Project project, Editor editor, @NotNull PsiElement element) { + if (element instanceof PsiKeyword && + element.getParent() instanceof PsiIfStatement && + PsiKeyword.ELSE.equals(element.getText())) { + PsiIfStatement ifStatement = (PsiIfStatement)element.getParent(); + if (ifStatement.getElseBranch() == null) return false; + PsiStatement thenBranch = ifStatement.getThenBranch(); + if (thenBranch == null) return false; + PsiElement block = PsiTreeUtil.getParentOfType(ifStatement, PsiCodeBlock.class); + if (block != null) { + while (cantCompleteNormally(thenBranch, block)) { + thenBranch = getPrevThenBranch(thenBranch); + if (thenBranch == null) return true; + } + return false; + } + } + return false; + } + + @Nullable + private static PsiStatement getPrevThenBranch(@NotNull PsiElement thenBranch) { + final PsiElement ifStatement = thenBranch.getParent(); + final PsiElement parent = ifStatement.getParent(); + if (parent instanceof PsiIfStatement && ((PsiIfStatement)parent).getElseBranch() == ifStatement) { + return ((PsiIfStatement)parent).getThenBranch(); + } + return null; + } + + private static boolean cantCompleteNormally(@NotNull PsiStatement thenBranch, PsiElement block) { + try { + ControlFlow controlFlow = ControlFlowFactory.getInstance(thenBranch.getProject()).getControlFlow(block, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance()); + int startOffset = controlFlow.getStartOffset(thenBranch); + int endOffset = controlFlow.getEndOffset(thenBranch); + return startOffset != -1 && endOffset != -1 && !BitUtil.isSet(ControlFlowUtil.getCompletionReasons(controlFlow, startOffset, endOffset), ControlFlowUtil.NORMAL_COMPLETION_REASON); + } + catch (AnalysisCanceledException e) { + return false; + } + } + + @Override + public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { + if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; + PsiIfStatement ifStatement = (PsiIfStatement)element.getParent(); + LOG.assertTrue(ifStatement != null && ifStatement.getElseBranch() != null); + PsiStatement elseBranch = ifStatement.getElseBranch(); + if (elseBranch instanceof PsiBlockStatement) { + PsiElement[] statements = ((PsiBlockStatement)elseBranch).getCodeBlock().getStatements(); + if (statements.length > 0) { + ifStatement.getParent().addRangeAfter(statements[0], statements[statements.length-1], ifStatement); + } + } else { + ifStatement.getParent().addAfter(elseBranch, ifStatement); + } + ifStatement.getElseBranch().delete(); + } +} diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/after1.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/after1.java new file mode 100644 index 0000000000000..d0d55761f11b6 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/after1.java @@ -0,0 +1,13 @@ +// "Remove redundant 'else'" "true" +class a { + void foo() { + int a = 0; + int b = 0; + if (a != b) { + return; + } + a = b; + a++; + } +} + diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/before1.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/before1.java new file mode 100644 index 0000000000000..ea4609835464b --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/before1.java @@ -0,0 +1,14 @@ +// "Remove redundant 'else'" "true" +class a { + void foo() { + int a = 0; + int b = 0; + if (a != b) { + return; + } else { + a = b; + } + a++; + } +} + diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeCanThrowException.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeCanThrowException.java new file mode 100644 index 0000000000000..8fd59ef094f32 --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeCanThrowException.java @@ -0,0 +1,15 @@ +// "Remove redundant 'else'" "false" +import java.io.IOException; +class a { + void foo(boolean condition) throws IOException{ + if (condition) { + tMethod(); + } + else { + System.out.println("else"); + } + } + + void tMethod() throws IOException {} +} + diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeIfElseChain.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeIfElseChain.java new file mode 100644 index 0000000000000..f702178d781ff --- /dev/null +++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse/beforeIfElseChain.java @@ -0,0 +1,17 @@ +// "Remove redundant 'else'" "false" +class a { + void foo() { + int a = 0; + int b = 0; + if (a != b) { + a = 10; + } else if (a + 1 == b) { + return; + } + else { + a = b; + } + a++; + } +} + diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantElseActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantElseActionTest.java new file mode 100644 index 0000000000000..0a33ada748f82 --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/RemoveRedundantElseActionTest.java @@ -0,0 +1,32 @@ +/* + * Copyright 2000-2010 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.daemon.quickFix; + +/** + * User: anna + * Date: Aug 30, 2010 + */ +public class RemoveRedundantElseActionTest extends LightQuickFixParameterizedTestCase { + + public void test() throws Exception { doAllTests(); } + + @Override + protected String getBasePath() { + return "/codeInsight/daemonCodeAnalyzer/quickFix/removeRedundantElse"; + } + +} + diff --git a/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/after.java.template b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/after.java.template new file mode 100644 index 0000000000000..6bbd9d56135a7 --- /dev/null +++ b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/after.java.template @@ -0,0 +1,8 @@ +public class X { + void f(int i) { + if (i==0) { + return; + } + int j = 0; + } +} \ No newline at end of file diff --git a/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/before.java.template b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/before.java.template new file mode 100644 index 0000000000000..edad99d14f454 --- /dev/null +++ b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/before.java.template @@ -0,0 +1,10 @@ +public class X { + void f(int i) { + if (i==0) { + return; + } + else { + int j = 0; + } + } +} \ No newline at end of file diff --git a/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/description.html b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/description.html new file mode 100644 index 0000000000000..8992a7b29b2c0 --- /dev/null +++ b/resources-en/src/intentionDescriptions/RemoveRedundantElseAction/description.html @@ -0,0 +1,7 @@ + + +This intention detaches else clause from the if statement, +if corresponding then clause never completes normally. + + + diff --git a/resources/src/META-INF/IdeaPlugin.xml b/resources/src/META-INF/IdeaPlugin.xml index ad80bf08d27d0..02c0b3840c5ce 100644 --- a/resources/src/META-INF/IdeaPlugin.xml +++ b/resources/src/META-INF/IdeaPlugin.xml @@ -832,6 +832,10 @@ com.intellij.codeInsight.intention.impl.ExtractIfConditionAction Java/Control Flow + + com.intellij.codeInsight.daemon.impl.quickfix.RemoveRedundantElseAction + Java/Control Flow + com.intellij.codeInsight.intention.impl.AddNotNullAnnotationIntention Java/Annotations From d52e7e9cb3ed9e19034df87cf3ae139349b914ed Mon Sep 17 00:00:00 2001 From: Alexander Lobas Date: Wed, 20 Jul 2016 18:51:04 +0300 Subject: [PATCH 35/67] IDEA-157763 rollback changes --- .../com/intellij/ide/WelcomeWizardUtil.java | 13 ---- .../CloudConfigurationManager.java | 62 ------------------- .../CloudConfigurationProvider.java | 34 ---------- .../AbstractCustomizeWizardStep.java | 6 -- .../customize/CustomizeIDEWizardDialog.java | 11 ---- .../CustomizeIdeaWizardStepsProvider.java | 3 - .../CustomizeMacKeyboardLayoutStep.java | 38 +----------- .../customize/CustomizeUIThemeStepPanel.java | 32 +--------- .../keymap/impl/KeymapChangeListener.java | 27 -------- .../openapi/keymap/impl/KeymapImpl.java | 54 +--------------- .../keymap/impl/KeymapManagerImpl.java | 7 --- 11 files changed, 3 insertions(+), 284 deletions(-) delete mode 100644 platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationManager.java delete mode 100644 platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationProvider.java delete mode 100644 platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapChangeListener.java diff --git a/platform/core-api/src/com/intellij/ide/WelcomeWizardUtil.java b/platform/core-api/src/com/intellij/ide/WelcomeWizardUtil.java index 91015732b28b7..8d855db855ca5 100644 --- a/platform/core-api/src/com/intellij/ide/WelcomeWizardUtil.java +++ b/platform/core-api/src/com/intellij/ide/WelcomeWizardUtil.java @@ -15,7 +15,6 @@ */ package com.intellij.ide; -import com.intellij.util.ParameterizedRunnable; import org.jetbrains.annotations.Nullable; import java.util.Collections; @@ -29,7 +28,6 @@ public class WelcomeWizardUtil { private static volatile String ourWizardEditorScheme; private static volatile Boolean ourAutoScrollToSource; private static final Set ourFeaturedPluginsToInstall = new HashSet(); - private static ParameterizedRunnable ourWizardCreateKeymapRunnable; public static void setDefaultLAF(String laf) { ourDefaultLAF = laf; @@ -49,12 +47,6 @@ public static String getWizardLAF() { public static void setWizardKeymap(@Nullable String keymap) { ourWizardMacKeymap = keymap; - ourWizardCreateKeymapRunnable = null; - } - - public static void setWizardKeymap(@Nullable ParameterizedRunnable runnable) { - ourWizardMacKeymap = null; - ourWizardCreateKeymapRunnable = runnable; } @Nullable @@ -62,11 +54,6 @@ public static String getWizardMacKeymap() { return ourWizardMacKeymap; } - @Nullable - public static ParameterizedRunnable getWizardCreateKeymapRunnable() { - return ourWizardCreateKeymapRunnable; - } - public static void setWizardEditorScheme(@Nullable String wizardEditorScheme) { ourWizardEditorScheme = wizardEditorScheme; } diff --git a/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationManager.java b/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationManager.java deleted file mode 100644 index fce1a473dc087..0000000000000 --- a/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationManager.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2000-2016 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.ide.cloudConfiguration; - -import com.intellij.openapi.keymap.KeymapManager; -import com.intellij.util.ParameterizedRunnable; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * @author Alexander Lobas - */ -public class CloudConfigurationManager { - private static final CloudConfigurationProvider EMPTY = new CloudConfigurationProvider() { - @Nullable - @Override - public String getSharedLaf() { - return null; - } - - @Nullable - @Override - public String getSharedKeymap() { - return null; - } - - @Nullable - @Override - public ParameterizedRunnable createSharedKeymap() { - return null; - } - }; - - private static CloudConfigurationProvider myCustomizeProvider; - - @Nullable - public static CloudConfigurationProvider getRawCustomizeProvider() { - return myCustomizeProvider; - } - - @NotNull - public static CloudConfigurationProvider getCustomizeProvider() { - return myCustomizeProvider == null ? EMPTY : myCustomizeProvider; - } - - public static void setCustomizeProvider(@Nullable CloudConfigurationProvider provider) { - myCustomizeProvider = provider; - } -} \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationProvider.java b/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationProvider.java deleted file mode 100644 index 425f0aa9d687d..0000000000000 --- a/platform/platform-impl/src/com/intellij/ide/cloudConfiguration/CloudConfigurationProvider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2000-2016 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.ide.cloudConfiguration; - -import com.intellij.openapi.keymap.KeymapManager; -import com.intellij.util.ParameterizedRunnable; -import org.jetbrains.annotations.Nullable; - -/** - * @author Alexander Lobas - */ -public interface CloudConfigurationProvider { - @Nullable - String getSharedLaf(); - - @Nullable - String getSharedKeymap(); - - @Nullable - ParameterizedRunnable createSharedKeymap(); -} \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java b/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java index b605dbc9ce8ea..4306d8cd6f049 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java @@ -32,12 +32,6 @@ public abstract class AbstractCustomizeWizardStep extends JPanel { protected static final int SMALL_GAP = 10; protected static final int GAP = 20; - protected boolean mySkipFirstShowing; - - public boolean skipFirstShowing() { - return mySkipFirstShowing; - } - protected abstract String getTitle(); protected abstract String getHTMLHeader(); diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java index dcb8bdba23de5..a8fe1c307ed58 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java @@ -69,7 +69,6 @@ public CustomizeIDEWizardDialog(@NotNull CustomizeIDEWizardStepsProvider stepsPr AbstractCustomizeWizardStep.applyHeaderFooterStyle(myHeaderLabel); AbstractCustomizeWizardStep.applyHeaderFooterStyle(myFooterLabel); init(); - skipFirstShowing(); initCurrentStep(true); setSize(400, 300); System.setProperty(StartupActionScriptManager.STARTUP_WIZARD_MODE, "true"); @@ -176,16 +175,6 @@ protected void doOKAction() { super.doOKAction(); } - private void skipFirstShowing() { - myIndex = 0; - for (AbstractCustomizeWizardStep step : mySteps) { - if (!step.skipFirstShowing()) { - myIndex = mySteps.indexOf(step); - return; - } - } - } - private void initCurrentStep(boolean forward) { final AbstractCustomizeWizardStep myCurrentStep = mySteps.get(myIndex); myCurrentStep.beforeShown(forward); diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIdeaWizardStepsProvider.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIdeaWizardStepsProvider.java index 5903bfba20796..22c8d1181b143 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIdeaWizardStepsProvider.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIdeaWizardStepsProvider.java @@ -28,9 +28,6 @@ public void initSteps(@NotNull CustomizeIDEWizardDialog dialog, @NotNull List" + style + "

" + sharedKeymap + " keymap

")); - add(panel); - group.add(button); - button.setSelected(true); - } - mySkipFirstShowing = sharedKeymap != null; - } - - public static void applySharedKeymap() { - CloudConfigurationProvider provider = CloudConfigurationManager.getCustomizeProvider(); - String keymap = provider.getSharedKeymap(); - if (keymap != null) { - ParameterizedRunnable runnable = provider.createSharedKeymap(); - if (runnable == null) { - WelcomeWizardUtil.setWizardKeymap(keymap); - } - else { - WelcomeWizardUtil.setWizardKeymap(runnable); - } - } + macRadioButton.setSelected(true); } @Override diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java index 6a76033d715a5..9ba7e502c9d40 100644 --- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java +++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java @@ -17,7 +17,6 @@ import com.intellij.CommonBundle; import com.intellij.ide.WelcomeWizardUtil; -import com.intellij.ide.cloudConfiguration.CloudConfigurationManager; import com.intellij.ide.ui.LafManager; import com.intellij.ide.ui.laf.IntelliJLaf; import com.intellij.ide.ui.laf.LafManagerImpl; @@ -28,8 +27,6 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.util.IconUtil; import com.intellij.util.ui.UIUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; @@ -92,7 +89,7 @@ public CustomizeUIThemeStepPanel() { myColumnMode = myThemes.size() > 2; JPanel buttonsPanel = new JPanel(new GridLayout(myColumnMode ? myThemes.size() : 1, myColumnMode ? 1 : myThemes.size(), 5, 5)); ButtonGroup group = new ButtonGroup(); - final ThemeInfo myDefaultTheme = getDefaultTheme(); + final ThemeInfo myDefaultTheme = myThemes.iterator().next(); for (final ThemeInfo theme : myThemes) { final JRadioButton radioButton = new JRadioButton(theme.name, myDefaultTheme == theme); @@ -128,33 +125,6 @@ public CustomizeUIThemeStepPanel() { myInitial = false; } - @NotNull - private ThemeInfo getDefaultTheme() { - String sharedLaf = CloudConfigurationManager.getCustomizeProvider().getSharedLaf(); - if (sharedLaf != null) { - ThemeInfo theme = findTheme(sharedLaf); - if (theme == null && AQUA.name.equals(sharedLaf)) { - theme = findTheme(INTELLIJ.name); - } - if (theme != null) { - return theme; - } - } - - return myThemes.iterator().next(); - } - - @Nullable - private ThemeInfo findTheme(@NotNull String name) { - for (ThemeInfo theme : myThemes) { - if (name.equals(theme.name)) { - mySkipFirstShowing = true; - return theme; - } - } - return null; - } - protected void initThemes(Collection result) { if (SystemInfo.isMac) { result.add(LafManagerImpl.useIntelliJInsteadOfAqua() ? INTELLIJ : AQUA); diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapChangeListener.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapChangeListener.java deleted file mode 100644 index 7e10c2128d348..0000000000000 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapChangeListener.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2000-2016 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.keymap.impl; - -import org.jetbrains.annotations.NotNull; - -import java.util.List; - -/** - * @author Alexander Lobas - */ -public interface KeymapChangeListener { - void onShortcutChanged(@NotNull List actionIds); -} \ No newline at end of file diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java index 937cbfd83ced6..6edb5b52e4e51 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapImpl.java @@ -124,8 +124,6 @@ public KeymapImpl copyTo(@NotNull final KeymapImpl otherKeymap) { otherKeymap.cleanShortcutsCache(); - List changedActionIds = getChangedActionIds(otherKeymap); - otherKeymap.myActionId2ListOfShortcuts.clear(); otherKeymap.myActionId2ListOfShortcuts.ensureCapacity(myActionId2ListOfShortcuts.size()); myActionId2ListOfShortcuts.forEachEntry(new TObjectObjectProcedure>() { @@ -135,38 +133,9 @@ public boolean execute(String actionId, OrderedSet shortcuts) { return true; } }); - - if (!ContainerUtil.isEmpty(changedActionIds)) { - otherKeymap.fireShortcutChanged(changedActionIds); - } - return otherKeymap; } - @Nullable - private List getChangedActionIds(@NotNull KeymapImpl otherKeymap) { - if (!otherKeymap.isInternalKeymapListener()) { - return null; - } - List changedActionIds = new ArrayList<>(); - Set oldKeys = otherKeymap.myActionId2ListOfShortcuts.keySet(); - Set newKeys = new HashSet<>(myActionId2ListOfShortcuts.keySet()); - - for (String key : oldKeys) { - if (newKeys.remove(key)) { - if (!Comparing.equal(otherKeymap.myActionId2ListOfShortcuts.get(key), myActionId2ListOfShortcuts.get(key))) { - changedActionIds.add(key); - } - } - else { - changedActionIds.add(key); - } - } - changedActionIds.addAll(newKeys); - - return changedActionIds; - } - public boolean equals(Object object) { if (!(object instanceof Keymap)) return false; KeymapImpl secondKeymap = (KeymapImpl)object; @@ -576,10 +545,6 @@ private KeymapManagerEx getKeymapManager() { return myKeymapManager; } - public void setKeymapManager(@NotNull KeymapManagerEx keymapManager) { - myKeymapManager = keymapManager; - } - /** * @param keymapElement element which corresponds to "keymap" tag. */ @@ -782,7 +747,7 @@ public static String getKeyShortcutString(KeyStroke keyStroke) { * @return string representation of passed mouse shortcut. This method should * be used only for serializing of the MouseShortcut */ - public static String getMouseShortcutString(MouseShortcut shortcut) { + private static String getMouseShortcutString(MouseShortcut shortcut) { if (Registry.is("ide.mac.forceTouch") && shortcut instanceof PressureShortcut) { return "Force touch"; @@ -924,23 +889,6 @@ public void removeShortcutChangeListener(Listener listener) { myListeners.remove(listener); } - private boolean isInternalKeymapListener() { - for (Listener listener : myListeners) { - if (listener instanceof KeymapChangeListener) { - return true; - } - } - return false; - } - - private void fireShortcutChanged(@NotNull List actionIds) { - for (Listener listener : myListeners) { - if (listener instanceof KeymapChangeListener) { - ((KeymapChangeListener)listener).onShortcutChanged(actionIds); - } - } - } - private void fireShortcutChanged(String actionId) { for (Listener listener : myListeners) { listener.onShortcutChanged(actionId); diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java index 28c6c79819dea..1f3fbc381cc45 100644 --- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java @@ -19,7 +19,6 @@ import com.intellij.openapi.Disposable; import com.intellij.openapi.components.*; import com.intellij.openapi.keymap.Keymap; -import com.intellij.openapi.keymap.KeymapManager; import com.intellij.openapi.keymap.KeymapManagerListener; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.options.Scheme; @@ -28,7 +27,6 @@ import com.intellij.openapi.options.SchemesManagerFactory; import com.intellij.openapi.util.*; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.ParameterizedRunnable; import com.intellij.util.containers.ContainerUtil; import org.jdom.Element; import org.jetbrains.annotations.NonNls; @@ -96,11 +94,6 @@ public void onCurrentSchemeChanged(@Nullable Scheme oldScheme) { } mySchemesManager.loadSchemes(); - ParameterizedRunnable runnable = WelcomeWizardUtil.getWizardCreateKeymapRunnable(); - if (runnable != null) { - runnable.run(this); - } - //noinspection AssignmentToStaticFieldFromInstanceMethod ourKeymapManagerInitialized = true; } From 3a0dbe157307fa6ab9de6989329599b94e5a1db5 Mon Sep 17 00:00:00 2001 From: Dmitry Batrak Date: Wed, 20 Jul 2016 18:57:33 +0300 Subject: [PATCH 36/67] IDEA-158635 Toggling Ligatures does not update font preview --- .../src/com/intellij/application/options/colors/FontOptions.java | 1 + 1 file changed, 1 insertion(+) diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java b/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java index 59e3f116c0db2..35c49f0653eb1 100644 --- a/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java +++ b/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java @@ -198,6 +198,7 @@ public void keyPressed(KeyEvent e) { myEnableLigaturesCheckbox.addActionListener(e -> { getFontPreferences().setUseLigatures(myEnableLigaturesCheckbox.isSelected()); updateWarningIconVisibility(warningIcon); + updateDescription(true); }); } From 515eb4afa1e847612bf77313eac3f9086a6d6877 Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Tue, 19 Jul 2016 22:49:28 +0300 Subject: [PATCH 37/67] [file-history] copy provider for commit details IDEA-158666 --- .../vcs/history/FileHistoryPanelImpl.java | 152 +++++++++--------- 1 file changed, 73 insertions(+), 79 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java index dcf3504a58440..a9687993fabdb 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java @@ -78,6 +78,8 @@ import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; +import javax.swing.text.BadLocationException; +import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; @@ -88,6 +90,7 @@ import java.awt.datatransfer.Transferable; import java.awt.event.InputEvent; import java.io.IOException; +import java.io.StringWriter; import java.util.*; import java.util.List; @@ -174,30 +177,12 @@ protected boolean isStatusVisible() { } }; myCommentsStatus.setText("Commit message"); - myComments = new JEditorPane(UIUtil.HTML_MIME, "") { - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - myCommentsStatus.paint(this, g); - } - - @Override - public Color getBackground() { - return UIUtil.getEditorPaneBackground(); - } - }; + myComments = new MyCommentsPane(); myCommentsStatus.attachTo(myComments); - myComments.setPreferredSize(new Dimension(150, 100)); - myComments.setEditable(false); - myComments.setOpaque(false); - myComments.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); - myComments.addHyperlinkListener(BrowserHyperlinkListener.INSTANCE); myRevisionsOrder = new HashMap<>(); refreshRevisionsOrder(); - replaceTransferable(); - myUpdateAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, myProject); final HistoryAsTreeProvider treeHistoryProvider = myHistorySession.getHistoryAsTreeProvider(); @@ -335,66 +320,6 @@ public VcsRevisionNumber getStartingRevision() { return myStartingRevision; } - private void replaceTransferable() { - final TransferHandler originalTransferHandler = myComments.getTransferHandler(); - - final TransferHandler newHandler = new TransferHandler("copy") { - @Override - public void exportAsDrag(final JComponent comp, final InputEvent e, final int action) { - originalTransferHandler.exportAsDrag(comp, e, action); - } - - @Override - public void exportToClipboard(final JComponent comp, final Clipboard clip, final int action) throws IllegalStateException { - if ((action == COPY || action == MOVE) - && (getSourceActions(comp) & action) != 0) { - - String selectedText = myComments.getSelectedText(); - final Transferable t; - if (selectedText == null) { - t = new TextTransferable(myComments.getText(), myOriginalComment); - } - else { - t = new TextTransferable(selectedText); - } - try { - clip.setContents(t, null); - exportDone(comp, t, action); - return; - } - catch (IllegalStateException ise) { - exportDone(comp, t, NONE); - throw ise; - } - } - - exportDone(comp, null, NONE); - } - - @Override - public boolean importData(final JComponent comp, final Transferable t) { - return originalTransferHandler.importData(comp, t); - } - - @Override - public boolean canImport(final JComponent comp, final DataFlavor[] transferFlavors) { - return originalTransferHandler.canImport(comp, transferFlavors); - } - - @Override - public int getSourceActions(final JComponent c) { - return originalTransferHandler.getSourceActions(c); - } - - @Override - public Icon getVisualRepresentation(final Transferable t) { - return originalTransferHandler.getVisualRepresentation(t); - } - }; - - myComments.setTransferHandler(newHandler); - } - private DualViewColumnInfo[] createColumnList(Project project, VcsHistoryProvider provider, final VcsHistorySession session) { final VcsDependentHistoryComponents components = provider.getUICustomization(session, this); myAdditionalDetails = components.getDetailsComponent(); @@ -1787,4 +1712,73 @@ public void setSelected(AnActionEvent e, boolean state) { setupDetails(); } } + + private class MyCommentsPane extends JEditorPane implements DataProvider, CopyProvider { + public MyCommentsPane() { + super(UIUtil.HTML_MIME, ""); + + setPreferredSize(new Dimension(150, 100)); + setEditable(false); + setOpaque(false); + putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); + addHyperlinkListener(BrowserHyperlinkListener.INSTANCE); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + myCommentsStatus.paint(this, g); + } + + @Override + public Color getBackground() { + return UIUtil.getEditorPaneBackground(); + } + + @Override + public String getSelectedText() { + javax.swing.text.Document doc = getDocument(); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + try { + Position p0 = doc.createPosition(start); + Position p1 = doc.createPosition(end); + StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); + getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); + + return StringUtil.removeHtmlTags(sw.toString()); + } + catch (BadLocationException | IOException e) { + LOG.warn(e); + } + return super.getSelectedText(); + } + + @Override + public void performCopy(@NotNull DataContext dataContext) { + String selectedText = getSelectedText(); + if (selectedText == null || selectedText.isEmpty()) selectedText = myOriginalComment; + CopyPasteManager.getInstance().setContents(new StringSelection(selectedText)); + } + + @Override + public boolean isCopyEnabled(@NotNull DataContext dataContext) { + return true; + } + + @Override + public boolean isCopyVisible(@NotNull DataContext dataContext) { + return true; + } + + @Nullable + @Override + public Object getData(@NonNls String dataId) { + if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) { + return this; + } + return null; + } + } } From 66d87ec01d70fc9727d8c72b51aa260341995253 Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Tue, 19 Jul 2016 23:03:26 +0300 Subject: [PATCH 38/67] [file-history] extract code similar between details in history and log --- .../vcs/history/FileHistoryPanelImpl.java | 31 +--------- .../src/com/intellij/util/ui/HtmlPanel.java | 62 +++++++++++++++++++ .../vcs/log/ui/frame/CommitPanel.java | 52 ++++------------ 3 files changed, 75 insertions(+), 70 deletions(-) create mode 100644 platform/vcs-impl/src/com/intellij/util/ui/HtmlPanel.java diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java index a9687993fabdb..9d9d8fa2c5800 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java @@ -78,8 +78,6 @@ import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; -import javax.swing.text.BadLocationException; -import javax.swing.text.Position; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; @@ -90,7 +88,6 @@ import java.awt.datatransfer.Transferable; import java.awt.event.InputEvent; import java.io.IOException; -import java.io.StringWriter; import java.util.*; import java.util.List; @@ -1713,15 +1710,9 @@ public void setSelected(AnActionEvent e, boolean state) { } } - private class MyCommentsPane extends JEditorPane implements DataProvider, CopyProvider { + private class MyCommentsPane extends HtmlPanel implements DataProvider, CopyProvider { public MyCommentsPane() { - super(UIUtil.HTML_MIME, ""); - setPreferredSize(new Dimension(150, 100)); - setEditable(false); - setOpaque(false); - putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); - addHyperlinkListener(BrowserHyperlinkListener.INSTANCE); } @Override @@ -1735,26 +1726,6 @@ public Color getBackground() { return UIUtil.getEditorPaneBackground(); } - @Override - public String getSelectedText() { - javax.swing.text.Document doc = getDocument(); - int start = getSelectionStart(); - int end = getSelectionEnd(); - - try { - Position p0 = doc.createPosition(start); - Position p1 = doc.createPosition(end); - StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); - getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); - - return StringUtil.removeHtmlTags(sw.toString()); - } - catch (BadLocationException | IOException e) { - LOG.warn(e); - } - return super.getSelectedText(); - } - @Override public void performCopy(@NotNull DataContext dataContext) { String selectedText = getSelectedText(); diff --git a/platform/vcs-impl/src/com/intellij/util/ui/HtmlPanel.java b/platform/vcs-impl/src/com/intellij/util/ui/HtmlPanel.java new file mode 100644 index 0000000000000..b559996e39048 --- /dev/null +++ b/platform/vcs-impl/src/com/intellij/util/ui/HtmlPanel.java @@ -0,0 +1,62 @@ +/* + * Copyright 2000-2016 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.util.ui; + +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.ui.BrowserHyperlinkListener; + +import javax.swing.*; +import javax.swing.event.HyperlinkEvent; +import javax.swing.event.HyperlinkListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.Position; +import java.io.IOException; +import java.io.StringWriter; + +public class HtmlPanel extends JEditorPane implements HyperlinkListener { + public HtmlPanel() { + super(UIUtil.HTML_MIME, ""); + setEditable(false); + setOpaque(false); + putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); + addHyperlinkListener(this); + } + + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e); + } + + @Override + public String getSelectedText() { + Document doc = getDocument(); + int start = getSelectionStart(); + int end = getSelectionEnd(); + + try { + Position p0 = doc.createPosition(start); + Position p1 = doc.createPosition(end); + StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); + getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); + + return StringUtil.removeHtmlTags(sw.toString()); + } + catch (BadLocationException | IOException ignored) { + } + return super.getSelectedText(); + } +} diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/CommitPanel.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/CommitPanel.java index 0e7181ee24f92..1984101c2dab0 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/CommitPanel.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/CommitPanel.java @@ -20,9 +20,9 @@ import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkHtmlRenderer; +import com.intellij.util.ui.HtmlPanel; import com.intellij.openapi.vcs.ui.FontUtil; import com.intellij.openapi.vfs.VirtualFile; -import com.intellij.ui.BrowserHyperlinkListener; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBPanel; import com.intellij.util.containers.ContainerUtil; @@ -45,13 +45,8 @@ import javax.swing.border.CompoundBorder; import javax.swing.border.MatteBorder; import javax.swing.event.HyperlinkEvent; -import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; -import javax.swing.text.Document; -import javax.swing.text.Position; import java.awt.*; -import java.io.IOException; -import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.List; @@ -169,7 +164,7 @@ public static String formatDateTime(long time) { return " on " + DateFormatUtil.formatDate(time) + " at " + DateFormatUtil.formatTime(time); } - private static class DataPanel extends JEditorPane { + private static class DataPanel extends HtmlPanel { private static final int PER_ROW = 3; private static final String LINK_HREF = "show-hide-branches"; @@ -181,27 +176,24 @@ private static class DataPanel extends JEditorPane { private boolean myExpanded = false; DataPanel(@NotNull Project project, boolean multiRoot) { - super(UIUtil.HTML_MIME, ""); myProject = project; myMultiRoot = multiRoot; - setEditable(false); - setOpaque(false); - putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); DefaultCaret caret = (DefaultCaret)getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); setBorder(JBUI.Borders.empty(BOTTOM_BORDER, ReferencesPanel.H_GAP, 0, 0)); + } - addHyperlinkListener(e -> { - if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && LINK_HREF.equals(e.getDescription())) { - myExpanded = !myExpanded; - update(); - } - else { - BrowserHyperlinkListener.INSTANCE.hyperlinkUpdate(e); - } - }); + @Override + public void hyperlinkUpdate(HyperlinkEvent e) { + if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED && LINK_HREF.equals(e.getDescription())) { + myExpanded = !myExpanded; + update(); + } + else { + super.hyperlinkUpdate(e); + } } @Override @@ -392,26 +384,6 @@ else if (authorTime != commitTime) { return authorText; } - @Override - public String getSelectedText() { - Document doc = getDocument(); - int start = getSelectionStart(); - int end = getSelectionEnd(); - - try { - Position p0 = doc.createPosition(start); - Position p1 = doc.createPosition(end); - StringWriter sw = new StringWriter(p1.getOffset() - p0.getOffset()); - getEditorKit().write(sw, doc, p0.getOffset(), p1.getOffset() - p0.getOffset()); - - return StringUtil.removeHtmlTags(sw.toString()); - } - catch (BadLocationException | IOException e) { - LOG.warn(e); - } - return super.getSelectedText(); - } - @Override public Color getBackground() { return getCommitDetailsBackground(); From d8fa76b6538d0d8a4a342e370b91d92288fdef5a Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Tue, 19 Jul 2016 23:42:33 +0300 Subject: [PATCH 39/67] [file-history] move myOriginalComment field into MyCommentsPane --- .../vcs/history/FileHistoryPanelImpl.java | 102 ++++++++++-------- 1 file changed, 56 insertions(+), 46 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java index 9d9d8fa2c5800..ff25a2e4553ad 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java @@ -82,11 +82,7 @@ import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import java.awt.*; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; -import java.awt.datatransfer.Transferable; -import java.awt.event.InputEvent; import java.io.IOException; import java.util.*; import java.util.List; @@ -102,7 +98,7 @@ public class FileHistoryPanelImpl extends PanelWithActionsAndCloseButton impleme private static final String COMMIT_MESSAGE_TITLE = VcsBundle.message("label.selected.revision.commit.message"); private static final String VCS_HISTORY_ACTIONS_GROUP = "VcsHistoryActionsGroup"; @NotNull private final Project myProject; - private final JEditorPane myComments; + private final MyCommentsPane myComments; private final StatusText myCommentsStatus; private final DefaultActionGroup myPopupActions; private final AbstractVcs myVcs; @@ -125,7 +121,6 @@ public int compare(VcsFileRevision o1, VcsFileRevision o2) { }; private JComponent myAdditionalDetails; private Consumer myListener; - private String myOriginalComment = ""; private VcsHistorySession myHistorySession; private VcsFileRevision myBottomRevisionForShowDiff; private volatile boolean myInRefresh; @@ -170,11 +165,17 @@ public FileHistoryPanelImpl(AbstractVcs vcs, myCommentsStatus = new StatusText() { @Override protected boolean isStatusVisible() { - return StringUtil.isEmpty(myOriginalComment); + return myComments.isEmpty(); } }; myCommentsStatus.setText("Commit message"); - myComments = new MyCommentsPane(); + myComments = new MyCommentsPane() { + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + myCommentsStatus.paint(this, g); + } + }; myCommentsStatus.attachTo(myComments); myRevisionsOrder = new HashMap<>(); @@ -418,42 +419,10 @@ private void createDualView() { private void updateMessage() { List selection = getSelection(); + myComments.update(selection); if (selection.isEmpty()) { - myComments.setText(""); - myOriginalComment = ""; return; } - boolean addRevisionInfo = selection.size() > 1; - StringBuilder original = new StringBuilder(); - StringBuilder html = new StringBuilder(); - for (TreeNodeOnVcsRevision revision : selection) { - String message = revision.getCommitMessage(); - if (StringUtil.isEmpty(message)) continue; - if (original.length() > 0) { - original.append("\n\n"); - html.append("

"); - } - if (addRevisionInfo) { - String revisionInfo = getPresentableText(revision.getRevision(), false); - html.append("") - .append(getHtmlWithFonts(revisionInfo)).append("
"); - original.append(revisionInfo).append("\n"); - } - original.append(message); - html.append(getHtmlWithFonts(formatTextWithLinks(myVcs.getProject(), message))); - } - myOriginalComment = original.toString(); - if (StringUtil.isEmpty(myOriginalComment)) { - myComments.setText(""); - } - else { - myComments.setText("" + - UIUtil.getCssFontDeclaration(VcsHistoryUtil.getCommitDetailsFont()) + - "" + - html.toString() + - ""); - myComments.setCaretPosition(0); - } if (myListener != null) { myListener.consume(selection.get(0).getRevision()); } @@ -876,7 +845,9 @@ public String getPreferredStringValue() { private static class AuthorCellRenderer extends ColoredTableCellRenderer { private String myTooltipText; - /** @noinspection MethodNamesDifferingOnlyByCase*/ + /** + * @noinspection MethodNamesDifferingOnlyByCase + */ public void setTooltipText(final String text) { myTooltipText = text; } @@ -1711,14 +1682,53 @@ public void setSelected(AnActionEvent e, boolean state) { } private class MyCommentsPane extends HtmlPanel implements DataProvider, CopyProvider { + private String myOriginalComment = ""; + public MyCommentsPane() { setPreferredSize(new Dimension(150, 100)); } - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - myCommentsStatus.paint(this, g); + public void update(@NotNull List selection) { + if (selection.isEmpty()) { + setText(""); + myOriginalComment = ""; + return; + } + boolean addRevisionInfo = selection.size() > 1; + StringBuilder original = new StringBuilder(); + StringBuilder html = new StringBuilder(); + for (TreeNodeOnVcsRevision revision : selection) { + String message = revision.getCommitMessage(); + if (StringUtil.isEmpty(message)) continue; + if (original.length() > 0) { + original.append("\n\n"); + html.append("

"); + } + if (addRevisionInfo) { + String revisionInfo = getPresentableText(revision.getRevision(), false); + html.append("") + .append(getHtmlWithFonts(revisionInfo)).append("
"); + original.append(revisionInfo).append("\n"); + } + original.append(message); + html.append(getHtmlWithFonts(formatTextWithLinks(myVcs.getProject(), message))); + } + myOriginalComment = original.toString(); + if (StringUtil.isEmpty(myOriginalComment)) { + setText(""); + } + else { + setText("" + + UIUtil.getCssFontDeclaration(VcsHistoryUtil.getCommitDetailsFont()) + + "" + + html.toString() + + ""); + setCaretPosition(0); + } + } + + public boolean isEmpty() { + return StringUtil.isEmpty(myOriginalComment); } @Override From f1fa7db481381287ccb45ab7eccc8e85c2957055 Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Tue, 19 Jul 2016 23:54:08 +0300 Subject: [PATCH 40/67] [file-history] remove myOriginalComment field --- .../vcs/history/FileHistoryPanelImpl.java | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java index ff25a2e4553ad..634750de3a978 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java @@ -1682,7 +1682,7 @@ public void setSelected(AnActionEvent e, boolean state) { } private class MyCommentsPane extends HtmlPanel implements DataProvider, CopyProvider { - private String myOriginalComment = ""; + @NotNull private String myText = ""; public MyCommentsPane() { setPreferredSize(new Dimension(150, 100)); @@ -1691,44 +1691,39 @@ public MyCommentsPane() { public void update(@NotNull List selection) { if (selection.isEmpty()) { setText(""); - myOriginalComment = ""; return; } boolean addRevisionInfo = selection.size() > 1; - StringBuilder original = new StringBuilder(); StringBuilder html = new StringBuilder(); for (TreeNodeOnVcsRevision revision : selection) { String message = revision.getCommitMessage(); if (StringUtil.isEmpty(message)) continue; - if (original.length() > 0) { - original.append("\n\n"); + if (html.length() > 0) { html.append("

"); } if (addRevisionInfo) { String revisionInfo = getPresentableText(revision.getRevision(), false); html.append("") .append(getHtmlWithFonts(revisionInfo)).append("
"); - original.append(revisionInfo).append("\n"); } - original.append(message); html.append(getHtmlWithFonts(formatTextWithLinks(myVcs.getProject(), message))); } - myOriginalComment = original.toString(); - if (StringUtil.isEmpty(myOriginalComment)) { + myText = html.toString(); + if (myText.isEmpty()) { setText(""); } else { setText("" + UIUtil.getCssFontDeclaration(VcsHistoryUtil.getCommitDetailsFont()) + "" + - html.toString() + + myText + ""); setCaretPosition(0); } } public boolean isEmpty() { - return StringUtil.isEmpty(myOriginalComment); + return StringUtil.isEmpty(myText); } @Override @@ -1739,7 +1734,7 @@ public Color getBackground() { @Override public void performCopy(@NotNull DataContext dataContext) { String selectedText = getSelectedText(); - if (selectedText == null || selectedText.isEmpty()) selectedText = myOriginalComment; + if (selectedText == null || selectedText.isEmpty()) selectedText = StringUtil.removeHtmlTags(getText()); CopyPasteManager.getInstance().setContents(new StringSelection(selectedText)); } From d4c8dc223d566c93024f4fced54bf8f56d029d83 Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Wed, 20 Jul 2016 00:06:26 +0300 Subject: [PATCH 41/67] [file-history] move status text inside comments pane --- .../vcs/history/FileHistoryPanelImpl.java | 37 +++++++++---------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java index 634750de3a978..7292629cf3d0e 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/history/FileHistoryPanelImpl.java @@ -99,7 +99,6 @@ public class FileHistoryPanelImpl extends PanelWithActionsAndCloseButton impleme private static final String VCS_HISTORY_ACTIONS_GROUP = "VcsHistoryActionsGroup"; @NotNull private final Project myProject; private final MyCommentsPane myComments; - private final StatusText myCommentsStatus; private final DefaultActionGroup myPopupActions; private final AbstractVcs myVcs; private final VcsHistoryProvider myProvider; @@ -162,21 +161,7 @@ public FileHistoryPanelImpl(AbstractVcs vcs, myDiffHandler = customDiffHandler == null ? new StandardDiffFromHistoryHandler() : customDiffHandler; final DualViewColumnInfo[] columns = createColumnList(myVcs.getProject(), provider, session); - myCommentsStatus = new StatusText() { - @Override - protected boolean isStatusVisible() { - return myComments.isEmpty(); - } - }; - myCommentsStatus.setText("Commit message"); - myComments = new MyCommentsPane() { - @Override - protected void paintComponent(Graphics g) { - super.paintComponent(g); - myCommentsStatus.paint(this, g); - } - }; - myCommentsStatus.attachTo(myComments); + myComments = new MyCommentsPane(); myRevisionsOrder = new HashMap<>(); refreshRevisionsOrder(); @@ -1682,12 +1667,28 @@ public void setSelected(AnActionEvent e, boolean state) { } private class MyCommentsPane extends HtmlPanel implements DataProvider, CopyProvider { + @NotNull private final StatusText myStatusText; @NotNull private String myText = ""; public MyCommentsPane() { + myStatusText = new StatusText() { + @Override + protected boolean isStatusVisible() { + return StringUtil.isEmpty(myText); + } + }; + myStatusText.setText("Commit message"); + myStatusText.attachTo(this); + setPreferredSize(new Dimension(150, 100)); } + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + myStatusText.paint(this, g); + } + public void update(@NotNull List selection) { if (selection.isEmpty()) { setText(""); @@ -1722,10 +1723,6 @@ public void update(@NotNull List selection) { } } - public boolean isEmpty() { - return StringUtil.isEmpty(myText); - } - @Override public Color getBackground() { return UIUtil.getEditorPaneBackground(); From 5170b5d3eab60053a741b8ee4b0a11cc9e44ebac Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Wed, 20 Jul 2016 17:47:05 +0200 Subject: [PATCH 42/67] introduce constant: don't traverse inside class or lambda to check unhandled throwables; check for calls to instance methods though --- .../IntroduceConstantHandler.java | 14 ++++++++++++++ .../AnonymousClassWithThrownClause.java | 17 +++++++++++++++++ .../AnonymousClassWithThrownClause_after.java | 19 +++++++++++++++++++ .../refactoring/IntroduceConstantTest.java | 6 ++++++ 4 files changed, 56 insertions(+) create mode 100644 java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause.java create mode 100644 java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause_after.java diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java index aa2f8bd60c04a..40472c6bc7461 100644 --- a/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java +++ b/java/java-impl/src/com/intellij/refactoring/introduceField/IntroduceConstantHandler.java @@ -230,6 +230,7 @@ protected OccurrenceManager createOccurrenceManager(final PsiExpression selected private static class IsStaticFinalInitializerExpression extends ClassMemberReferencesVisitor { private PsiElement myElementReference; private final PsiExpression myInitializer; + private boolean myCheckThrowables = true; public IsStaticFinalInitializerExpression(PsiClass aClass, PsiExpression initializer) { super(aClass); @@ -251,12 +252,25 @@ public void visitReferenceExpression(PsiReferenceExpression expression) { @Override public void visitCallExpression(PsiCallExpression callExpression) { super.visitCallExpression(callExpression); + if (!myCheckThrowables) return; final List checkedExceptions = ExceptionUtil.getThrownCheckedExceptions(new PsiElement[]{callExpression}); if (!checkedExceptions.isEmpty()) { myElementReference = callExpression; } } + @Override + public void visitClass(PsiClass aClass) { + myCheckThrowables = false; + super.visitClass(aClass); + } + + @Override + public void visitLambdaExpression(PsiLambdaExpression expression) { + myCheckThrowables = false; + super.visitLambdaExpression(expression); + } + protected void visitClassMemberReferenceElement(PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) { if (!classMember.hasModifierProperty(PsiModifier.STATIC)) { myElementReference = classMemberReference; diff --git a/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause.java b/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause.java new file mode 100644 index 0000000000000..c97d1d83217b8 --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause.java @@ -0,0 +1,17 @@ +import java.io.IOException; +class Test { + void bar() throws IOException {} + + I get() { + return new I() { + @Override + public void foo() throws IOException { + bar(); + } + }; + } +} + +interface I { + void foo() throws IOException; +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause_after.java b/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause_after.java new file mode 100644 index 0000000000000..4f348e7fb8cc7 --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceConstant/AnonymousClassWithThrownClause_after.java @@ -0,0 +1,19 @@ +import java.io.IOException; +class Test { + public static final I xxx = new I() { + @Override + public void foo() throws IOException { + bar(); + } + }; + + void bar() throws IOException {} + + I get() { + return xxx; + } +} + +interface I { + void foo() throws IOException; +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceConstantTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceConstantTest.java index b92d69600d9f8..c2edd708904db 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceConstantTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceConstantTest.java @@ -52,6 +52,12 @@ public void testEnumConstant() throws Exception { doTest(true); } + public void testAnonymousClassWithThrownClause() throws Exception { + configureByFile(BASE_PATH + getTestName(false) + ".java"); + new MockIntroduceConstantHandler(null).invoke(getProject(), getEditor(), getFile(), null); + checkResultByFile(BASE_PATH + getTestName(false) + "_after.java"); + } + public void testAnnotationDescription() throws Exception { configureByFile(BASE_PATH + getTestName(false) + ".java"); new MockIntroduceConstantHandler(null).invoke(getProject(), getEditor(), getFile(), null); From b649b3a5117b15af1c5ba3b2572058cec03f1cbd Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Wed, 20 Jul 2016 18:04:39 +0200 Subject: [PATCH 43/67] pull up from anonymous: check for base class type instead of extends list --- .../util/classMembers/MemberInfoStorage.java | 12 +++++++++--- .../pullUp/PullUpFromAnonymousToInterface.java | 9 +++++++++ .../pullUp/PullUpFromAnonymousToInterface_after.java | 12 ++++++++++++ .../testSrc/com/intellij/refactoring/PullUpTest.java | 4 ++++ 4 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface.java create mode 100644 java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface_after.java diff --git a/java/java-impl/src/com/intellij/refactoring/util/classMembers/MemberInfoStorage.java b/java/java-impl/src/com/intellij/refactoring/util/classMembers/MemberInfoStorage.java index 34fd3241e3685..4cb8f4d30cf67 100644 --- a/java/java-impl/src/com/intellij/refactoring/util/classMembers/MemberInfoStorage.java +++ b/java/java-impl/src/com/intellij/refactoring/util/classMembers/MemberInfoStorage.java @@ -61,15 +61,21 @@ protected void buildSubClassesMap(PsiClass aClass) { private void buildSubClassesMap(PsiClass aClass, Set visited) { final PsiReferenceList extendsList = aClass.getExtendsList(); if (extendsList != null) { - buildSubClassesMapForList(extendsList.getReferencedTypes(), aClass, visited); + buildSubClassesMapForList(aClass, visited, extendsList.getReferencedTypes()); } final PsiReferenceList implementsList = aClass.getImplementsList(); if (implementsList != null) { - buildSubClassesMapForList(implementsList.getReferencedTypes(), aClass, visited); + buildSubClassesMapForList(aClass, visited, implementsList.getReferencedTypes()); + } + + if (aClass instanceof PsiAnonymousClass) { + buildSubClassesMapForList(aClass, visited, ((PsiAnonymousClass)aClass).getBaseClassType()); } } - private void buildSubClassesMapForList(final PsiClassType[] classesList, PsiClass aClass, Set processed) { + private void buildSubClassesMapForList(final PsiClass aClass, + final Set processed, + final PsiClassType... classesList) { for (PsiClassType element : classesList) { PsiClass resolved = element.resolve(); if (resolved != null && processed.add(resolved)) { diff --git a/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface.java b/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface.java new file mode 100644 index 0000000000000..a057fcedcc30c --- /dev/null +++ b/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface.java @@ -0,0 +1,9 @@ +class Test { + { + I i = new I() { + public void foo() {} + }; + } + + interface I {} +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface_after.java b/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface_after.java new file mode 100644 index 0000000000000..31a37f01bd242 --- /dev/null +++ b/java/java-tests/testData/refactoring/pullUp/PullUpFromAnonymousToInterface_after.java @@ -0,0 +1,12 @@ +class Test { + { + I i = new I() { + @Override + public void foo() {} + }; + } + + interface I { + void foo(); + } +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java index b2a1f6408d717..c74e41a213839 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java @@ -207,6 +207,10 @@ public void testPullUpAsAbstractInClass() throws Exception { doTest(false, new RefactoringTestUtil.MemberDescriptor("test", PsiMethod.class, true)); } + public void testPullUpFromAnonymousToInterface() throws Exception { + doTest(false, new RefactoringTestUtil.MemberDescriptor("foo", PsiMethod.class, true)); + } + private void doTest(RefactoringTestUtil.MemberDescriptor... membersToFind) { doTest(true, membersToFind); } From 705bcd43fe00a4ac9e6552f096d9017715fe08b0 Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Wed, 20 Jul 2016 18:13:03 +0200 Subject: [PATCH 44/67] descriptions of misspelled inspections --- .../src/inspectionDescriptions/MisspelledCompareTo.html | 9 --------- .../src/inspectionDescriptions/MisspelledHashcode.html | 9 --------- ...esDifferOnlyByCase.html => MisspelledMethodName.html} | 0 .../src/inspectionDescriptions/MisspelledSetUp.html | 9 --------- .../src/inspectionDescriptions/MisspelledTearDown.html | 9 --------- .../src/inspectionDescriptions/MisspelledToString.html | 9 --------- 6 files changed, 45 deletions(-) delete mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledCompareTo.html delete mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledHashcode.html rename plugins/InspectionGadgets/src/inspectionDescriptions/{MethodNamesDifferOnlyByCase.html => MisspelledMethodName.html} (100%) delete mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledSetUp.html delete mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledTearDown.html delete mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledToString.html diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledCompareTo.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledCompareTo.html deleted file mode 100644 index 1bb4d937b7378..0000000000000 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledCompareTo.html +++ /dev/null @@ -1,9 +0,0 @@ - - -Reports any declaration of a compareto() method, taking one argument. -Normally, this is a typo of compareTo(). - -

- - - \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledHashcode.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledHashcode.html deleted file mode 100644 index 5daace96dee46..0000000000000 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledHashcode.html +++ /dev/null @@ -1,9 +0,0 @@ - - -Reports any declaration of a hashcode() method, taking no arguments. -Normally, this is a typo of hashCode(). - -

- - - \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MethodNamesDifferOnlyByCase.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledMethodName.html similarity index 100% rename from plugins/InspectionGadgets/src/inspectionDescriptions/MethodNamesDifferOnlyByCase.html rename to plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledMethodName.html diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledSetUp.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledSetUp.html deleted file mode 100644 index dee6b015dc829..0000000000000 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledSetUp.html +++ /dev/null @@ -1,9 +0,0 @@ - - -Reports a setup() method on a JUnit test case. This is -normally a misspelling of setUp(), and is entirely too easy to make. - -

- - - \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledTearDown.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledTearDown.html deleted file mode 100644 index d8cf165295391..0000000000000 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledTearDown.html +++ /dev/null @@ -1,9 +0,0 @@ - - -Reports a teardown() method on a JUnit test case. This is -normally a misspelling of tearDown(), and is entirely too easy to make. - -

- - - \ No newline at end of file diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledToString.html b/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledToString.html deleted file mode 100644 index 417f92db6d2ff..0000000000000 --- a/plugins/InspectionGadgets/src/inspectionDescriptions/MisspelledToString.html +++ /dev/null @@ -1,9 +0,0 @@ - - -Reports any declaration of a tostring() method, taking one argument. -Normally, this is a typo of toString(). - -

- - - \ No newline at end of file From 7eb44355bf8e3fec1229c923bca4f944cfa10dd0 Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Wed, 20 Jul 2016 18:41:45 +0200 Subject: [PATCH 45/67] [platform] fixes unwanted file extension appending (IDEA-148656) --- .../refactoring/copy/CopyFilesOrDirectoriesDialog.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java index c79c8bd41fa79..ba412e965c8ea 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/copy/CopyFilesOrDirectoriesDialog.java @@ -23,7 +23,6 @@ import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.fileChooser.FileChooserDescriptor; import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory; -import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.ex.FileTypeChooser; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.keymap.KeymapUtil; @@ -44,7 +43,6 @@ import com.intellij.ui.components.JBLabelDecorator; import com.intellij.ui.components.JBTextField; import com.intellij.util.IncorrectOperationException; -import com.intellij.util.ObjectUtils; import com.intellij.util.PathUtil; import com.intellij.util.PathUtilRt; import com.intellij.util.ui.FormBuilder; @@ -113,10 +111,6 @@ public CopyFilesOrDirectoriesDialog(PsiElement[] elements, @Nullable PsiDirector VirtualFile vFile = file.getVirtualFile(); text = RefactoringBundle.message(doClone ? "copy.files.clone.file.0" : "copy.files.copy.file.0", shortenPath(vFile)); String fileName = vFile.isInLocalFileSystem() ? vFile.getName() : PathUtil.suggestFileName(file.getName(), true, true); - if (StringUtil.isEmpty(vFile.getExtension())) { - FileType type = ObjectUtils.notNull(file.getLanguage().getAssociatedFileType(), file.getFileType()); - fileName = PathUtil.makeFileName(fileName, type.getDefaultExtension()); - } myNewNameField.setText(fileName); int dotIdx = fileName.lastIndexOf('.'); if (dotIdx > 0) { From d62aee954c8050fc58f4d9b4358d4025e5a51e20 Mon Sep 17 00:00:00 2001 From: Alexey Utkin Date: Wed, 20 Jul 2016 20:00:45 +0300 Subject: [PATCH 46/67] CPP-778 Semantic per-variable highlighting (new approach for small set of rainbow colors) --- .../daemon/JavaRainbowVisitor.java | 77 +++++++++++++++++ .../daemon/LightRainbowHighlightingTest.java | 84 +++++++++++++++++++ .../codeHighlighting/RainbowHighlighter.java | 67 ++++++++++----- .../codeInsight/daemon/RainbowVisitor.java | 42 ++++++++++ .../daemon/impl/HighlightInfo.java | 25 +----- resources/src/META-INF/IdeaPlugin.xml | 1 + 6 files changed, 251 insertions(+), 45 deletions(-) create mode 100644 java/java-impl/src/com/intellij/codeInsight/daemon/JavaRainbowVisitor.java create mode 100644 java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightRainbowHighlightingTest.java diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/JavaRainbowVisitor.java b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaRainbowVisitor.java new file mode 100644 index 0000000000000..34fb907a57a09 --- /dev/null +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/JavaRainbowVisitor.java @@ -0,0 +1,77 @@ +/* + * Copyright 2000-2016 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.daemon; + +import com.intellij.codeHighlighting.RainbowHighlighter; +import com.intellij.codeInsight.daemon.impl.HighlightInfo; +import com.intellij.codeInsight.daemon.impl.HighlightVisitor; +import com.intellij.ide.highlighter.JavaHighlightingColors; +import com.intellij.openapi.util.Pair; +import com.intellij.psi.*; +import com.intellij.psi.util.PsiTreeUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class JavaRainbowVisitor extends RainbowVisitor { + @Override + public boolean suitableForFile(@NotNull PsiFile file) { + return file instanceof PsiJavaFile; + } + + @Override + public void visit(@NotNull PsiElement element) { + if (!RainbowHighlighter.isRainbowEnabled()) return; + + if (element instanceof PsiReferenceExpression + || element instanceof PsiLocalVariable + || element instanceof PsiParameter) { + PsiElement context = PsiTreeUtil.findFirstParent(element, p -> p instanceof PsiMethod); + if (context != null) { + HighlightInfo attrs = getRainbowSymbolKey( + context, + element instanceof PsiReferenceExpression + ? Pair.create(element, ((PsiReferenceExpression)element).resolve()) + : Pair.create(((PsiVariable)element).getNameIdentifier(), element)); + if (attrs != null) { + addInfo(attrs); + } + } + } + } + + @Nullable + private HighlightInfo getRainbowSymbolKey(@NotNull PsiElement context, @NotNull Pair rainbow) { + if (rainbow.first == null || rainbow.second == null) { + return null; + } + if (rainbow.second instanceof PsiLocalVariable || rainbow.second instanceof PsiParameter) { + String name = ((PsiVariable)rainbow.second).getName(); + if (name != null) { + return getInfo(context, rainbow.first, name, rainbow.second instanceof PsiLocalVariable + ? JavaHighlightingColors.LOCAL_VARIABLE_ATTRIBUTES + : JavaHighlightingColors.PARAMETER_ATTRIBUTES); + } + } + return null; + } + + @Override + @NotNull + public HighlightVisitor clone() { + return new JavaRainbowVisitor(); + } +} + diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightRainbowHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightRainbowHighlightingTest.java new file mode 100644 index 0000000000000..a36934abd9abd --- /dev/null +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightRainbowHighlightingTest.java @@ -0,0 +1,84 @@ +/* + * Copyright 2000-2016 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.daemon; + +import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase; +import org.jetbrains.annotations.NotNull; + +public class LightRainbowHighlightingTest extends LightCodeInsightFixtureTestCase { + + public void testRainbowOff() throws Exception { + checkRainbow( + "class TestClass {\n" + + " private static int field = 1;\n" + + " public static void main(String[] args) {\n" + + " ++field;\n" + + " String local1 = null;\n" + + " System.out.println(field + local1 + args[0]);\n" + + " }\n" + + "}", false, false); + } + + public void testRainbowSameColorsForSameIds() throws Exception { + checkRainbow( + "class TestClass {\n" + + " public static void main(String[] args) {\n" + + " String local1 = null;\n" + + " System.out.println(local1\n" + + " + args[0]);\n" + + " }\n" + + "}", true, true); + } + + public void testRainbowHighlightingIds() throws Exception { + // check no coloring for [this] and etc. + checkRainbow( + "class TestClass {\n" + + " private static int SFIELD = 1;\n" + + " private static int myField = 1;\n" + + " public void f(int param1,\n" + + " int param2,\n" + + " int param3) {\n" + + " SFIELD = param1 + param2 + param3 + myField;\n" + + " param1 = this.hashCode() + this.myField;\n" + + " }\n" + + "}", true, false); + } + + public void fixme_testRainbowParamsInJavadocHaveTheSameColorsAsInCode() throws Exception { + checkRainbow( + "class TestClass {\n" + + " /**\n" + + " * \n" + + " * @param param1\n" + + " * @param param2\n" + + " * @param param3\n" + + " */\n" + + " public void f(int param1,\n" + + " int param2,\n" + + " int param3) {\n" + + " }\n" + + "}", true, true); + } + + + void checkRainbow(@NotNull String code, boolean isRainbowOn, boolean withColor) throws Exception { + myFixture.testRainbow( + "rainbow.java", + code, + isRainbowOn, withColor); + } +} diff --git a/platform/analysis-impl/src/com/intellij/codeHighlighting/RainbowHighlighter.java b/platform/analysis-impl/src/com/intellij/codeHighlighting/RainbowHighlighter.java index ce8d1b288a18a..55cad7fdf1b3f 100644 --- a/platform/analysis-impl/src/com/intellij/codeHighlighting/RainbowHighlighter.java +++ b/platform/analysis-impl/src/com/intellij/codeHighlighting/RainbowHighlighter.java @@ -18,65 +18,90 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.HighlightInfoType; import com.intellij.lang.annotation.HighlightSeverity; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.colors.EditorColorsManager; import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.editor.colors.TextAttributesScheme; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.util.registry.Registry; -import com.intellij.openapi.util.text.StringHash; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.ui.ColorUtil; +import com.intellij.ui.JBColor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; +import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class RainbowHighlighter { + private final static String UNIT_TEST_COLORS = "#000001,#000002,#000003,#000004"; // Do not modify! + private final static int COLOR_COUNT = 16; + @NotNull private final TextAttributesScheme myColorsScheme; + @NotNull private final List myRainbowColors; public RainbowHighlighter(@Nullable TextAttributesScheme colorsScheme) { myColorsScheme = colorsScheme != null ? colorsScheme : EditorColorsManager.getInstance().getGlobalScheme(); + myRainbowColors = generateColorSequence(myColorsScheme); } - public static final HighlightInfoType RAINBOW_ELEMENT = new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, DefaultLanguageHighlighterColors.CONSTANT); + public static final HighlightInfoType RAINBOW_ELEMENT = + new HighlightInfoType.HighlightInfoTypeImpl(HighlightSeverity.INFORMATION, DefaultLanguageHighlighterColors.CONSTANT); public static boolean isRainbowEnabled() { return Registry.is("editor.rainbow.identifiers", false); } @NotNull - public TextAttributes getAttributes(@NotNull String name, @NotNull TextAttributes origin) { - final Color fg = calculateForeground(name); - return TextAttributes.fromFlyweight(origin.getFlyweight().withForeground(fg)); + public Color calculateForeground(int colorIndex) { + return myRainbowColors.get(Math.abs(colorIndex) % myRainbowColors.size()); } - @NotNull - protected Color calculateForeground(@NotNull String name) { - int hash = StringHash.murmur(name, 0); - final List registryColors = StringUtil.split(Registry.get("rainbow.highlighter.colors").asString(), ","); + public int getColorsCount() { + return myRainbowColors.size(); + } + + private static List generateColorSequence(@NotNull TextAttributesScheme colorsScheme) { + String colorDump = ApplicationManager.getApplication().isUnitTestMode() + ? UNIT_TEST_COLORS + : Registry.get("rainbow.highlighter.colors").asString(); + + final List registryColors = StringUtil.split(colorDump, ","); if (!registryColors.isEmpty()) { - final List colors = registryColors.stream().map((s -> ColorUtil.fromHex(s.trim()))).collect(Collectors.toList()); - if (!colors.isEmpty()) { - return colors.get(Math.abs(hash) % colors.size()); - } + return registryColors.stream().map((s -> ColorUtil.fromHex(s.trim()))).collect(Collectors.toList()); } - final float colors = 36.0f; - final float v = Math.round(Math.abs(colors * hash) / Integer.MAX_VALUE) / colors; - return Color.getHSBColor(v, 0.7f, .3f); + List colors = new ArrayList(COLOR_COUNT); + TextAttributes attributes = colorsScheme.getAttributes(DefaultLanguageHighlighterColors.CONSTANT); + Color foregroundColor = attributes != null ? attributes.getForegroundColor() : JBColor.gray; + float[] floats = Color.RGBtoHSB(foregroundColor.getRed(), foregroundColor.getGreen(), foregroundColor.getBlue(), null); + for (int i = 0; i < COLOR_COUNT; ++i) { + float factor = ((float)i) / COLOR_COUNT; + Color color = Color.getHSBColor(factor, .7f, floats[2] * 1.3f); + //noinspection UseJBColor + colors.add(new Color(color.getRed()/2, color.getGreen(), color.getBlue())); // to highlight errors we reduce Red color + } + return colors; } - public HighlightInfo getInfo(@Nullable String nameKey, @Nullable PsiElement id, @Nullable TextAttributesKey colorKey) { - if (id == null || nameKey == null || StringUtil.isEmpty(nameKey)) return null; - if (colorKey == null) colorKey = DefaultLanguageHighlighterColors.LOCAL_VARIABLE; - final TextAttributes attributes = getAttributes(nameKey, myColorsScheme.getAttributes(colorKey)); + public HighlightInfo getInfo(int colorIndex, @Nullable PsiElement id, @Nullable TextAttributesKey colorKey) { + if (id == null) { + return null; + } + if (colorKey == null) { + colorKey = DefaultLanguageHighlighterColors.LOCAL_VARIABLE; + } return HighlightInfo .newHighlightInfo(RAINBOW_ELEMENT) - .textAttributes(attributes) + .textAttributes(TextAttributes + .fromFlyweight(myColorsScheme + .getAttributes(colorKey) + .getFlyweight() + .withForeground(calculateForeground(colorIndex)))) .range(id) .create(); } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/RainbowVisitor.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/RainbowVisitor.java index 7f9849cb8b54b..52e6096c76670 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/RainbowVisitor.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/RainbowVisitor.java @@ -19,14 +19,25 @@ import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.daemon.impl.HighlightVisitor; import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder; +import com.intellij.openapi.editor.colors.TextAttributesKey; import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.util.NotNullLazyKey; +import com.intellij.openapi.util.text.StringHash; +import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.HashMap; +import java.util.Map; public abstract class RainbowVisitor implements HighlightVisitor { private HighlightInfoHolder myHolder; private RainbowHighlighter myRainbowHighlighter; + protected static final NotNullLazyKey, PsiElement> USED_COLORS = + NotNullLazyKey.create("USED_COLORS", psiElement -> new HashMap()); + @NotNull @Override public abstract HighlightVisitor clone(); @@ -70,4 +81,35 @@ public static boolean existsPassSuitableForFile(@NotNull PsiFile file) { } return false; } + + protected HighlightInfo getInfo(@NotNull PsiElement context, + @NotNull PsiElement rainbowElement, + @NotNull String id, + @Nullable TextAttributesKey colorKey) { + HashMap id2index = USED_COLORS.getValue(context); + Integer colorIndex = id2index.get(id); + if (colorIndex == null) { + colorIndex = Math.abs(StringHash.murmur(id, 0x55AA)); + + Map index2usage = new HashMap(); + id2index.values().forEach(i -> { + Integer useCount = index2usage.get(i); + index2usage.put(i, useCount == null ? 1 : ++useCount); + }); + + int colorsCount = getHighlighter().getColorsCount(); + out: + for (int cutoff = 0; ; ++cutoff) { + for (int i = 0; i < colorsCount; ++i) { + colorIndex %= colorsCount; + Integer useCount = index2usage.get(colorIndex % colorsCount); + if (useCount == null) useCount = 0; + if (useCount == cutoff) break out; + ++colorIndex; + } + } + id2index.put(id, colorIndex); + } + return getHighlighter().getInfo(colorIndex, rainbowElement, colorKey); + } } diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java index d7d0c2df34bd5..e8c8343bdd53e 100644 --- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java +++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java @@ -16,10 +16,8 @@ package com.intellij.codeInsight.daemon.impl; -import com.intellij.codeHighlighting.RainbowHighlighter; import com.intellij.codeInsight.daemon.GutterMark; import com.intellij.codeInsight.daemon.HighlightDisplayKey; -import com.intellij.codeInsight.daemon.RainbowVisitor; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.intention.IntentionManager; import com.intellij.codeInspection.*; @@ -31,7 +29,6 @@ import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.annotation.ProblemGroup; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.openapi.editor.DefaultLanguageHighlighterColors; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.HighlighterColors; import com.intellij.openapi.editor.RangeMarker; @@ -49,7 +46,6 @@ import com.intellij.util.containers.ContainerUtil; import com.intellij.xml.util.XmlStringUtil; import org.intellij.lang.annotations.MagicConstant; -import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -180,26 +176,7 @@ public TextAttributes getTextAttributes(@Nullable final PsiElement element, @Nul return colorsScheme.getAttributes(forcedTextAttributesKey); } - TextAttributes attributes = getAttributesByType(element, type, colorsScheme); - if (element != null && - RainbowHighlighter.isRainbowEnabled() && - isLikeVariable(type.getAttributesKey())) { - PsiFile containingFile = element.getContainingFile(); - if (!RainbowVisitor.existsPassSuitableForFile(containingFile)) { - CharSequence text = containingFile.getViewProvider().getContents().subSequence(startOffset, endOffset); - attributes = new RainbowHighlighter(colorsScheme).getAttributes(text.toString(), attributes); - } - } - return attributes; - } - - @Contract("null -> false") - private static boolean isLikeVariable(TextAttributesKey key) { - if (key == null) return false; - TextAttributesKey fallbackAttributeKey = key.getFallbackAttributeKey(); - if (fallbackAttributeKey == null) return false; - if (fallbackAttributeKey == DefaultLanguageHighlighterColors.LOCAL_VARIABLE || fallbackAttributeKey == DefaultLanguageHighlighterColors.PARAMETER) return true; - return isLikeVariable(fallbackAttributeKey); + return getAttributesByType(element, type, colorsScheme); } public static TextAttributes getAttributesByType(@Nullable final PsiElement element, diff --git a/resources/src/META-INF/IdeaPlugin.xml b/resources/src/META-INF/IdeaPlugin.xml index 02c0b3840c5ce..b84caae7c5ed1 100644 --- a/resources/src/META-INF/IdeaPlugin.xml +++ b/resources/src/META-INF/IdeaPlugin.xml @@ -1583,6 +1583,7 @@ + From b4924c4325945d0c1df714bc2c316d1cde79657e Mon Sep 17 00:00:00 2001 From: "Egor.Ushakov" Date: Wed, 20 Jul 2016 19:03:30 +0300 Subject: [PATCH 47/67] cache source positions to speedup frame loading when stepping --- .../engine/CompoundPositionManager.java | 25 +++---------------- 1 file changed, 3 insertions(+), 22 deletions(-) diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java index c53f80661f0f9..67f1e7b73cfd5 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java @@ -36,10 +36,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; +import java.util.*; public class CompoundPositionManager extends PositionManagerEx implements MultiRequestPositionManager{ private static final Logger LOG = Logger.getInstance(CompoundPositionManager.class); @@ -57,9 +54,10 @@ public CompoundPositionManager(PositionManager manager) { public void appendPositionManager(PositionManager manager) { myPositionManagers.remove(manager); myPositionManagers.add(0, manager); + mySourcePositionCache.clear(); } - private final Cache mySourcePositionCache = new Cache<>(); + private final Map mySourcePositionCache = new WeakHashMap<>(); private interface Processor { T process(PositionManager positionManager) throws NoDataException; @@ -196,21 +194,4 @@ public ThreeState evaluateCondition(@NotNull EvaluationContext context, } return ThreeState.UNSURE; } - - private static class Cache { - private K myKey; - private V myValue; - - public V get(@NotNull K key) { - if (key.equals(myKey)) { - return myValue; - } - return null; - } - - public void put(@NotNull K key, V value) { - myKey = key; - myValue = value; - } - } } From 0ea1f3f32f5fa60127780b0bfa18a5f9944fa341 Mon Sep 17 00:00:00 2001 From: Valentin Fondaratov Date: Wed, 20 Jul 2016 18:24:35 +0300 Subject: [PATCH 48/67] Fix YAML parser to include into block scalars only their real content --- .../org/jetbrains/yaml/parser/YAMLParser.java | 26 ++++++++++++-- .../yaml/psi/impl/YAMLBlockScalarImpl.java | 3 ++ .../jetbrains/yaml/parser/YAMLParserTest.java | 4 +++ .../yaml/parser/data/ScalarsWithNewlines.txt | 35 +++++++++++++++++++ .../yaml/parser/data/ScalarsWithNewlines.yml | 17 +++++++++ 5 files changed, 83 insertions(+), 2 deletions(-) create mode 100644 plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.txt create mode 100644 plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.yml diff --git a/plugins/yaml/src/org/jetbrains/yaml/parser/YAMLParser.java b/plugins/yaml/src/org/jetbrains/yaml/parser/YAMLParser.java index 9138502fb4909..719b1ebcd26be 100644 --- a/plugins/yaml/src/org/jetbrains/yaml/parser/YAMLParser.java +++ b/plugins/yaml/src/org/jetbrains/yaml/parser/YAMLParser.java @@ -214,12 +214,34 @@ private IElementType parseQuotedString() { @NotNull private IElementType parseMultiLineScalar(final IElementType tokenType) { + int indent = -1; IElementType type = getTokenType(); + PsiBuilder.Marker endOfValue = null; while (type == tokenType || type == INDENT || type == EOL) { - advanceLexer(); + if (indent == -1 && type == INDENT) { + indent = getCurrentTokenLength(); + } + + if (type == tokenType || type == INDENT && getCurrentTokenLength() > indent) { + advanceLexer(); + if (endOfValue != null) { + endOfValue.drop(); + } + endOfValue = myBuilder.mark(); + } + else { + advanceLexer(); + } + type = getTokenType(); } - rollBackToEol(); + if (endOfValue == null) { + rollBackToEol(); + } + else { + dropEolMarker(); + endOfValue.rollbackTo(); + } return tokenType == SCALAR_LIST ? YAMLElementTypes.SCALAR_LIST_VALUE : YAMLElementTypes.SCALAR_TEXT_VALUE; } diff --git a/plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLBlockScalarImpl.java b/plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLBlockScalarImpl.java index f550c10ea3783..4ef76e6a755fd 100644 --- a/plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLBlockScalarImpl.java +++ b/plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLBlockScalarImpl.java @@ -58,6 +58,9 @@ else if (child.getElementType() == YAMLTokenTypes.INDENT) { thisLineStart = child.getStartOffset() + 1; } } + if (thisLineStart != -1 && thisLineStart != getTextRange().getEndOffset()) { + result.add(TextRange.create(thisLineStart, getTextRange().getEndOffset()).shiftRight(-myStart)); + } final int lastNonEmpty = ContainerUtil.lastIndexOf(result, range -> range.getLength() != 0); diff --git a/plugins/yaml/testSrc/org/jetbrains/yaml/parser/YAMLParserTest.java b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/YAMLParserTest.java index f38de53a2d6fe..eb06d53dcedb8 100644 --- a/plugins/yaml/testSrc/org/jetbrains/yaml/parser/YAMLParserTest.java +++ b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/YAMLParserTest.java @@ -217,4 +217,8 @@ public void testKeyValueWithEmptyLineAhead() { public void testMultipleDocsWithMappings() { doTest(true); } + + public void testScalarsWithNewlines() { + doTest(true); + } } diff --git a/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.txt b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.txt new file mode 100644 index 0000000000000..3836ada5de2a7 --- /dev/null +++ b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.txt @@ -0,0 +1,35 @@ +YAML file + YAML document + PsiElement(---)('---') + PsiWhiteSpace(' ') + YAML compound value + YAML scalar text + PsiElement(scalar text)('>') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(scalar text)('foo') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(scalar text)('bar') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(indent)(' ') + PsiElement(Eol)('\n') + PsiElement(...)('...') \ No newline at end of file diff --git a/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.yml b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.yml new file mode 100644 index 0000000000000..78402924e54e7 --- /dev/null +++ b/plugins/yaml/testSrc/org/jetbrains/yaml/parser/data/ScalarsWithNewlines.yml @@ -0,0 +1,17 @@ +--- > + foo + bar + + + + + + + + + + + + + +... \ No newline at end of file From 676dfd784df2b4715844f886a80cdf93139b26cc Mon Sep 17 00:00:00 2001 From: Andrey Vokin Date: Wed, 20 Jul 2016 19:24:26 +0200 Subject: [PATCH 49/67] RUBY-18217 Show only Ruby 2.2+ for Rails API applications in Ruby Plugin. After review changes --- .../ide/util/projectWizard/SdkSettingsStep.java | 2 +- .../roots/ui/configuration/JdkComboBox.java | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/java/idea-ui/src/com/intellij/ide/util/projectWizard/SdkSettingsStep.java b/java/idea-ui/src/com/intellij/ide/util/projectWizard/SdkSettingsStep.java index e673f7c29cc61..954dd10592bbf 100644 --- a/java/idea-ui/src/com/intellij/ide/util/projectWizard/SdkSettingsStep.java +++ b/java/idea-ui/src/com/intellij/ide/util/projectWizard/SdkSettingsStep.java @@ -85,7 +85,7 @@ public SdkSettingsStep(WizardContext context, sdkFilter = JdkComboBox.getSdkFilter(sdkTypeIdFilter); } - myJdkComboBox = new JdkComboBox(myModel, sdkFilter, sdkTypeIdFilter, true); + myJdkComboBox = new JdkComboBox(myModel, sdkTypeIdFilter, sdkFilter, sdkTypeIdFilter, true); myJdkPanel = new JPanel(new GridBagLayout()); final PropertiesComponent component = project == null ? PropertiesComponent.getInstance() : PropertiesComponent.getInstance(project); diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java index f43b142cb80d2..6ef56538841b5 100644 --- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java +++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/JdkComboBox.java @@ -66,14 +66,15 @@ public JdkComboBox(@NotNull final ProjectSdksModel jdkModel) { public JdkComboBox(@NotNull final ProjectSdksModel jdkModel, @Nullable Condition filter) { - this(jdkModel, getSdkFilter(filter), filter, false); + this(jdkModel, filter, getSdkFilter(filter), filter, false); } public JdkComboBox(@NotNull final ProjectSdksModel jdkModel, + @Nullable Condition sdkTypeFilter, @Nullable Condition filter, @Nullable Condition creationFilter, boolean addSuggestedItems) { - super(new JdkComboBoxModel(jdkModel, filter, addSuggestedItems)); + super(new JdkComboBoxModel(jdkModel, sdkTypeFilter, filter, addSuggestedItems)); myFilter = filter; myCreationFilter = creationFilter; setRenderer(new ProjectJdkListRenderer() { @@ -289,7 +290,8 @@ public void reloadModel(JdkComboBoxItem firstItem, @Nullable Project project) { } private static class JdkComboBoxModel extends DefaultComboBoxModel { - public JdkComboBoxModel(final ProjectSdksModel jdksModel, @Nullable Condition sdkFilter, boolean addSuggested) { + public JdkComboBoxModel(final ProjectSdksModel jdksModel, @Nullable Condition sdkTypeFilter, + @Nullable Condition sdkFilter, boolean addSuggested) { Sdk[] jdks = jdksModel.getSdks(); Arrays.sort(jdks, (s1, s2) -> s1.getName().compareToIgnoreCase(s2.getName())); for (Sdk jdk : jdks) { @@ -298,14 +300,14 @@ public JdkComboBoxModel(final ProjectSdksModel jdksModel, @Nullable Condition sdkFilter, Sdk[] jdks) { + protected void addSuggestedItems(@Nullable Condition sdkTypeFilter, Sdk[] jdks) { SdkType[] types = SdkType.getAllTypes(); for (SdkType type : types) { - if (sdkFilter == null || ContainerUtil.find(jdks, sdkFilter) == null) { + if (sdkTypeFilter == null || sdkTypeFilter.value(type) && ContainerUtil.find(jdks, sdk -> sdk.getSdkType() == type) == null) { String homePath = type.suggestHomePath(); if (homePath != null && type.isValidSdkHome(homePath)) { addElement(new SuggestedJdkItem(type, homePath)); From c525a5fa9588966b6b0507aa7f47042c8096af12 Mon Sep 17 00:00:00 2001 From: Pavel Dolgov Date: Wed, 20 Jul 2016 20:57:15 +0300 Subject: [PATCH 50/67] Java inspection: Converted the intention "Add Array Creation Expression" into an INFORMATION-level inspection (IDEA-157727) --- .../src/META-INF/InspectionGadgets.xml | 4 + .../siyeh/InspectionGadgetsBundle.properties | 4 +- .../AddArrayCreationExpressionInspection.java | 110 ++++++++++++++++++ .../AddArrayCreationExpression.html | 6 + .../Generic.after.java} | 0 .../array_creation_expression}/Generic.java | 0 .../NotAnArray.java | 0 .../Primitive.after.java | 3 + .../array_creation_expression/Primitive.java | 3 + .../AddArrayCreationExpressionFixTest.java | 45 +++++++ .../src/META-INF/IntentionPowerPack.xml | 6 - .../siyeh/IntentionPowerPackBundle.properties | 2 - .../AddArrayCreationExpressionIntention.java | 54 --------- .../ArrayCreationExpressionPredicate.java | 36 ------ .../after.java.template | 3 - .../before.java.template | 3 - .../description.html | 7 -- ...dArrayCreationExpressionIntentionTest.java | 37 ------ 18 files changed, 174 insertions(+), 149 deletions(-) create mode 100644 plugins/InspectionGadgets/src/com/siyeh/ig/style/AddArrayCreationExpressionInspection.java create mode 100644 plugins/InspectionGadgets/src/inspectionDescriptions/AddArrayCreationExpression.html rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/Generic_after.java => InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Generic.after.java} (100%) rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation => InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression}/Generic.java (100%) rename plugins/{IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation => InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression}/NotAnArray.java (100%) create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.after.java create mode 100644 plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.java create mode 100644 plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/AddArrayCreationExpressionFixTest.java delete mode 100644 plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/AddArrayCreationExpressionIntention.java delete mode 100644 plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/ArrayCreationExpressionPredicate.java delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/after.java.template delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/before.java.template delete mode 100644 plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/description.html delete mode 100644 plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/braces/AddArrayCreationExpressionIntentionTest.java diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml index 3c969aec81530..9e77481eb5c40 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml @@ -2568,6 +2568,10 @@ key="expand.to.normal.annotation.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.code.style.issues" enabledByDefault="true" level="INFORMATION" implementationClass="com.siyeh.ig.annotation.ExpandToNormalAnnotationInspection"/> + + +This inspection reports array initializer without new array expression. +

The quick fix for this inspection adds a new array expression to the initializer. + + diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/Generic_after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Generic.after.java similarity index 100% rename from plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/Generic_after.java rename to plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Generic.after.java diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/Generic.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Generic.java similarity index 100% rename from plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/Generic.java rename to plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Generic.java diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/NotAnArray.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/NotAnArray.java similarity index 100% rename from plugins/IntentionPowerPak/test/com/siyeh/ipp/braces/array_creation/NotAnArray.java rename to plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/NotAnArray.java diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.after.java new file mode 100644 index 0000000000000..b34626c1224f9 --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.after.java @@ -0,0 +1,3 @@ +class Primitive { + int[] a = new int[]{42}; +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.java new file mode 100644 index 0000000000000..a68d299ce0f6d --- /dev/null +++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/style/array_creation_expression/Primitive.java @@ -0,0 +1,3 @@ +class Primitive { + int[] a = {42}; +} \ No newline at end of file diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/AddArrayCreationExpressionFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/AddArrayCreationExpressionFixTest.java new file mode 100644 index 0000000000000..dff4020198dcb --- /dev/null +++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/style/AddArrayCreationExpressionFixTest.java @@ -0,0 +1,45 @@ +/* + * Copyright 2000-2016 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.siyeh.ig.fixes.style; + +import com.siyeh.InspectionGadgetsBundle; +import com.siyeh.ig.IGQuickFixesTestCase; +import com.siyeh.ig.style.AddArrayCreationExpressionInspection; + +public class AddArrayCreationExpressionFixTest extends IGQuickFixesTestCase { + + public void testPrimitive() { doTest("int[]"); } + public void testGeneric() { doTest("java.util.Map[][]"); } + public void testNotAnArray() { assertQuickfixNotAvailable(); } + + @Override + protected void doTest(String hint) { + super.doTest(InspectionGadgetsBundle.message("add.array.creation.expression.descriptor", hint)); + } + + @Override + protected void assertQuickfixNotAvailable() { + String message = InspectionGadgetsBundle.message("add.array.creation.expression.descriptor", "@"); + super.assertQuickfixNotAvailable(message.substring(0, message.indexOf('@'))); + } + + @Override + public void setUp() throws Exception { + super.setUp(); + myFixture.enableInspections(new AddArrayCreationExpressionInspection()); + myRelativePath = "style/array_creation_expression"; + } +} diff --git a/plugins/IntentionPowerPak/src/META-INF/IntentionPowerPack.xml b/plugins/IntentionPowerPak/src/META-INF/IntentionPowerPack.xml index 0b8cdc1089d54..0e7d73362ffde 100644 --- a/plugins/IntentionPowerPak/src/META-INF/IntentionPowerPack.xml +++ b/plugins/IntentionPowerPak/src/META-INF/IntentionPowerPack.xml @@ -181,12 +181,6 @@ --> - - com.siyeh.ipp.braces.AddArrayCreationExpressionIntention - com.siyeh.IntentionPowerPackBundle - intention.category.declaration - - com.siyeh.ipp.initialization.SplitDeclarationAndInitializationIntention com.siyeh.IntentionPowerPackBundle diff --git a/plugins/IntentionPowerPak/src/com/siyeh/IntentionPowerPackBundle.properties b/plugins/IntentionPowerPak/src/com/siyeh/IntentionPowerPackBundle.properties index efcc5244f3d67..fdbbc70eaad6a 100644 --- a/plugins/IntentionPowerPak/src/com/siyeh/IntentionPowerPackBundle.properties +++ b/plugins/IntentionPowerPak/src/com/siyeh/IntentionPowerPackBundle.properties @@ -140,7 +140,6 @@ replace.arm.with.try.finally.intention.family.name=Replace Try-With-Resources wi merge.nested.try.statements.intention.name=Merge nested 'try' statements merge.nested.try.statements.intention.family.name=Merge Nested Try Statements obscure.thrown.exceptions.intention.family.name=Replace Exceptions in Throws Clause with Single More General Exception -add.array.creation.expression.intention.family.name=Add Array Creation Expression make.public.intention.name=Make 'public' make.public.intention.family.name=Make Public make.package.private.intention.name=Make package-private @@ -190,7 +189,6 @@ swap.method.call.arguments.intention.name=Swap ''{0}'' and ''{1}'' flip.setter.call.intention.name=Flip Setter Call adapter.to.listener.intention.name=Replace extension of ''{0}'' with ''Listener'' implementation obscure.thrown.exceptions.intention.name=Replace with ''throws {0}'' -add.array.creation.expression.intention.name=Add ''new {0}'' change.variable.type.to.rhs.type.intention.name=Declare ''{0}'' with type ''{1}'' postfix.prefix.intention.name=Replace with ''{0}'' diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/AddArrayCreationExpressionIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/AddArrayCreationExpressionIntention.java deleted file mode 100644 index 8a08420de479f..0000000000000 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/AddArrayCreationExpressionIntention.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2011-2013 Bas Leijdekkers - * - * 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.siyeh.ipp.braces; - -import com.intellij.psi.*; -import com.intellij.psi.util.TypeConversionUtil; -import com.intellij.util.IncorrectOperationException; -import com.siyeh.IntentionPowerPackBundle; -import com.siyeh.ig.PsiReplacementUtil; -import com.siyeh.ipp.base.MutablyNamedIntention; -import com.siyeh.ipp.base.PsiElementPredicate; -import org.jetbrains.annotations.NotNull; - -public class AddArrayCreationExpressionIntention extends MutablyNamedIntention { - - @Override - @NotNull - protected PsiElementPredicate getElementPredicate() { - return new ArrayCreationExpressionPredicate(); - } - - @Override - protected String getTextForElement(PsiElement element) { - final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)element; - final PsiType type = arrayInitializerExpression.getType(); - return IntentionPowerPackBundle.message("add.array.creation.expression.intention.name", - TypeConversionUtil.erasure(type).getCanonicalText()); - } - - @Override - protected void processIntention(@NotNull PsiElement element) throws IncorrectOperationException { - final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)element; - final PsiType type = arrayInitializerExpression.getType(); - if (type == null) { - return; - } - PsiReplacementUtil.replaceExpression(arrayInitializerExpression, "new " + - TypeConversionUtil.erasure(type).getCanonicalText() + - arrayInitializerExpression.getText()); - } -} diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/ArrayCreationExpressionPredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/ArrayCreationExpressionPredicate.java deleted file mode 100644 index f3bc646c25a54..0000000000000 --- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/ArrayCreationExpressionPredicate.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2011-2013 Bas Leijdekkers - * - * 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.siyeh.ipp.braces; - -import com.intellij.psi.*; -import com.siyeh.ipp.base.PsiElementPredicate; -import org.jetbrains.annotations.NotNull; - -class ArrayCreationExpressionPredicate implements PsiElementPredicate { - - public boolean satisfiedBy(@NotNull PsiElement element) { - if (!(element instanceof PsiArrayInitializerExpression)) { - return false; - } - final PsiArrayInitializerExpression arrayInitializerExpression = (PsiArrayInitializerExpression)element; - final PsiType type = arrayInitializerExpression.getType(); - if (type == null || !(type instanceof PsiArrayType)) { - return false; - } - final PsiElement parent = element.getParent(); - return !(parent instanceof PsiNewExpression); - } -} diff --git a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/after.java.template b/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/after.java.template deleted file mode 100644 index feec2a48e6503..0000000000000 --- a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/after.java.template +++ /dev/null @@ -1,3 +0,0 @@ -public class X { - private final String[] ss = new String[]{}; -} diff --git a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/before.java.template b/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/before.java.template deleted file mode 100644 index a95d1e983b2e0..0000000000000 --- a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/before.java.template +++ /dev/null @@ -1,3 +0,0 @@ -public class X { - private final String[] ss = {}; -} diff --git a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/description.html b/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/description.html deleted file mode 100644 index 5072b9cd04647..0000000000000 --- a/plugins/IntentionPowerPak/src/intentionDescriptions/AddArrayCreationExpressionIntention/description.html +++ /dev/null @@ -1,7 +0,0 @@ - - -This intention adds an array creation expression to an -array initializer expression without one. -

- - diff --git a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/braces/AddArrayCreationExpressionIntentionTest.java b/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/braces/AddArrayCreationExpressionIntentionTest.java deleted file mode 100644 index bb45de803082a..0000000000000 --- a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/braces/AddArrayCreationExpressionIntentionTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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.siyeh.ipp.braces; - -import com.siyeh.IntentionPowerPackBundle; -import com.siyeh.ipp.IPPTestCase; - -/** - * @see AddArrayCreationExpressionIntention - */ -public class AddArrayCreationExpressionIntentionTest extends IPPTestCase { - public void testGeneric() { doTest(); } - public void testNotAnArray() { assertIntentionNotAvailable(AddArrayCreationExpressionIntention.class); } - - @Override - protected String getIntentionName() { - return IntentionPowerPackBundle.message("add.array.creation.expression.intention.name", "java.util.Map[][]"); - } - - @Override - protected String getRelativePath() { - return "braces/array_creation"; - } -} From 3f37223565af0211112b1b48b6d5cb44296a176f Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 20 Jul 2016 21:07:18 +0300 Subject: [PATCH 51/67] IDEA-97406 cached images refactoring --- .../com/intellij/ui/paint/EffectPainter.java | 148 +++++++++--------- 1 file changed, 75 insertions(+), 73 deletions(-) diff --git a/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java b/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java index 008dcdb4db3ff..fa5263309fc11 100644 --- a/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java +++ b/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java @@ -131,7 +131,7 @@ public void paint(Graphics2D g, int x, int y, int width, int height, Paint paint WavePainter.forColor(g.getColor()).paint(g, x, x + width, y + height); } else if (width > 0 && height > 0) { - WAVE_FACTORY.paint(g, x, y, width, height, paint); + Cached.WAVE_UNDERSCORE.paint(g, x, y, width, height, paint); } } }, @@ -181,112 +181,114 @@ private static void drawLineCentered(Graphics2D g, int x, int y, int width, int height = thickness; } if (painter == BOLD_DOTTED_UNDERSCORE) { - BOLD_DOTTED_FACTORY.paint(g, x, y, width, height, null); + Cached.BOLD_DOTTED_UNDERSCORE.paint(g, x, y, width, height, null); } else { g.fillRect(x, y, width, height); } } - private static abstract class Factory implements RegionPainter { - private final ConcurrentHashMap myCache = new ConcurrentHashMap<>(); - - abstract BufferedImage create(Graphics2D g, Paint paint, int height); - - @Override - public void paint(Graphics2D g, int x, int y, int width, int height, Paint paint) { - if (paint == null) paint = g.getPaint(); - g = (Graphics2D)g.create(x, y, width, height); - g.setComposite(AlphaComposite.SrcOver); - BufferedImage image; - if (paint instanceof Color) { - Color color = (Color)paint; - Long key = color.getRGB() ^ ((long)height << 32); - image = myCache.get(key); - boolean exists = image != null; - if (!exists || UIUtil.isRetina(g) != (image instanceof JBHiDPIScaledImage)) { - image = create(g, paint, height); - myCache.put(key, image); - } - } - else { - image = create(g, paint, height); + private enum Cached implements RegionPainter { + BOLD_DOTTED_UNDERSCORE { + @Override + int getPeriod(int height) { + return height; } - int length = image.getWidth(); - int dx = -((x % length + length) % length); // normalize - for (; dx < width; dx += length) { - UIUtil.drawImage(g, image, dx, 0, null); - } - g.dispose(); - } - } - private static final Factory BOLD_DOTTED_FACTORY = new Factory() { - @Override - BufferedImage create(Graphics2D graphics, Paint paint, int height) { - Integer round = height <= 2 && !UIUtil.isRetina(graphics) ? null : height; - //noinspection SuspiciousNameCombination - int width = height << 8; - BufferedImage image = UIUtil.createImageForGraphics(graphics, width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = image.createGraphics(); - g.setPaint(paint); - try { - int dx = 0; - while (dx < width) { - //noinspection SuspiciousNameCombination - RectanglePainter.FILL.paint(g, dx, 0, height, height, round); - dx += height + height; + @Override + void paintImage(Graphics2D g, int width, int height, int period) { + Integer round = period <= 2 && !UIUtil.isRetina(g) ? null : period; + for (int dx = 0; dx < width; dx += period + period) { + RectanglePainter.FILL.paint(g, dx, 0, period, period, round); } } - finally { - g.dispose(); + }, + WAVE_UNDERSCORE { + private final BasicStroke THIN_STROKE = new BasicStroke(.7f); + + @Override + int getPeriod(int height) { + return getMaxHeight(height) - 1; } - return image; - } - }; - private static final BasicStroke WAVE_THIN_STROKE = new BasicStroke(.7f); - private static final Factory WAVE_FACTORY = new Factory() { - @Override - BufferedImage create(Graphics2D graphics, Paint paint, int height) { - int h = getMaxHeight(height); - int width = 2 * h - 2; // the spatial period of the wave - BufferedImage image = UIUtil.createImageForGraphics(graphics, width << 8, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = image.createGraphics(); - try { + @Override + void paintImage(Graphics2D g, int width, int height, int period) { double dx = 0; - double upper = height - h; double lower = height - 1; + double upper = lower - period; Path2D path = new Path2D.Double(); path.moveTo(dx, lower); if (height < 6) { - g.setStroke(WAVE_THIN_STROKE); - double size = (double)width / 2; - while (dx < image.getWidth()) { - path.lineTo(dx += size, upper); - path.lineTo(dx += size, lower); + g.setStroke(THIN_STROKE); + while (dx < width) { + path.lineTo(dx += period, upper); + path.lineTo(dx += period, lower); } } else { - double size = (double)width / 4; + double size = (double)period / 2; double prev = dx - size / 2; double center = (upper + lower) / 2; - while (dx < image.getWidth()) { + while (dx < width) { path.quadTo(prev += size, lower, dx += size, center); path.quadTo(prev += size, upper, dx += size, upper); path.quadTo(prev += size, upper, dx += size, center); path.quadTo(prev += size, lower, dx += size, lower); } } - path.lineTo((double)image.getWidth(), lower); + path.lineTo((double)width, lower); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g.setPaint(paint); g.draw(path); } + }; + + private final ConcurrentHashMap myCache = new ConcurrentHashMap<>(); + + abstract int getPeriod(int height); + + abstract void paintImage(Graphics2D g, int width, int height, int period); + + void paintImage(Graphics2D g, Paint paint, int width, int height, int period) { + try { + g.setPaint(paint); + paintImage(g, width, height, period); + } finally { g.dispose(); } + } + + BufferedImage getImage(Graphics2D g, Color color, int height) { + Long key = color.getRGB() ^ ((long)height << 32); + BufferedImage image = myCache.get(key); + if (image == null || UIUtil.isRetina(g) != (image instanceof JBHiDPIScaledImage)) { + int period = getPeriod(height); + image = UIUtil.createImageForGraphics(g, period << 8, height, BufferedImage.TYPE_INT_ARGB); + paintImage(image.createGraphics(), color, image.getWidth(), image.getHeight(), period); + myCache.put(key, image); + } return image; } - }; + + BufferedImage createImage(Graphics2D g, Paint paint, int height) { + int period = getPeriod(height); + BufferedImage image = UIUtil.createImageForGraphics(g, period << 1, height, BufferedImage.TYPE_INT_ARGB); + paintImage(image.createGraphics(), paint, image.getWidth(), image.getHeight(), period); + return image; + } + + @Override + public void paint(Graphics2D g, int x, int y, int width, int height, Paint paint) { + if (paint == null) paint = g.getPaint(); + g = (Graphics2D)g.create(x, y, width, height); + g.setComposite(AlphaComposite.SrcOver); + BufferedImage image = paint instanceof Color ? getImage(g, (Color)paint, height) : createImage(g, paint, height); + int period = image.getWidth(null); + int offset = (x % period + period) % period; // normalize + for (int dx = -offset; dx < width; dx += period) { + UIUtil.drawImage(g, image, dx, 0, null); + } + g.dispose(); + } + } } From b1326d769d297334b62a9ba91c5615256b6fe597 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Mon, 4 Jul 2016 16:27:43 +0300 Subject: [PATCH 52/67] PY-19461 Fixed: Inspection does not recognize all subclasses PY-19530 Fixed: from MODULE import SUBMODULE as NAME not find inheritance If superclass is imported via 'as', save its imported and original names in stubs. Use original name in PySuperClassIndex building and imported name in superclasses calculating --- .../python/psi/stubs/PyClassStub.java | 8 ++- .../python/psi/PyFileElementType.java | 2 +- .../python/psi/impl/PyClassImpl.java | 15 ++-- .../psi/impl/stubs/PyClassElementType.java | 72 +++++++++++++------ .../psi/impl/stubs/PyClassStubImpl.java | 13 ++-- .../a.py | 2 + .../b.py | 5 ++ .../a.py | 2 + .../b.py | 4 ++ .../a.py | 2 + .../b.py | 5 ++ .../python/PyInheritorsSearchTest.java | 10 ++- .../com/jetbrains/python/PyStubsTest.java | 56 +++++++++++++-- 13 files changed, 151 insertions(+), 45 deletions(-) create mode 100644 python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/a.py create mode 100644 python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/b.py create mode 100644 python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/a.py create mode 100644 python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/b.py create mode 100644 python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/a.py create mode 100644 python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/b.py diff --git a/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java b/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java index 7d00e5988bf6e..b14307af1cd10 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java +++ b/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -25,9 +25,13 @@ import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.Map; public interface PyClassStub extends NamedStub { - QualifiedName[] getSuperClasses(); + /** + * @return a {@code Map} which contains imported class names as keys and their original names as values + */ + Map getSuperClasses(); @Nullable QualifiedName getMetaClass(); List getSlots(); String getDocString(); diff --git a/python/src/com/jetbrains/python/psi/PyFileElementType.java b/python/src/com/jetbrains/python/psi/PyFileElementType.java index 3fc046be1632f..c62a709c74a23 100644 --- a/python/src/com/jetbrains/python/psi/PyFileElementType.java +++ b/python/src/com/jetbrains/python/psi/PyFileElementType.java @@ -62,7 +62,7 @@ public StubBuilder getBuilder() { @Override public int getStubVersion() { // Don't forget to update versions of indexes that use the updated stub-based elements - return 57; + return 58; } @Nullable diff --git a/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java b/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java index 928d60736ab9b..7f193e9843f06 100644 --- a/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/PyClassImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -1294,18 +1294,13 @@ private void fillSuperClassesSwitchingToAst(@NotNull TypeEvalContext context, Li private void fillSuperClassesNoSwitchToAst(@NotNull final TypeEvalContext context, @Nullable final PyClassStub stub, @NotNull final List result) { - final List qualifiedNames; - if (stub != null) { - qualifiedNames = Arrays.asList(stub.getSuperClasses()); - } - else { - qualifiedNames = PyClassElementType.getSuperClassQNames(this); - } - + final Map superClasses = stub != null + ? stub.getSuperClasses() + : PyClassElementType.getSuperClassQNames(this); final PsiFile file = getContainingFile(); if (file instanceof PyFile) { - for (QualifiedName name : qualifiedNames) { + for (QualifiedName name : superClasses.keySet()) { result.add(name != null ? classTypeFromQName(name, (PyFile)file, context) : null); } } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index a62cae8583f43..dc2f29cd4018b 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -24,12 +24,14 @@ import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyClassImpl; import com.jetbrains.python.psi.impl.PyPsiUtils; +import com.jetbrains.python.psi.resolve.PyResolveProcessor; +import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.psi.stubs.*; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; +import java.util.*; /** * @author max @@ -53,10 +55,10 @@ public PyClass createPsi(@NotNull final PyClassStub stub) { } public PyClassStub createStub(@NotNull final PyClass psi, final StubElement parentStub) { - final List superClasses = getSuperClassQNames(psi); + final Map superClasses = getSuperClassQNames(psi); final PyStringLiteralExpression docStringExpression = psi.getDocStringExpression(); return new PyClassStubImpl(psi.getName(), parentStub, - superClasses.toArray(new QualifiedName[superClasses.size()]), + superClasses, PyPsiUtils.asQualifiedName(psi.getMetaClassExpression()), psi.getOwnSlots(), PyPsiUtils.strValue(docStringExpression), @@ -64,25 +66,53 @@ public PyClassStub createStub(@NotNull final PyClass psi, final StubElement pare } @NotNull - public static List getSuperClassQNames(@NotNull final PyClass pyClass) { - final PyExpression[] exprs = pyClass.getSuperClassExpressions(); - List superClasses = new ArrayList(); - for (PyExpression expression : exprs) { - if (expression instanceof PyKeywordArgument) { - continue; + public static Map getSuperClassQNames(@NotNull final PyClass pyClass) { + final Map result = new LinkedHashMap<>(); + + Arrays + .stream(pyClass.getSuperClassExpressions()) + .filter(expression -> !PyKeywordArgument.class.isInstance(expression)) + .map(PyClassImpl::unfoldClass) + .forEach(expression -> result.put(PyPsiUtils.asQualifiedName(expression), resolveOriginalSuperClassQName(expression))); + + return result; + } + + @Nullable + private static QualifiedName resolveOriginalSuperClassQName(@NotNull PyExpression superClassExpression) { + if (superClassExpression instanceof PyReferenceExpression) { + final PyReferenceExpression reference = (PyReferenceExpression)superClassExpression; + final String referenceName = reference.getName(); + + if (referenceName == null) { + return PyPsiUtils.asQualifiedName(superClassExpression); + } + + final PyResolveProcessor processor = new PyResolveProcessor(referenceName, true); + PyResolveUtil.scopeCrawlUp(processor, reference, referenceName, null); + + final Optional qualifiedName = processor.getElements().stream() + .filter(PyImportElement.class::isInstance) + .map(PyImportElement.class::cast) + .filter(element -> element.getAsName() != null) + .map(PyImportElement::getImportedQName) + .findAny(); + + if (qualifiedName.isPresent()) { + return qualifiedName.get(); } - expression = PyClassImpl.unfoldClass(expression); - superClasses.add(PyPsiUtils.asQualifiedName(expression)); } - return superClasses; + + return PyPsiUtils.asQualifiedName(superClassExpression); } public void serialize(@NotNull final PyClassStub pyClassStub, @NotNull final StubOutputStream dataStream) throws IOException { dataStream.writeName(pyClassStub.getName()); - final QualifiedName[] classes = pyClassStub.getSuperClasses(); - dataStream.writeByte(classes.length); - for (QualifiedName s : classes) { - QualifiedName.serialize(s, dataStream); + final Map superClasses = pyClassStub.getSuperClasses(); + dataStream.writeByte(superClasses.size()); + for (Map.Entry entry : superClasses.entrySet()) { + QualifiedName.serialize(entry.getKey(), dataStream); + QualifiedName.serialize(entry.getValue(), dataStream); } QualifiedName.serialize(pyClassStub.getMetaClass(), dataStream); PyFileElementType.writeNullableList(dataStream, pyClassStub.getSlots()); @@ -94,9 +124,9 @@ public void serialize(@NotNull final PyClassStub pyClassStub, @NotNull final Stu public PyClassStub deserialize(@NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException { String name = StringRef.toString(dataStream.readName()); int superClassCount = dataStream.readByte(); - QualifiedName[] superClasses = new QualifiedName[superClassCount]; + Map superClasses = new LinkedHashMap<>(); for (int i = 0; i < superClassCount; i++) { - superClasses[i] = QualifiedName.deserialize(dataStream); + superClasses.put(QualifiedName.deserialize(dataStream), QualifiedName.deserialize(dataStream)); } final QualifiedName metaClass = QualifiedName.deserialize(dataStream); List slots = PyFileElementType.readNullableList(dataStream); @@ -115,7 +145,7 @@ public void indexStub(@NotNull final PyClassStub stub, @NotNull final IndexSink for (String attribute : PyClassAttributesIndex.getAllDeclaredAttributeNames(pyClass)) { sink.occurrence(PyClassAttributesIndex.KEY, attribute); } - for (QualifiedName s : stub.getSuperClasses()) { + for (QualifiedName s : stub.getSuperClasses().values()) { if (s != null) { String className = s.getLastComponent(); if (className != null) { diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java index 294885838bfc0..934db36edb906 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -18,25 +18,26 @@ import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubBase; import com.intellij.psi.stubs.StubElement; -import com.jetbrains.python.psi.PyClass; import com.intellij.psi.util.QualifiedName; +import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.stubs.PyClassStub; import org.jetbrains.annotations.Nullable; import java.util.List; +import java.util.Map; /** * @author max */ public class PyClassStubImpl extends StubBase implements PyClassStub { private final String myName; - private final QualifiedName[] mySuperClasses; + private final Map mySuperClasses; @Nullable private final QualifiedName myMetaClass; private final List mySlots; private final String myDocString; - public PyClassStubImpl(final String name, StubElement parentStub, final QualifiedName[] superClasses, @Nullable QualifiedName metaClass, - final List slots, String docString, IStubElementType stubElementType) { + public PyClassStubImpl(final String name, StubElement parentStub, final Map superClasses, + @Nullable QualifiedName metaClass, final List slots, String docString, IStubElementType stubElementType) { super(parentStub, stubElementType); myName = name; mySuperClasses = superClasses; @@ -49,7 +50,7 @@ public String getName() { return myName; } - public QualifiedName[] getSuperClasses() { + public Map getSuperClasses() { return mySuperClasses; } diff --git a/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/a.py b/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/a.py new file mode 100644 index 0000000000000..67b24cac95098 --- /dev/null +++ b/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/a.py @@ -0,0 +1,2 @@ +class C: + pass \ No newline at end of file diff --git a/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/b.py b/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/b.py new file mode 100644 index 0000000000000..475d9ea8466cd --- /dev/null +++ b/python/testData/inheritors/inheritorsWhenSuperClassImportedWithAs/b.py @@ -0,0 +1,5 @@ +from a import C as C2 + + +class D(C2): + pass \ No newline at end of file diff --git a/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/a.py b/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/a.py new file mode 100644 index 0000000000000..696b8ce26dab1 --- /dev/null +++ b/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/a.py @@ -0,0 +1,2 @@ +class A(object): + pass \ No newline at end of file diff --git a/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/b.py b/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/b.py new file mode 100644 index 0000000000000..849937b67b395 --- /dev/null +++ b/python/testData/stubs/ancestorsWhenSuperClassImportedWithQName/b.py @@ -0,0 +1,4 @@ +import A + +class B(A.A): + pass \ No newline at end of file diff --git a/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/a.py b/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/a.py new file mode 100644 index 0000000000000..67b24cac95098 --- /dev/null +++ b/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/a.py @@ -0,0 +1,2 @@ +class C: + pass \ No newline at end of file diff --git a/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/b.py b/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/b.py new file mode 100644 index 0000000000000..475d9ea8466cd --- /dev/null +++ b/python/testData/stubs/inheritorsWhenSuperClassImportedWithAs/b.py @@ -0,0 +1,5 @@ +from a import C as C2 + + +class D(C2): + pass \ No newline at end of file diff --git a/python/testSrc/com/jetbrains/python/PyInheritorsSearchTest.java b/python/testSrc/com/jetbrains/python/PyInheritorsSearchTest.java index 11c02f14abdc4..c0ebd0d929dad 100644 --- a/python/testSrc/com/jetbrains/python/PyInheritorsSearchTest.java +++ b/python/testSrc/com/jetbrains/python/PyInheritorsSearchTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -49,6 +49,14 @@ public void testDotted() throws Exception { assertEquals(1, inheritors.size()); } + // PY-19461 + public void testInheritorsWhenSuperClassImportedWithAs() throws Exception { + setupProject(); + final PyClass pyClass = findClass("C"); + final Collection inheritors = PyClassInheritorsSearch.search(pyClass, false).findAll(); + assertSameElements(inheritors, findClass("D")); + } + private void setupProject() throws Exception { String testName = getTestName(true); myFixture.copyDirectoryToProject(testName, ""); diff --git a/python/testSrc/com/jetbrains/python/PyStubsTest.java b/python/testSrc/com/jetbrains/python/PyStubsTest.java index 60eaac935e800..c4bddf13d69ac 100644 --- a/python/testSrc/com/jetbrains/python/PyStubsTest.java +++ b/python/testSrc/com/jetbrains/python/PyStubsTest.java @@ -25,7 +25,9 @@ import com.intellij.psi.*; import com.intellij.psi.impl.source.PsiFileImpl; import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.psi.search.ProjectScope; import com.intellij.psi.stubs.StubElement; +import com.intellij.psi.stubs.StubIndex; import com.intellij.psi.util.QualifiedName; import com.intellij.testFramework.TestDataPath; import com.jetbrains.python.codeInsight.stdlib.PyNamedTupleType; @@ -35,6 +37,7 @@ import com.jetbrains.python.psi.impl.PythonLanguageLevelPusher; import com.jetbrains.python.psi.stubs.PyClassNameIndex; import com.jetbrains.python.psi.stubs.PyNamedTupleStub; +import com.jetbrains.python.psi.stubs.PySuperClassIndex; import com.jetbrains.python.psi.stubs.PyVariableNameIndex; import com.jetbrains.python.psi.types.PyType; import com.jetbrains.python.psi.types.TypeEvalContext; @@ -42,10 +45,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; /** * @author max @@ -548,4 +548,52 @@ private static void doTestNamedTuple(@NotNull String expectedName, assertEquals(expectedName, namedTupleType.getName()); assertEquals(expectedFields, namedTupleType.getElementNames()); } + + // PY-19461 + public void testInheritorsWhenSuperClassImportedWithAs() { + final PyFile file1 = getTestFile("inheritorsWhenSuperClassImportedWithAs/a.py"); + final PyFile file2 = getTestFile("inheritorsWhenSuperClassImportedWithAs/b.py"); + + final Project project = myFixture.getProject(); + + final Collection classes = + StubIndex.getElements(PySuperClassIndex.KEY, "C", project, ProjectScope.getAllScope(project), PyClass.class); + + assertEquals(1, classes.size()); + assertEquals("D", classes.iterator().next().getName()); + + assertNotParsed(file1); + assertNotParsed(file2); + } + + // PY-19461 + public void testAncestorsWhenSuperClassImportedWithAs() { + final PyFile file1 = getTestFile("inheritorsWhenSuperClassImportedWithAs/a.py"); + final PyFile file2 = getTestFile("inheritorsWhenSuperClassImportedWithAs/b.py"); + + final PyClass pyClass = file2.findTopLevelClass("D"); + assertNotNull(pyClass); + + final Map superClasses = pyClass.getStub().getSuperClasses(); + assertEquals(1, superClasses.size()); + assertEquals(QualifiedName.fromComponents("C"), superClasses.get(QualifiedName.fromComponents("C2"))); + + assertNotParsed(file1); + assertNotParsed(file2); + } + + public void testAncestorsWhenSuperClassImportedWithQName() { + final PyFile file1 = getTestFile("ancestorsWhenSuperClassImportedWithQName/a.py"); + final PyFile file2 = getTestFile("ancestorsWhenSuperClassImportedWithQName/b.py"); + + final PyClass pyClass = file2.findTopLevelClass("B"); + assertNotNull(pyClass); + + final Map superClasses = pyClass.getStub().getSuperClasses(); + assertEquals(1, superClasses.size()); + assertEquals(QualifiedName.fromDottedString("A.A"), superClasses.get(QualifiedName.fromDottedString("A.A"))); + + assertNotParsed(file1); + assertNotParsed(file2); + } } From 3fd146f13a9eeb0e02df5c790e281dbe6d8a260d Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 14:57:42 +0300 Subject: [PATCH 53/67] NotNull annotation for PyStubElementType.createElement and its inheritors --- .../jetbrains/plugins/ipnb/psi/IpnbFunctionElementType.java | 1 + .../plugins/ipnb/psi/IpnbPyTargetExpressionElementType.java | 1 + .../src/com/jetbrains/python/psi/PyStubElementType.java | 1 + .../python/psi/impl/stubs/PyAnnotationElementType.java | 1 + .../jetbrains/python/psi/impl/stubs/PyClassElementType.java | 1 + .../python/psi/impl/stubs/PyDecoratorCallElementType.java | 1 + .../python/psi/impl/stubs/PyDecoratorListElementType.java | 1 + .../python/psi/impl/stubs/PyExceptPartElementType.java | 1 + .../psi/impl/stubs/PyFromImportStatementElementType.java | 3 ++- .../jetbrains/python/psi/impl/stubs/PyFunctionElementType.java | 1 + .../python/psi/impl/stubs/PyImportElementElementType.java | 3 ++- .../python/psi/impl/stubs/PyImportStatementElementType.java | 1 + .../python/psi/impl/stubs/PyNamedParameterElementType.java | 3 ++- .../python/psi/impl/stubs/PyParameterListElementType.java | 1 + .../psi/impl/stubs/PySingleStarParameterElementType.java | 1 + .../python/psi/impl/stubs/PyStarImportElementElementType.java | 1 + .../python/psi/impl/stubs/PyTargetExpressionElementType.java | 1 + .../python/psi/impl/stubs/PyTupleParameterElementType.java | 1 + 18 files changed, 21 insertions(+), 3 deletions(-) diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbFunctionElementType.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbFunctionElementType.java index 80723bdb1f951..4a282cf530223 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbFunctionElementType.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbFunctionElementType.java @@ -13,6 +13,7 @@ public IpnbFunctionElementType() { super("IPNB_FUNCTION"); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new IpnbPyFunction(node); diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbPyTargetExpressionElementType.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbPyTargetExpressionElementType.java index 07cdf7d528683..11e6e8992591c 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbPyTargetExpressionElementType.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/psi/IpnbPyTargetExpressionElementType.java @@ -27,6 +27,7 @@ public IpnbPyTargetExpressionElementType() { super("IPNB_TARGET_EXPRESSION"); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new IpnbPyTargetExpression(node); } diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java b/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java index 4b496504a6b07..961e9d35392c0 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java +++ b/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java @@ -37,6 +37,7 @@ public String toString() { return "Py:" + super.toString(); } + @NotNull public abstract PsiElement createElement(@NotNull final ASTNode node); public void indexStub(@NotNull final StubT stub, @NotNull final IndexSink sink) { diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java index 8dcb90cb9535b..4fa87d6171d3e 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java @@ -50,6 +50,7 @@ public PyAnnotationStub createStub(@NotNull final PyAnnotation psi, final StubEl return new PyAnnotationStubImpl(parentStub, PyElementTypes.ANNOTATION); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyAnnotationImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index dc2f29cd4018b..22c40bee93a74 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -46,6 +46,7 @@ public PyClassElementType(String debugName) { super(debugName); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyClassImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java index e3244660ff7b7..84fdd0b32b487 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java @@ -41,6 +41,7 @@ public PyDecoratorCallElementType() { super("DECORATOR_CALL"); } + @NotNull public PsiElement createElement(@NotNull ASTNode node) { return new PyDecoratorImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java index fdebf51c1d725..f57c78df7c6fa 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java @@ -39,6 +39,7 @@ public PyDecoratorListElementType() { super("DECORATOR_LIST"); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyDecoratorListImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java index 12f8eb22d8db4..0c885d225ada8 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java @@ -36,6 +36,7 @@ public PyExceptPartElementType() { super("EXCEPT_PART"); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new PyExceptPartImpl(node); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java index 71734d5f8955e..6da49034dbb14 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java @@ -21,11 +21,11 @@ import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; +import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.psi.PyFromImportStatement; import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyFromImportStatementImpl; -import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.stubs.PyFromImportStatementStub; import org.jetbrains.annotations.NotNull; @@ -43,6 +43,7 @@ public PyFromImportStatementElementType(String debugName) { super(debugName); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new PyFromImportStatementImpl(node); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java index bc17a691c8fdd..c8d8672fab576 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java @@ -44,6 +44,7 @@ public PyFunctionElementType(String debugName) { super(debugName); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyFunctionImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java index 53be66e1c6227..db450288fae52 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java @@ -21,13 +21,13 @@ import com.intellij.psi.stubs.StubElement; import com.intellij.psi.stubs.StubInputStream; import com.intellij.psi.stubs.StubOutputStream; +import com.intellij.psi.util.QualifiedName; import com.intellij.util.io.StringRef; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.psi.PyImportElement; import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.PyTargetExpression; import com.jetbrains.python.psi.impl.PyImportElementImpl; -import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.stubs.PyImportElementStub; import org.jetbrains.annotations.NotNull; @@ -45,6 +45,7 @@ public PyImportElementElementType(String debugName) { super(debugName); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new PyImportElementImpl(node); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java index f0f80ffe7734e..c7110df768011 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java @@ -42,6 +42,7 @@ public PyImportStatementElementType(String debugName) { super(debugName); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new PyImportStatementImpl(node); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java index d46e04410e58c..3fc2335c9f535 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java @@ -23,8 +23,8 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.stubs.IStubElementType; import com.intellij.psi.stubs.StubElement; -import com.intellij.psi.stubs.StubOutputStream; import com.intellij.psi.stubs.StubInputStream; +import com.intellij.psi.stubs.StubOutputStream; import com.intellij.util.io.StringRef; import com.jetbrains.python.PyElementTypes; import com.jetbrains.python.psi.PyNamedParameter; @@ -57,6 +57,7 @@ public PyNamedParameterStub createStub(@NotNull final PyNamedParameter psi, fina psi.getTypeCommentAnnotation(), parentStub, getStubElementType()); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyNamedParameterImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java index 46a2944b5e10b..f5f1ead044c1b 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java @@ -51,6 +51,7 @@ public PyParameterListStub createStub(@NotNull final PyParameterList psi, final return new PyParameterListStubImpl(parentStub, getStubElementType()); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyParameterListImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java index 4efa28ec03417..6260be7149818 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java @@ -36,6 +36,7 @@ public PySingleStarParameterElementType() { super("SINGLE_STAR_PARAMETER"); } + @NotNull @Override public PsiElement createElement(@NotNull ASTNode node) { return new PySingleStarParameterImpl(node); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java index f1fb25c5e8d73..20c17bde67f01 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java @@ -36,6 +36,7 @@ public PyStarImportElementElementType() { super("STAR_IMPORT_ELEMENT"); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyStarImportElementImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java index 0fd30fe1c818d..d2f8809f70b77 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java @@ -58,6 +58,7 @@ private CustomTargetExpressionStubType[] getCustomStubTypes() { return myCustomStubTypes; } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyTargetExpressionImpl(node); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java index a5cb712c3477d..31803df2ef892 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java @@ -37,6 +37,7 @@ public PyTupleParameterElementType() { super("TUPLE_PARAMETER"); } + @NotNull public PsiElement createElement(@NotNull final ASTNode node) { return new PyTupleParameterImpl(node); } From cabe8bb04ce2ea038649af7d2f848f809016fc53 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 15:09:06 +0300 Subject: [PATCH 54/67] NotNull annotation for IStubElementType.createStub and its inheritors --- .../com/intellij/psi/impl/java/stubs/JavaStubElementType.java | 1 + .../core-api/src/com/intellij/psi/stubs/IStubElementType.java | 1 + .../plugins/groovy/lang/parser/GroovyElementTypes.java | 2 ++ .../groovy/lang/psi/stubs/elements/GrAnnotationElementType.java | 1 + .../lang/psi/stubs/elements/GrEnumConstantElementType.java | 1 + .../groovy/lang/psi/stubs/elements/GrFieldElementType.java | 1 + .../lang/psi/stubs/elements/GrImportStatementElementType.java | 1 + .../groovy/lang/psi/stubs/elements/GrMethodElementType.java | 1 + .../lang/psi/stubs/elements/GrModifierListElementType.java | 1 + .../lang/psi/stubs/elements/GrPackageDefinitionElementType.java | 1 + .../lang/psi/stubs/elements/GrReferenceListElementType.java | 1 + .../lang/psi/stubs/elements/GrTypeDefinitionElementType.java | 1 + .../lang/properties/parsing/PropertyListStubElementType.java | 1 + .../lang/properties/parsing/PropertyStubElementType.java | 1 + .../python/psi/impl/stubs/PyAnnotationElementType.java | 1 + .../com/jetbrains/python/psi/impl/stubs/PyClassElementType.java | 1 + .../python/psi/impl/stubs/PyDecoratorCallElementType.java | 1 + .../python/psi/impl/stubs/PyDecoratorListElementType.java | 1 + .../python/psi/impl/stubs/PyExceptPartElementType.java | 1 + .../python/psi/impl/stubs/PyFromImportStatementElementType.java | 1 + .../jetbrains/python/psi/impl/stubs/PyFunctionElementType.java | 1 + .../python/psi/impl/stubs/PyImportElementElementType.java | 1 + .../python/psi/impl/stubs/PyImportStatementElementType.java | 1 + .../python/psi/impl/stubs/PyNamedParameterElementType.java | 1 + .../python/psi/impl/stubs/PyParameterListElementType.java | 1 + .../python/psi/impl/stubs/PySingleStarParameterElementType.java | 1 + .../python/psi/impl/stubs/PyStarImportElementElementType.java | 1 + .../python/psi/impl/stubs/PyTargetExpressionElementType.java | 1 + .../python/psi/impl/stubs/PyTupleParameterElementType.java | 1 + 29 files changed, 30 insertions(+) diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaStubElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaStubElementType.java index 35af99af74da9..ac7509c304e4e 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaStubElementType.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaStubElementType.java @@ -67,6 +67,7 @@ private PsiJavaFileStub getFileStub(StubT stub) { @SuppressWarnings("MethodOverloadsMethodOfSuperclass") public abstract PsiT createPsi(@NotNull ASTNode node); + @NotNull @Override public final StubT createStub(@NotNull final PsiT psi, final StubElement parentStub) { final String message = "Should not be called. Element=" + psi + "; class" + psi.getClass() + "; file=" + (psi.isValid() ? psi.getContainingFile() : "-"); diff --git a/platform/core-api/src/com/intellij/psi/stubs/IStubElementType.java b/platform/core-api/src/com/intellij/psi/stubs/IStubElementType.java index 635b47d72ed97..83784304b04d7 100644 --- a/platform/core-api/src/com/intellij/psi/stubs/IStubElementType.java +++ b/platform/core-api/src/com/intellij/psi/stubs/IStubElementType.java @@ -34,6 +34,7 @@ public IStubElementType(@NotNull @NonNls final String debugName, @Nullable final public abstract PsiT createPsi(@NotNull StubT stub); + @NotNull public abstract StubT createStub(@NotNull PsiT psi, final StubElement parentStub); public boolean shouldCreateStub(ASTNode node) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java index 298b0fb698178..6596d556bf950 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java @@ -285,6 +285,7 @@ public GrTypeParameter createPsi(@NotNull GrTypeParameterStub stub) { return new GrTypeParameterImpl(stub); } + @NotNull @Override public GrTypeParameterStub createStub(@NotNull GrTypeParameter psi, StubElement parentStub) { return new GrTypeParameterStub(parentStub, StringRef.fromString(psi.getName())); @@ -341,6 +342,7 @@ public GrParameter createPsi(@NotNull GrParameterStub stub) { return new GrParameterImpl(stub); } + @NotNull @Override public GrParameterStub createStub(@NotNull GrParameter psi, StubElement parentStub) { return new GrParameterStub(parentStub, StringRef.fromString(psi.getName()), GrStubUtils.getAnnotationNames(psi), GrStubUtils.getTypeText( diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrAnnotationElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrAnnotationElementType.java index c3612d919a359..95d53ddac2069 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrAnnotationElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrAnnotationElementType.java @@ -38,6 +38,7 @@ public GrAnnotation createPsi(@NotNull GrAnnotationStub stub) { return new GrAnnotationImpl(stub); } + @NotNull @Override public GrAnnotationStub createStub(@NotNull GrAnnotation psi, StubElement parentStub) { return new GrAnnotationStub(parentStub, psi); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java index 1c40db3d435cd..006dd1d395faf 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrEnumConstantElementType.java @@ -44,6 +44,7 @@ public GrEnumConstant createPsi(@NotNull GrFieldStub stub) { return new GrEnumConstantImpl(stub); } + @NotNull @Override public GrFieldStub createStub(@NotNull GrEnumConstant psi, StubElement parentStub) { String[] annNames = GrStubUtils.getAnnotationNames(psi); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrFieldElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrFieldElementType.java index 594c16fd234a7..55fdc3f53adfd 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrFieldElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrFieldElementType.java @@ -48,6 +48,7 @@ public GrField createPsi(@NotNull GrFieldStub stub) { return new GrFieldImpl(stub); } + @NotNull @Override public GrFieldStub createStub(@NotNull GrField psi, StubElement parentStub) { String[] annNames = GrStubUtils.getAnnotationNames(psi); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java index 75253b8ff32fa..6a30a414c516b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java @@ -41,6 +41,7 @@ public GrImportStatement createPsi(@NotNull GrImportStatementStub stub) { return new GrImportStatementImpl(stub, this); } + @NotNull @Override public GrImportStatementStub createStub(@NotNull GrImportStatement psi, StubElement parentStub) { GrCodeReferenceElement ref = psi.getImportReference(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrMethodElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrMethodElementType.java index 947f619aaa111..2fe6ceeb6b862 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrMethodElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrMethodElementType.java @@ -41,6 +41,7 @@ public GrMethodElementType(final String debugName) { super(debugName); } + @NotNull @Override public GrMethodStub createStub(@NotNull GrMethod psi, StubElement parentStub) { diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrModifierListElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrModifierListElementType.java index 2294fc9e43486..9f51aeaf73da5 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrModifierListElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrModifierListElementType.java @@ -39,6 +39,7 @@ public GrModifierList createPsi(@NotNull GrModifierListStub stub) { return new GrModifierListImpl(stub); } + @NotNull @Override public GrModifierListStub createStub(@NotNull GrModifierList psi, StubElement parentStub) { return new GrModifierListStub(parentStub, GroovyElementTypes.MODIFIERS, GrModifierListStub.buildFlags(psi)); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrPackageDefinitionElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrPackageDefinitionElementType.java index ffdbcfdc2ee6b..9d59a6c9f0fe4 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrPackageDefinitionElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrPackageDefinitionElementType.java @@ -38,6 +38,7 @@ public GrPackageDefinition createPsi(@NotNull GrPackageDefinitionStub stub) { return new GrPackageDefinitionImpl(stub); } + @NotNull @Override public GrPackageDefinitionStub createStub(@NotNull GrPackageDefinition psi, StubElement parentStub) { return new GrPackageDefinitionStub(parentStub, GroovyElementTypes.PACKAGE_DEFINITION, StringRef.fromString(psi.getPackageName())); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrReferenceListElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrReferenceListElementType.java index d69c2a2b4c2ce..97852ecb1f131 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrReferenceListElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrReferenceListElementType.java @@ -42,6 +42,7 @@ public GrReferenceListElementType(final String debugName) { super(debugName); } + @NotNull @Override public GrReferenceListStub createStub(@NotNull T psi, StubElement parentStub) { List refNames = new ArrayList(); diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrTypeDefinitionElementType.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrTypeDefinitionElementType.java index 86cdca9c67507..08c8b92df5a00 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrTypeDefinitionElementType.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrTypeDefinitionElementType.java @@ -42,6 +42,7 @@ public GrTypeDefinitionElementType(@NotNull String debugName) { super(debugName); } + @NotNull @Override public GrTypeDefinitionStub createStub(@NotNull TypeDef psi, StubElement parentStub) { final byte flags = GrTypeDefinitionStub.buildFlags(psi); diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyListStubElementType.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyListStubElementType.java index 604e271f90358..438d470f01771 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyListStubElementType.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyListStubElementType.java @@ -39,6 +39,7 @@ public PropertiesList createPsi(@NotNull final PropertiesListStub stub) { return new PropertiesListImpl(stub); } + @NotNull public PropertiesListStub createStub(@NotNull final PropertiesList psi, final StubElement parentStub) { return new PropertiesListStubImpl(parentStub); } diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyStubElementType.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyStubElementType.java index f8eed2902c1f1..752779787346f 100644 --- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyStubElementType.java +++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/parsing/PropertyStubElementType.java @@ -44,6 +44,7 @@ public Property createPsi(@NotNull final PropertyStub stub) { return new PropertyImpl(stub, this); } + @NotNull public PropertyStub createStub(@NotNull final Property psi, final StubElement parentStub) { return new PropertyStubImpl(parentStub, psi.getKey()); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java index 4fa87d6171d3e..28c4c5efdc828 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java @@ -46,6 +46,7 @@ public PyAnnotation createPsi(@NotNull final PyAnnotationStub stub) { return new PyAnnotationImpl(stub); } + @NotNull public PyAnnotationStub createStub(@NotNull final PyAnnotation psi, final StubElement parentStub) { return new PyAnnotationStubImpl(parentStub, PyElementTypes.ANNOTATION); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index 22c40bee93a74..b8cca89504752 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -55,6 +55,7 @@ public PyClass createPsi(@NotNull final PyClassStub stub) { return new PyClassImpl(stub); } + @NotNull public PyClassStub createStub(@NotNull final PyClass psi, final StubElement parentStub) { final Map superClasses = getSuperClassQNames(psi); final PyStringLiteralExpression docStringExpression = psi.getDocStringExpression(); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java index 84fdd0b32b487..b713c15cde793 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorCallElementType.java @@ -50,6 +50,7 @@ public PyDecorator createPsi(@NotNull PyDecoratorStub stub) { return new PyDecoratorImpl(stub); } + @NotNull public PyDecoratorStub createStub(@NotNull PyDecorator psi, StubElement parentStub) { return new PyDecoratorStubImpl(psi.getQualifiedName(), parentStub); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java index f57c78df7c6fa..f97cd7f140108 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyDecoratorListElementType.java @@ -48,6 +48,7 @@ public PyDecoratorList createPsi(@NotNull final PyDecoratorListStub stub) { return new PyDecoratorListImpl(stub); } + @NotNull public PyDecoratorListStub createStub(@NotNull final PyDecoratorList psi, final StubElement parentStub) { return new PyDecoratorListStubImpl(parentStub); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java index 0c885d225ada8..04431c30387da 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyExceptPartElementType.java @@ -47,6 +47,7 @@ public PyExceptPart createPsi(@NotNull PyExceptPartStub stub) { return new PyExceptPartImpl(stub); } + @NotNull @Override public PyExceptPartStub createStub(@NotNull PyExceptPart psi, StubElement parentStub) { return new PyExceptPartStubImpl(parentStub); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java index 6da49034dbb14..26e6c1cac34e2 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java @@ -54,6 +54,7 @@ public PyFromImportStatement createPsi(@NotNull PyFromImportStatementStub stub) return new PyFromImportStatementImpl(stub); } + @NotNull @Override public PyFromImportStatementStub createStub(@NotNull PyFromImportStatement psi, StubElement parentStub) { return new PyFromImportStatementStubImpl(psi.getImportSourceQName(), psi.isStarImport(), psi.getRelativeLevel(), parentStub, diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java index c8d8672fab576..8281102038ad3 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java @@ -53,6 +53,7 @@ public PyFunction createPsi(@NotNull final PyFunctionStub stub) { return new PyFunctionImpl(stub); } + @NotNull public PyFunctionStub createStub(@NotNull final PyFunction psi, final StubElement parentStub) { PyFunctionImpl function = (PyFunctionImpl)psi; String message = function.extractDeprecationMessage(); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java index db450288fae52..9650dd1a672e1 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java @@ -56,6 +56,7 @@ public PyImportElement createPsi(@NotNull PyImportElementStub stub) { return new PyImportElementImpl(stub); } + @NotNull @Override public PyImportElementStub createStub(@NotNull PyImportElement psi, StubElement parentStub) { final PyTargetExpression asName = psi.getAsNameElement(); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java index c7110df768011..8ae39f312a1ee 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java @@ -53,6 +53,7 @@ public PyImportStatement createPsi(@NotNull PyImportStatementStub stub) { return new PyImportStatementImpl(stub); } + @NotNull @Override public PyImportStatementStub createStub(@NotNull PyImportStatement psi, StubElement parentStub) { return new PyImportStatementStubImpl(parentStub, getStubElementType()); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java index 3fc2335c9f535..d54c39ca8f4a4 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java @@ -52,6 +52,7 @@ public PyNamedParameter createPsi(@NotNull final PyNamedParameterStub stub) { return new PyNamedParameterImpl(stub); } + @NotNull public PyNamedParameterStub createStub(@NotNull final PyNamedParameter psi, final StubElement parentStub) { return new PyNamedParameterStubImpl(psi.getName(), psi.isPositionalContainer(), psi.isKeywordContainer(), psi.hasDefaultValue(), psi.getTypeCommentAnnotation(), parentStub, getStubElementType()); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java index f5f1ead044c1b..87ebdc36c8af3 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java @@ -47,6 +47,7 @@ public PyParameterList createPsi(@NotNull final PyParameterListStub stub) { return new PyParameterListImpl(stub); } + @NotNull public PyParameterListStub createStub(@NotNull final PyParameterList psi, final StubElement parentStub) { return new PyParameterListStubImpl(parentStub, getStubElementType()); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java index 6260be7149818..dbe05ec388236 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PySingleStarParameterElementType.java @@ -47,6 +47,7 @@ public PySingleStarParameter createPsi(@NotNull PySingleStarParameterStub stub) return new PySingleStarParameterImpl(stub); } + @NotNull @Override public PySingleStarParameterStub createStub(@NotNull PySingleStarParameter psi, StubElement parentStub) { return new PySingleStarParameterStubImpl(parentStub); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java index 20c17bde67f01..752dbd5c78615 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyStarImportElementElementType.java @@ -45,6 +45,7 @@ public PyStarImportElement createPsi(@NotNull final PyStarImportElementStub stub return new PyStarImportElementImpl(stub); } + @NotNull public PyStarImportElementStub createStub(@NotNull final PyStarImportElement psi, final StubElement parentStub) { return new PyStarImportElementStubImpl(parentStub); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java index d2f8809f70b77..d8c7ff9114058 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java @@ -67,6 +67,7 @@ public PyTargetExpression createPsi(@NotNull final PyTargetExpressionStub stub) return new PyTargetExpressionImpl(stub); } + @NotNull public PyTargetExpressionStub createStub(@NotNull final PyTargetExpression psi, final StubElement parentStub) { final String name = psi.getName(); final PyExpression assignedValue = psi.findAssignedValue(); diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java index 31803df2ef892..713934eec0ec0 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTupleParameterElementType.java @@ -46,6 +46,7 @@ public PyTupleParameter createPsi(@NotNull PyTupleParameterStub stub) { return new PyTupleParameterImpl(stub); } + @NotNull public PyTupleParameterStub createStub(@NotNull PyTupleParameter psi, StubElement parentStub) { return new PyTupleParameterStubImpl(psi.hasDefaultValue(), parentStub); } From f4fa3d0eb71300e0d4e8431a79eb4072d7b85262 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 15:15:36 +0300 Subject: [PATCH 55/67] Annotation for PyStubElementType.PyStubElementType and its inheritors --- .../src/com/jetbrains/python/psi/PyStubElementType.java | 2 +- .../python/psi/impl/stubs/PyAnnotationElementType.java | 3 ++- .../jetbrains/python/psi/impl/stubs/PyClassElementType.java | 3 ++- .../psi/impl/stubs/PyFromImportStatementElementType.java | 3 ++- .../jetbrains/python/psi/impl/stubs/PyFunctionElementType.java | 3 ++- .../python/psi/impl/stubs/PyImportElementElementType.java | 3 ++- .../python/psi/impl/stubs/PyImportStatementElementType.java | 3 ++- .../python/psi/impl/stubs/PyNamedParameterElementType.java | 3 ++- .../python/psi/impl/stubs/PyParameterListElementType.java | 3 ++- .../python/psi/impl/stubs/PyTargetExpressionElementType.java | 3 ++- 10 files changed, 19 insertions(+), 10 deletions(-) diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java b/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java index 961e9d35392c0..819ec557388c7 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java +++ b/python/psi-api/src/com/jetbrains/python/psi/PyStubElementType.java @@ -28,7 +28,7 @@ * @author max */ public abstract class PyStubElementType extends IStubElementType { - public PyStubElementType(@NonNls String debugName) { + public PyStubElementType(@NotNull @NonNls String debugName) { super(debugName, PythonFileType.INSTANCE.getLanguage()); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java index 28c4c5efdc828..0c7caf3056b27 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyAnnotationElementType.java @@ -29,6 +29,7 @@ import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyAnnotationImpl; import com.jetbrains.python.psi.stubs.PyAnnotationStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -38,7 +39,7 @@ public PyAnnotationElementType() { this("ANNOTATION"); } - public PyAnnotationElementType(String debugName) { + public PyAnnotationElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index b8cca89504752..16b680586e7f7 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -27,6 +27,7 @@ import com.jetbrains.python.psi.resolve.PyResolveProcessor; import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.psi.stubs.*; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -42,7 +43,7 @@ public PyClassElementType() { this("CLASS_DECLARATION"); } - public PyClassElementType(String debugName) { + public PyClassElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java index 26e6c1cac34e2..4a7490ddca97d 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFromImportStatementElementType.java @@ -27,6 +27,7 @@ import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyFromImportStatementImpl; import com.jetbrains.python.psi.stubs.PyFromImportStatementStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -39,7 +40,7 @@ public PyFromImportStatementElementType() { this("FROM_IMPORT_STATEMENT"); } - public PyFromImportStatementElementType(String debugName) { + public PyFromImportStatementElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java index 8281102038ad3..b3127dc3dc0ba 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyFunctionElementType.java @@ -28,6 +28,7 @@ import com.jetbrains.python.psi.impl.PyPsiUtils; import com.jetbrains.python.psi.stubs.PyFunctionNameIndex; import com.jetbrains.python.psi.stubs.PyFunctionStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -40,7 +41,7 @@ public PyFunctionElementType() { this("FUNCTION_DECLARATION"); } - public PyFunctionElementType(String debugName) { + public PyFunctionElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java index 9650dd1a672e1..7dd2018f92588 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportElementElementType.java @@ -29,6 +29,7 @@ import com.jetbrains.python.psi.PyTargetExpression; import com.jetbrains.python.psi.impl.PyImportElementImpl; import com.jetbrains.python.psi.stubs.PyImportElementStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -41,7 +42,7 @@ public PyImportElementElementType() { this("IMPORT_ELEMENT"); } - public PyImportElementElementType(String debugName) { + public PyImportElementElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java index 8ae39f312a1ee..bbfa952bc74d3 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyImportStatementElementType.java @@ -26,6 +26,7 @@ import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyImportStatementImpl; import com.jetbrains.python.psi.stubs.PyImportStatementStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -38,7 +39,7 @@ public PyImportStatementElementType() { this("IMPORT_STATEMENT"); } - public PyImportStatementElementType(String debugName) { + public PyImportStatementElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java index d54c39ca8f4a4..626effc7da0a8 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedParameterElementType.java @@ -31,6 +31,7 @@ import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyNamedParameterImpl; import com.jetbrains.python.psi.stubs.PyNamedParameterStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -44,7 +45,7 @@ public PyNamedParameterElementType() { this("NAMED_PARAMETER"); } - public PyNamedParameterElementType(String debugName) { + public PyNamedParameterElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java index 87ebdc36c8af3..e6cc66f3b2c80 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyParameterListElementType.java @@ -30,6 +30,7 @@ import com.jetbrains.python.psi.PyStubElementType; import com.jetbrains.python.psi.impl.PyParameterListImpl; import com.jetbrains.python.psi.stubs.PyParameterListStub; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -39,7 +40,7 @@ public PyParameterListElementType() { this("PARAMETER_LIST"); } - public PyParameterListElementType(String debugName) { + public PyParameterListElementType(@NotNull @NonNls String debugName) { super(debugName); } diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java index d8c7ff9114058..74320424f1087 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyTargetExpressionElementType.java @@ -33,6 +33,7 @@ import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyTargetExpressionImpl; import com.jetbrains.python.psi.stubs.*; +import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -47,7 +48,7 @@ public PyTargetExpressionElementType() { super("TARGET_EXPRESSION"); } - public PyTargetExpressionElementType(String debugName) { + public PyTargetExpressionElementType(@NotNull @NonNls String debugName) { super(debugName); } From 71f122f9f5aada73068441b91bd5e218d41e8695 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 15:45:55 +0300 Subject: [PATCH 56/67] Attempt to make PyClassElementType more readable --- .../psi/impl/stubs/PyClassElementType.java | 51 +++++++++++-------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index 16b680586e7f7..1af45bfaa06ea 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -58,13 +58,12 @@ public PyClass createPsi(@NotNull final PyClassStub stub) { @NotNull public PyClassStub createStub(@NotNull final PyClass psi, final StubElement parentStub) { - final Map superClasses = getSuperClassQNames(psi); - final PyStringLiteralExpression docStringExpression = psi.getDocStringExpression(); - return new PyClassStubImpl(psi.getName(), parentStub, - superClasses, + return new PyClassStubImpl(psi.getName(), + parentStub, + getSuperClassQNames(psi), PyPsiUtils.asQualifiedName(psi.getMetaClassExpression()), psi.getOwnSlots(), - PyPsiUtils.strValue(docStringExpression), + PyPsiUtils.strValue(psi.getDocStringExpression()), getStubElementType()); } @@ -111,31 +110,40 @@ private static QualifiedName resolveOriginalSuperClassQName(@NotNull PyExpressio public void serialize(@NotNull final PyClassStub pyClassStub, @NotNull final StubOutputStream dataStream) throws IOException { dataStream.writeName(pyClassStub.getName()); + final Map superClasses = pyClassStub.getSuperClasses(); dataStream.writeByte(superClasses.size()); for (Map.Entry entry : superClasses.entrySet()) { QualifiedName.serialize(entry.getKey(), dataStream); QualifiedName.serialize(entry.getValue(), dataStream); } + QualifiedName.serialize(pyClassStub.getMetaClass(), dataStream); + PyFileElementType.writeNullableList(dataStream, pyClassStub.getSlots()); + final String docString = pyClassStub.getDocString(); dataStream.writeUTFFast(docString != null ? docString : ""); } @NotNull public PyClassStub deserialize(@NotNull final StubInputStream dataStream, final StubElement parentStub) throws IOException { - String name = StringRef.toString(dataStream.readName()); - int superClassCount = dataStream.readByte(); - Map superClasses = new LinkedHashMap<>(); + final String name = StringRef.toString(dataStream.readName()); + + final int superClassCount = dataStream.readByte(); + final Map superClasses = new LinkedHashMap<>(); for (int i = 0; i < superClassCount; i++) { superClasses.put(QualifiedName.deserialize(dataStream), QualifiedName.deserialize(dataStream)); } + final QualifiedName metaClass = QualifiedName.deserialize(dataStream); - List slots = PyFileElementType.readNullableList(dataStream); - final String docString = dataStream.readUTFFast(); - return new PyClassStubImpl(name, parentStub, superClasses, metaClass, slots, docString.length() > 0 ? docString : null, - getStubElementType()); + + final List slots = PyFileElementType.readNullableList(dataStream); + + final String docStringInStub = dataStream.readUTFFast(); + final String docString = docStringInStub.length() > 0 ? docStringInStub : null; + + return new PyClassStubImpl(name, parentStub, superClasses, metaClass, slots, docString, getStubElementType()); } public void indexStub(@NotNull final PyClassStub stub, @NotNull final IndexSink sink) { @@ -144,18 +152,17 @@ public void indexStub(@NotNull final PyClassStub stub, @NotNull final IndexSink sink.occurrence(PyClassNameIndex.KEY, name); sink.occurrence(PyClassNameIndexInsensitive.KEY, name.toLowerCase()); } - final PyClass pyClass = createPsi(stub); - for (String attribute : PyClassAttributesIndex.getAllDeclaredAttributeNames(pyClass)) { + + for (String attribute : PyClassAttributesIndex.getAllDeclaredAttributeNames(createPsi(stub))) { sink.occurrence(PyClassAttributesIndex.KEY, attribute); } - for (QualifiedName s : stub.getSuperClasses().values()) { - if (s != null) { - String className = s.getLastComponent(); - if (className != null) { - sink.occurrence(PySuperClassIndex.KEY, className); - } - } - } + + stub.getSuperClasses().values() + .stream() + .filter(Objects::nonNull) + .map(QualifiedName::getLastComponent) + .filter(Objects::nonNull) + .forEach(className -> sink.occurrence(PySuperClassIndex.KEY, className)); } protected IStubElementType getStubElementType() { From 55f643f377784125d3a6f2985b2819ba992b3aa6 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 15:46:36 +0300 Subject: [PATCH 57/67] NotNull annotation for PyClassElementType.getStubElementType --- .../com/jetbrains/python/psi/impl/stubs/PyClassElementType.java | 1 + 1 file changed, 1 insertion(+) diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index 1af45bfaa06ea..89660de4ef341 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -165,6 +165,7 @@ public void indexStub(@NotNull final PyClassStub stub, @NotNull final IndexSink .forEach(className -> sink.occurrence(PySuperClassIndex.KEY, className)); } + @NotNull protected IStubElementType getStubElementType() { return PyElementTypes.CLASS_DECLARATION; } From 8dbf66d862f311b1962e22ce1217ce59a127372f Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 17:26:21 +0300 Subject: [PATCH 58/67] Introduce PyResolveUtil.resolveLocally methods to resolve references and names in current file --- .../DeclarationConflictChecker.java | 9 ++-- .../python/psi/impl/PropertyBunch.java | 48 ++++++------------- .../psi/impl/stubs/PyClassElementType.java | 7 +-- .../psi/impl/stubs/PyNamedTupleStubImpl.java | 22 ++------- .../python/psi/resolve/PyResolveUtil.java | 27 ++++++++++- 5 files changed, 48 insertions(+), 65 deletions(-) diff --git a/python/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java b/python/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java index 4b75dd59f1cda..6ecfe917f03b4 100644 --- a/python/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java +++ b/python/src/com/jetbrains/python/codeInsight/intentions/DeclarationConflictChecker.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,7 +26,6 @@ import com.jetbrains.python.PyBundle; import com.jetbrains.python.codeInsight.controlflow.ScopeOwner; import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; -import com.jetbrains.python.psi.resolve.PyResolveProcessor; import com.jetbrains.python.psi.resolve.PyResolveUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -56,14 +55,12 @@ private DeclarationConflictChecker() { /* Don't instantiate */ } public static List> findDefinitions(@NotNull String name, @NotNull Collection references, @NotNull Set ignored) { - List> conflicts = new ArrayList>(); + final List> conflicts = new ArrayList>(); for (PsiReference ref : references) { final PsiElement refElement = ref.getElement(); final ScopeOwner owner = ScopeUtil.getScopeOwner(refElement); - final PyResolveProcessor processor = new PyResolveProcessor(name, true); if (owner != null) { - PyResolveUtil.scopeCrawlUp(processor, owner, name, null); - for (PsiElement element : processor.getElements()) { + for (PsiElement element : PyResolveUtil.resolveLocally(owner, name)) { if (!ignored.contains(element)) { conflicts.add(Pair.create(refElement, element)); } diff --git a/python/src/com/jetbrains/python/psi/impl/PropertyBunch.java b/python/src/com/jetbrains/python/psi/impl/PropertyBunch.java index 88c4e65cbf747..27bae00c71c32 100644 --- a/python/src/com/jetbrains/python/psi/impl/PropertyBunch.java +++ b/python/src/com/jetbrains/python/psi/impl/PropertyBunch.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -15,17 +15,17 @@ */ package com.jetbrains.python.psi.impl; -import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.util.ArrayUtil; import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.*; -import com.jetbrains.python.psi.resolve.PyResolveProcessor; import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.toolbox.Maybe; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Objects; + /** * Something that describes a property, with all related accessors. *
@@ -72,48 +72,28 @@ public String getDoc() { public static PyCallExpression findPropertyCallSite(@Nullable PyExpression source) { if (source instanceof PyCallExpression) { final PyCallExpression call = (PyCallExpression)source; - PyExpression callee = call.getCallee(); + final PyExpression callee = call.getCallee(); if (callee instanceof PyReferenceExpression) { - PyReferenceExpression ref = (PyReferenceExpression)callee; - if (ref.isQualified()) return null; - if (PyNames.PROPERTY.equals(callee.getName())) { - PsiFile file = source.getContainingFile(); - if (isBuiltinFile(file) || !resolvesLocally(ref)) { - // we assume that a non-local name 'property' is a built-in name. - // ref.resolve() is not used because we run in stub building phase where resolve() is frowned upon. - // NOTE: this logic fails if (quite unusually) name 'property' is directly imported from builtins. - return call; - } + final PyReferenceExpression ref = (PyReferenceExpression)callee; + + if (!ref.isQualified() && + PyNames.PROPERTY.equals(callee.getName()) && + (isBuiltinFile(source.getContainingFile()) || PyResolveUtil.resolveLocally(ref).stream().allMatch(Objects::isNull))) { + // we assume that a non-local name 'property' is a built-in name. + // ref.resolve() is not used because we run in stub building phase where resolve() is frowned upon. + // NOTE: this logic fails if (quite unusually) name 'property' is directly imported from builtins. + return call; } } } return null; } - private static boolean isBuiltinFile(PsiFile file) { + private static boolean isBuiltinFile(@NotNull PsiFile file) { final String name = file.getName(); return PyBuiltinCache.BUILTIN_FILE.equals(name) || PyBuiltinCache.BUILTIN_FILE_3K.equals(name); } - /** - * Resolve in containing file only. - * @param ref what to resolve - * @return true iff ref obviously resolves to a local name (maybe partially, e.g. via import). - */ - protected static boolean resolvesLocally(@NotNull PyReferenceExpression ref) { - final String name = ref.getName(); - if (name != null) { - final PyResolveProcessor processor = new PyResolveProcessor(name, true); - PyResolveUtil.scopeCrawlUp(processor, ref, name, null); - for (PsiElement element : processor.getElements()) { - if (element != null) { - return true; - } - } - } - return false; - } - /** * Tries to form a bunch from data available at a possible property() call site. * @param source should be a PyCallExpression (if not, null is immediately returned). diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java index 89660de4ef341..fcf5a6d083b90 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassElementType.java @@ -24,7 +24,6 @@ import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyClassImpl; import com.jetbrains.python.psi.impl.PyPsiUtils; -import com.jetbrains.python.psi.resolve.PyResolveProcessor; import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.psi.stubs.*; import org.jetbrains.annotations.NonNls; @@ -90,10 +89,8 @@ private static QualifiedName resolveOriginalSuperClassQName(@NotNull PyExpressio return PyPsiUtils.asQualifiedName(superClassExpression); } - final PyResolveProcessor processor = new PyResolveProcessor(referenceName, true); - PyResolveUtil.scopeCrawlUp(processor, reference, referenceName, null); - - final Optional qualifiedName = processor.getElements().stream() + final Optional qualifiedName = PyResolveUtil.resolveLocally(reference) + .stream() .filter(PyImportElement.class::isInstance) .map(PyImportElement.class::cast) .filter(element -> element.getAsName() != null) diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedTupleStubImpl.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedTupleStubImpl.java index 9e1398e1dd5bd..bf8833d4bcd8e 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedTupleStubImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyNamedTupleStubImpl.java @@ -24,7 +24,6 @@ import com.jetbrains.python.PyNames; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.PyPsiUtils; -import com.jetbrains.python.psi.resolve.PyResolveProcessor; import com.jetbrains.python.psi.resolve.PyResolveUtil; import com.jetbrains.python.psi.stubs.PyNamedTupleStub; import org.jetbrains.annotations.NotNull; @@ -32,7 +31,6 @@ import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.List; @@ -250,7 +248,7 @@ private static QualifiedName getImportedNamedTupleQName(@NotNull PyReferenceExpr // from collections import namedtuple as NT // Point = NT(...) - for (PsiElement element : resolveLocally(referenceExpression)) { + for (PsiElement element : PyResolveUtil.resolveLocally(referenceExpression)) { if (element instanceof PyImportElement) { final PyImportElement importElement = (PyImportElement)element; @@ -272,7 +270,7 @@ private static QualifiedName getImportedNamedTupleQName(@NotNull PyReferenceExpr } private static boolean resolvesToCollections(@NotNull PyReferenceExpression referenceExpression) { - for (PsiElement element : resolveLocally(referenceExpression)) { + for (PsiElement element : PyResolveUtil.resolveLocally(referenceExpression)) { if (element instanceof PyImportElement) { final PyImportElement importElement = (PyImportElement)element; @@ -285,27 +283,13 @@ private static boolean resolvesToCollections(@NotNull PyReferenceExpression refe return false; } - @NotNull - private static Collection resolveLocally(@NotNull PyReferenceExpression referenceExpression) { - final String referenceName = referenceExpression.getName(); - - if (referenceName == null) { - return Collections.emptyList(); - } - - final PyResolveProcessor processor = new PyResolveProcessor(referenceName, true); - PyResolveUtil.scopeCrawlUp(processor, referenceExpression, referenceName, null); - - return processor.getElements(); - } - private static boolean equals(@Nullable QualifiedName qualifiedName, @NotNull String name) { return qualifiedName != null && name.equals(qualifiedName.toString()); } @Nullable private static PyExpression fullResolveLocally(@NotNull PyReferenceExpression referenceExpression) { - for (PsiElement element : resolveLocally(referenceExpression)) { + for (PsiElement element : PyResolveUtil.resolveLocally(referenceExpression)) { if (element instanceof PyTargetExpression) { final PyExpression assignedValue = ((PyTargetExpression)element).findAssignedValue(); diff --git a/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java b/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java index a8e81ce77be17..f5e3f95363c66 100644 --- a/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java +++ b/python/src/com/jetbrains/python/psi/resolve/PyResolveUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -28,6 +28,9 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Collection; +import java.util.Collections; + /** * @author vlan * @@ -100,4 +103,26 @@ public static void scopeCrawlUp(@NotNull PsiScopeProcessor processor, @Nullable scopeOwner = ScopeUtil.getScopeOwner(scopeOwner); } } + + @NotNull + public static Collection resolveLocally(@NotNull PyReferenceExpression referenceExpression) { + final String referenceName = referenceExpression.getName(); + + if (referenceName == null) { + return Collections.emptyList(); + } + + final PyResolveProcessor processor = new PyResolveProcessor(referenceName, true); + scopeCrawlUp(processor, referenceExpression, referenceName, null); + + return processor.getElements(); + } + + @NotNull + public static Collection resolveLocally(@NotNull ScopeOwner scopeOwner, @NotNull String name) { + final PyResolveProcessor processor = new PyResolveProcessor(name, true); + scopeCrawlUp(processor, scopeOwner, name, null); + + return processor.getElements(); + } } From f70d284f9a9f690a1a6840368c291bab53a1fa81 Mon Sep 17 00:00:00 2001 From: Semyon Proshev Date: Fri, 15 Jul 2016 17:33:51 +0300 Subject: [PATCH 59/67] Specify nullability annotations in PyClassStub and PyClassStubImpl --- .../python/psi/stubs/PyClassStub.java | 11 +++++++- .../psi/impl/stubs/PyClassStubImpl.java | 26 ++++++++++++++++--- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java b/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java index b14307af1cd10..49935b62b20fd 100644 --- a/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java +++ b/python/psi-api/src/com/jetbrains/python/psi/stubs/PyClassStub.java @@ -22,17 +22,26 @@ import com.intellij.psi.stubs.NamedStub; import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.PyClass; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Map; public interface PyClassStub extends NamedStub { + /** * @return a {@code Map} which contains imported class names as keys and their original names as values */ + @NotNull Map getSuperClasses(); - @Nullable QualifiedName getMetaClass(); + + @Nullable + QualifiedName getMetaClass(); + + @Nullable List getSlots(); + + @Nullable String getDocString(); } \ No newline at end of file diff --git a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java index 934db36edb906..5a8e4d413ddec 100644 --- a/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java +++ b/python/src/com/jetbrains/python/psi/impl/stubs/PyClassStubImpl.java @@ -21,6 +21,7 @@ import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.stubs.PyClassStub; +import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; @@ -30,14 +31,29 @@ * @author max */ public class PyClassStubImpl extends StubBase implements PyClassStub { + + @Nullable private final String myName; + + @NotNull private final Map mySuperClasses; - @Nullable private final QualifiedName myMetaClass; + + @Nullable + private final QualifiedName myMetaClass; + + @Nullable private final List mySlots; + + @Nullable private final String myDocString; - public PyClassStubImpl(final String name, StubElement parentStub, final Map superClasses, - @Nullable QualifiedName metaClass, final List slots, String docString, IStubElementType stubElementType) { + public PyClassStubImpl(@Nullable String name, + @Nullable StubElement parentStub, + @NotNull Map superClasses, + @Nullable QualifiedName metaClass, + @Nullable List slots, + @Nullable String docString, + @NotNull IStubElementType stubElementType) { super(parentStub, stubElementType); myName = name; mySuperClasses = superClasses; @@ -46,10 +62,12 @@ public PyClassStubImpl(final String name, StubElement parentStub, final Map getSuperClasses() { return mySuperClasses; } @@ -60,11 +78,13 @@ public QualifiedName getMetaClass() { return myMetaClass; } + @Nullable @Override public List getSlots() { return mySlots; } + @Nullable @Override public String getDocString() { return myDocString; From 5f7f217b922e5a3936afca1258b9954d4a41872c Mon Sep 17 00:00:00 2001 From: Julia Beliaeva Date: Wed, 20 Jul 2016 21:27:11 +0300 Subject: [PATCH 60/67] [vcs-log] get log provider for correct ref in comparator --- .../src/com/intellij/vcs/log/impl/VcsGoToRefComparator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsGoToRefComparator.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsGoToRefComparator.java index 1981806fab691..69106b5a5b1b5 100644 --- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsGoToRefComparator.java +++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsGoToRefComparator.java @@ -33,7 +33,7 @@ public VcsGoToRefComparator(@NotNull Map providers) @Override public int compare(@NotNull VcsRef ref1, @NotNull VcsRef ref2) { VcsLogProvider provider1 = myProviders.get(ref1.getRoot()); - VcsLogProvider provider2 = myProviders.get(ref1.getRoot()); + VcsLogProvider provider2 = myProviders.get(ref2.getRoot()); if (provider1 == null) return provider2 == null ? ref1.getName().compareTo(ref2.getName()) : 1; if (provider2 == null) return -1; From ad86a5171df4892a494e57ea2328be6ad8abd7a2 Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Wed, 20 Jul 2016 19:47:43 +0200 Subject: [PATCH 61/67] introduce variable: suggest upper bound of captured wildcard --- java/java-psi-api/src/com/intellij/psi/GenericsUtil.java | 2 +- .../CapturedWildcardUpperBoundSuggestedAsType.after.java | 9 +++++++++ .../CapturedWildcardUpperBoundSuggestedAsType.java | 9 +++++++++ .../com/intellij/refactoring/IntroduceVariableTest.java | 4 ++++ 4 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.after.java create mode 100644 java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.java diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java index 7adbeea3435b4..45605b6c727df 100644 --- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java +++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java @@ -298,7 +298,7 @@ public static PsiType getVariableTypeByExpressionType(@Nullable PsiType type) { public static PsiType getVariableTypeByExpressionType(@Nullable PsiType type, final boolean openCaptured) { if (type == null) return null; if (type instanceof PsiCapturedWildcardType) { - type = ((PsiCapturedWildcardType)type).getWildcard(); + type = ((PsiCapturedWildcardType)type).getUpperBound(); } PsiType transformed = type.accept(new PsiTypeVisitor() { @Override diff --git a/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.after.java b/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.after.java new file mode 100644 index 0000000000000..af406f7750a73 --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.after.java @@ -0,0 +1,9 @@ +interface I {} + +abstract class Test { + void foo(Test t) { + I m = t.get(); + } + + abstract T get(); +} \ No newline at end of file diff --git a/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.java b/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.java new file mode 100644 index 0000000000000..ee03c88653bc3 --- /dev/null +++ b/java/java-tests/testData/refactoring/introduceVariable/CapturedWildcardUpperBoundSuggestedAsType.java @@ -0,0 +1,9 @@ +interface I {} + +abstract class Test { + void foo(Test t) { + t.get() + } + + abstract T get(); +} \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java index fbe86084b54aa..56034a69ca869 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java @@ -520,6 +520,10 @@ public void testDenotableType3() { doTest(new MockIntroduceVariableHandler("m", false, false, false, "java.util.function.IntFunction[]>")); } + public void testCapturedWildcardUpperBoundSuggestedAsType() throws Exception { + doTest(new MockIntroduceVariableHandler("m", false, false, false, "I")); + } + public void testReturnNonExportedArray() { doTest(new MockIntroduceVariableHandler("i", false, false, false, "java.io.File[]") { @Override From f426e0eeb84aa5ee931dbc1770a4a7fa2b7ed30d Mon Sep 17 00:00:00 2001 From: "Anna.Kozlova" Date: Wed, 20 Jul 2016 19:48:27 +0200 Subject: [PATCH 62/67] junit: reject tests without method name during building of a tree (IDEA-158727) --- .../junit/JUnitTreeByDescriptionHierarchyTest.java | 1 - .../src/com/intellij/junit4/JUnit4TestListener.java | 10 ++++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/plugins/junit/test/com/intellij/execution/junit/JUnitTreeByDescriptionHierarchyTest.java b/plugins/junit/test/com/intellij/execution/junit/JUnitTreeByDescriptionHierarchyTest.java index aa3aa51e2a214..46830d4c87612 100644 --- a/plugins/junit/test/com/intellij/execution/junit/JUnitTreeByDescriptionHierarchyTest.java +++ b/plugins/junit/test/com/intellij/execution/junit/JUnitTreeByDescriptionHierarchyTest.java @@ -34,7 +34,6 @@ public class JUnitTreeByDescriptionHierarchyTest { @Test public void testEmptySuite() throws Exception { doTest(Description.createSuiteDescription("empty suite"), "##teamcity[enteredTheMatrix]\n" + - "##teamcity[suiteTreeNode name='empty suite' locationHint='java:test://empty suite.empty suite']\n" + "##teamcity[treeEnded]\n"); } diff --git a/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestListener.java b/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestListener.java index 0f668d99287d8..aa5ff995547d5 100644 --- a/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestListener.java +++ b/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestListener.java @@ -306,6 +306,12 @@ private String getFullMethodName(Description description) { } private String getFullMethodName(Description description, Description parent) { + return getFullMethodName(description, parent, false); + } + + private String getFullMethodName(Description description, + Description parent, + boolean acceptNull) { String methodName = (String)myMethodNames.get(description); if (methodName == null) { methodName = JUnit4ReflectionUtil.getMethodName(description); @@ -313,7 +319,7 @@ private String getFullMethodName(Description description, Description parent) { methodName = getShortName(JUnit4ReflectionUtil.getClassName(description)) + "." + methodName; } - if (methodName == null && description.getChildren().isEmpty()) { + if (!acceptNull && methodName == null && description.getChildren().isEmpty()) { methodName = getShortName(description.getDisplayName()); } @@ -463,7 +469,7 @@ private void sendTree(Description description, Description parent, List currentP String className = JUnit4ReflectionUtil.getClassName(description); if (description.isTest()) { - final String methodName = getFullMethodName((Description)description, parent); + final String methodName = getFullMethodName((Description)description, parent, true); if (methodName != null ) { if (isWarning(methodName, className) && parent != null) { className = JUnit4ReflectionUtil.getClassName(parent); From f0c47e9843539c1d1d25316e71fdeb9368cb511c Mon Sep 17 00:00:00 2001 From: Roman Shevchenko Date: Wed, 20 Jul 2016 20:44:26 +0200 Subject: [PATCH 63/67] [platform] update compatibility info in the dialog (IDEA-CR-12398) --- .../updateSettings/impl/UpdateInfoDialog.java | 27 ++++++++++--------- .../src/com/intellij/ui/LicensingFacade.java | 6 +++-- .../src/messages/IdeBundle.properties | 1 - 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java index 01108c389304e..a33d4277f0f94 100644 --- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java +++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java @@ -92,18 +92,21 @@ private void initLicensingInfo(@NotNull UpdateChannel channel, @NotNull BuildInf else { Date buildDate = build.getReleaseDate(); if (buildDate != null) { - if (!facade.isApplicableForProduct(buildDate)) { - myLicenseInfo = IdeBundle.message("updates.paid.upgrade", channel.getEvalDays()); - myLicenseInfoColor = JBColor.RED; - } - else if (facade.isPerpetualForProduct(buildDate)) { - myLicenseInfo = IdeBundle.message("updates.fallback.build"); - } - else { - Date expiration = facade.getLicenseExpirationDate(); - myLicenseInfo = expiration != null - ? IdeBundle.message("updates.interim.build", DateFormatUtil.formatAboutDialogDate(expiration)) - : IdeBundle.message("updates.interim.build.endless"); + Boolean applicable = facade.isApplicableForProduct(buildDate); + if (applicable != null) { + if (applicable == Boolean.FALSE) { + myLicenseInfo = IdeBundle.message("updates.paid.upgrade", channel.getEvalDays()); + myLicenseInfoColor = JBColor.RED; + } + else if (facade.isPerpetualForProduct(buildDate) == Boolean.TRUE) { + myLicenseInfo = IdeBundle.message("updates.fallback.build"); + } + else { + Date expiration = facade.getLicenseExpirationDate(); + if (expiration != null) { + myLicenseInfo = IdeBundle.message("updates.interim.build", DateFormatUtil.formatAboutDialogDate(expiration)); + } + } } } } diff --git a/platform/platform-impl/src/com/intellij/ui/LicensingFacade.java b/platform/platform-impl/src/com/intellij/ui/LicensingFacade.java index 377dd050371f8..c9f4e29f8ed17 100644 --- a/platform/platform-impl/src/com/intellij/ui/LicensingFacade.java +++ b/platform/platform-impl/src/com/intellij/ui/LicensingFacade.java @@ -38,9 +38,11 @@ public static LicensingFacade getInstance() { public abstract boolean isEvaluationLicense(); - public abstract boolean isApplicableForProduct(@NotNull Date productBuildDate); + @Nullable + public abstract Boolean isApplicableForProduct(@NotNull Date productBuildDate); - public abstract boolean isPerpetualForProduct(@NotNull Date productBuildDate); + @Nullable + public abstract Boolean isPerpetualForProduct(@NotNull Date productBuildDate); @Nullable public abstract Date getLicenseExpirationDate(); diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties index 7377f305ada4f..c8cd453903a96 100644 --- a/platform/platform-resources-en/src/messages/IdeBundle.properties +++ b/platform/platform-resources-en/src/messages/IdeBundle.properties @@ -916,7 +916,6 @@ updates.channel.bundled.key=The new version has an expiration date and does not updates.paid.upgrade=You can evaluate the new version for {0} days, or buy an upgrade online. updates.fallback.build=You have perpetual fallback license for the new version. updates.interim.build=You can use the new version until your subscription expires on {0}. -updates.interim.build.endless=You can use the new version until your subscription expires. updates.ready.message={0} is ready to update. updates.external.progress=Fetching available updates for external components updates.external.ready.message=The following component{0,choice,1# is|2#s are} ready to update: {1} From fbcc86cb081a17c86a3cfa09f5e6edd57fad87a4 Mon Sep 17 00:00:00 2001 From: Sergey Malenkov Date: Wed, 20 Jul 2016 22:10:56 +0300 Subject: [PATCH 64/67] IDEA-97406 do not clip a dotted line in the middle of a dot --- .../src/com/intellij/ui/paint/EffectPainter.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java b/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java index fa5263309fc11..5205f80d00bab 100644 --- a/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java +++ b/platform/platform-api/src/com/intellij/ui/paint/EffectPainter.java @@ -181,7 +181,10 @@ private static void drawLineCentered(Graphics2D g, int x, int y, int width, int height = thickness; } if (painter == BOLD_DOTTED_UNDERSCORE) { - Cached.BOLD_DOTTED_UNDERSCORE.paint(g, x, y, width, height, null); + int dx = (x % height + height) % height; + int w = width + dx; + int dw = (w % height + height) % height; + Cached.BOLD_DOTTED_UNDERSCORE.paint(g, x - dx, y, dw == 0 ? w : w - dw + height, height, null); } else { g.fillRect(x, y, width, height); From f3a0086e894b9940f728b7dc1a202b65d95a090a Mon Sep 17 00:00:00 2001 From: Dmitry Batkovich Date: Wed, 20 Jul 2016 22:26:50 +0300 Subject: [PATCH 65/67] inspection view: show diff --- .../intellij/codeInspection/ui/InspectionResultsView.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java index d72acb790b4eb..67f475395d75d 100644 --- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java +++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsView.java @@ -605,7 +605,9 @@ private Pair createBaseRightComponentFor(int problemCount, DiffUtil.setFoldingModelSupport(myPreviewEditor); final EditorSettings settings = myPreviewEditor.getSettings(); settings.setLineNumbersShown(false); - settings.setLineMarkerAreaShown(false); + settings.setFoldingOutlineShown(true); + settings.setLineMarkerAreaShown(true); + settings.setGutterIconsShown(false); settings.setAdditionalColumnsCount(0); settings.setAdditionalLinesCount(0); settings.setLeadingWhitespaceShown(true); @@ -615,7 +617,6 @@ private Pair createBaseRightComponentFor(int problemCount, if (problemCount == 0) { myPreviewEditor.getScrollingModel().scrollTo(myPreviewEditor.offsetToLogicalPosition(selectedElement.getTextOffset()), ScrollType.CENTER_UP); } - myPreviewEditor.getSettings().setFoldingOutlineShown(problemCount > 1); myPreviewEditor.getComponent().setBorder(IdeBorderFactory.createEmptyBorder()); return Pair.create(myPreviewEditor.getComponent(), myPreviewEditor); } From 0b0c72d0e451a3bb80e328b0b1a9fec0475d99b2 Mon Sep 17 00:00:00 2001 From: Sergey Simonchik Date: Thu, 21 Jul 2016 00:35:52 +0300 Subject: [PATCH 66/67] mark NodeJS 163.1699 as broken --- platform/platform-resources/src/brokenPlugins.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/platform/platform-resources/src/brokenPlugins.txt b/platform/platform-resources/src/brokenPlugins.txt index 8b29d64ddb4f5..2b26111628ccd 100644 --- a/platform/platform-resources/src/brokenPlugins.txt +++ b/platform/platform-resources/src/brokenPlugins.txt @@ -1,7 +1,7 @@ // This file contains list of broken plugins. // Each line contains plugin ID and list of versions that are broken. // If plugin name or version contains a space you can quote it like in command line. -NodeJS 163.1616 163.1479 163.1374.5 163.1105 163.1059 163.607 163.198 144.2986 144.2925.4 144.2911 144.2562 144.2131 144.988 143.1138 143.1088 143.769 143.751 143.516 143.381.8 143.380.6 143.381.11 143.380.8 143.444 143.379.15 143.21 143.110 143.250 142.4426 142.4100 142.3858 142.3224 142.2650 142.2492 142.2481 142.2064 141.1108 140.2045 140.1669 140.642 139.173 139.105 139.496 139.1 139.8 138.2196 138.2254 138.1684 138.1744 138.1879 138.2051 138.1367 138.1495 138.1189 138.1145 138.937 138.1013 138.921 138.447 138.172 138.317 138.21 138.35 138.96 138.85 136.1205 134.1276 134.1163 134.1145 134.1081 134.1039 134.985 134.680 134.31 134.307 134.262 134.198 134.125 136.1141 +NodeJS 163.1699 163.1616 163.1479 163.1374.5 163.1105 163.1059 163.607 163.198 144.2986 144.2925.4 144.2911 144.2562 144.2131 144.988 143.1138 143.1088 143.769 143.751 143.516 143.381.8 143.380.6 143.381.11 143.380.8 143.444 143.379.15 143.21 143.110 143.250 142.4426 142.4100 142.3858 142.3224 142.2650 142.2492 142.2481 142.2064 141.1108 140.2045 140.1669 140.642 139.173 139.105 139.496 139.1 139.8 138.2196 138.2254 138.1684 138.1744 138.1879 138.2051 138.1367 138.1495 138.1189 138.1145 138.937 138.1013 138.921 138.447 138.172 138.317 138.21 138.35 138.96 138.85 136.1205 134.1276 134.1163 134.1145 134.1081 134.1039 134.985 134.680 134.31 134.307 134.262 134.198 134.125 136.1141 com.jetbrains.php 145.258.2 144.4199.11 144.3891.12 144.3656 144.3168 143.790 143.1770 143.1184.87 143.382.38 143.279 143.381.48 143.129 142.5282 142.2716 142.3969 142.4491 140.2765 141.332 139.732 139.659 139.496 139.173 139.105 138.2502 138.2000.2262 138.1751 138.1806 138.1505 138.1161 138.826 136.1768 136.1672 134.1456 133.982 133.679 133.51 133.326 131.98 131.374 131.332 131.235 131.205 130.1639 130.1481 130.1176 129.91 129.814 129.672 129.362 127.67 127.100 126.334 123.66 122.875 121.62 121.390 121.215 121.12 com.intellij.phing 133.51 131.374 129.672 127.67 124.347 121.62 121.390 121.215 121.12 117.746 117.694 117.501 117.257 117.222 117.132 114.282 114.158 com.intellij.plugins.html.instantEditing 162.5 0.4.1 0.4 0.3.9 0.3.8 0.3.7 0.3.6 0.3.5 0.3.3 0.3.2 0.3.10 0.3.1 0.3 0.2.27 0.2.25 0.2.24 0.2.23 From e1d4d1acc4cc1545a6d7f3508d7a413a6aa6a0f7 Mon Sep 17 00:00:00 2001 From: Bas Leijdekkers Date: Thu, 21 Jul 2016 00:01:43 +0200 Subject: [PATCH 67/67] test profile for merged throwable not thrown inspections --- .../codeInspection/ex/InspectionProfileTest.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java index 85b9202d71fd2..f3ee0565b991a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -360,6 +360,18 @@ public void testDisabledUnusedDeclarationWithoutChanges() throws Exception { ""); } + public void testMergedThrowableNotThrownInspections() throws Exception { + checkMergedNoChanges("\n" + + " "); + checkMergedNoChanges("\n" + + " "); + } + public void testMergedMisspelledInspections() throws Exception { checkMergedNoChanges("\n" + "