Merge remote-tracking branch 'origin/master' into develar/is
authorVladimir Krivosheev <vladimir.krivosheev@jetbrains.com>
Wed, 20 Jul 2016 09:14:43 +0000 (11:14 +0200)
committerVladimir Krivosheev <vladimir.krivosheev@jetbrains.com>
Wed, 20 Jul 2016 09:14:43 +0000 (11:14 +0200)
# Conflicts:
# platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java

172 files changed:
bin/scripts/win/idea.bat
java/debugger/impl/src/com/intellij/debugger/engine/evaluation/expression/BoxingEvaluator.java
java/debugger/impl/src/com/intellij/debugger/jdi/MethodBytecodeUtil.java
java/debugger/impl/src/com/intellij/debugger/ui/tree/render/CachedEvaluator.java
java/debugger/openapi/src/com/intellij/debugger/engine/DebuggerUtils.java
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/ModuleHighlightUtil.java
java/java-analysis-impl/src/com/intellij/codeInspection/unusedSymbol/UnusedSymbolLocalInspectionBase.java
java/java-impl/src/com/intellij/codeInspection/deadCode/UnusedDeclarationInspectionMerger.java
java/java-impl/src/com/intellij/codeInspection/unusedParameters/UnusedParametersInspection.java
java/java-impl/src/com/intellij/psi/formatter/java/AbstractJavaBlock.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Imports.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/NameEnvironment.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/SerializedUnit.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/StubEnter.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/StubHierarchyConnector.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/StubHierarchyIndex.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/StubResolver.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Symbols.java
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Translator.java [deleted file]
java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/annotations.java
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionStub.java [moved from plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledCompareToInspection.java with 52% similarity]
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/JavaStubElementTypes.java
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/LambdaExpressionElementType.java [new file with mode: 0644]
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/MethodReferenceElementType.java [new file with mode: 0644]
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/hierarchy/IndexTree.java
java/java-psi-impl/src/com/intellij/psi/impl/source/JavaFileElementType.java
java/java-psi-impl/src/com/intellij/psi/impl/source/JavaLightStubBuilder.java
java/java-psi-impl/src/com/intellij/psi/impl/source/PsiClassImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaElementType.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLambdaExpressionImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiLiteralExpressionImpl.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java
java/java-tests/testData/inspection/unusedMethodParameter/suppressedParameter/src/Test.java
java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java.after [new file with mode: 0644]
java/java-tests/testSrc/com/intellij/codeInspection/ex/InspectionProfileTest.java
java/java-tests/testSrc/com/intellij/psi/JavaStubBuilderTest.java
java/java-tests/testSrc/com/intellij/psi/StubAstSwitchTest.groovy
java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java
java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java
platform/analysis-api/src/com/intellij/codeInspection/InspectionProfileEntry.java
platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java [new file with mode: 0644]
platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextBase.java
platform/analysis-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextUtil.java
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionElementsMergerBase.java [moved from platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java with 90% similarity]
platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionProfileImpl.java
platform/configuration-store-impl/src/ExportSettingsAction.kt
platform/configuration-store-impl/testSrc/DoNotStorePasswordTest.kt [new file with mode: 0644]
platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java
platform/core-api/src/com/intellij/psi/search/LocalSearchScope.java
platform/lang-impl/src/com/intellij/application/options/codeStyle/OptionTreeWithPreviewPanel.java
platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java
platform/lang-impl/src/com/intellij/codeInspection/export/ExportToHTMLDialog.java
platform/lang-impl/src/com/intellij/formatting/contextConfiguration/CodeFragmentCodeStyleSettingsPanel.java
platform/lang-impl/src/com/intellij/formatting/contextConfiguration/ConfigureCodeStyleOnSelectedFragment.java
platform/lang-impl/src/com/intellij/ide/bookmarks/Bookmark.java
platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/ExportableFileTemplateSettings.java
platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateManagerImpl.java
platform/lang-impl/src/com/intellij/ide/fileTemplates/impl/FileTemplateSettings.java
platform/lang-impl/src/com/intellij/ide/util/DeleteHandler.java
platform/lang-impl/src/com/intellij/ide/util/PsiElementModuleRenderer.java
platform/lang-impl/src/com/intellij/psi/codeStyle/CodeStyleSettingsCodeFragmentFilter.java
platform/lang-impl/src/com/intellij/psi/search/PredefinedSearchScopeProviderImpl.java
platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteDialog.java
platform/lang-impl/src/com/intellij/ui/tabs/FileColorsModel.java
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfo.kt
platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfoDialog.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java
platform/platform-impl/src/com/intellij/ui/LicensingFacade.java
platform/platform-resources-en/src/messages/IdeBundle.properties
platform/platform-resources/src/META-INF/LangExtensions.xml
platform/platform-resources/src/brokenPlugins.txt
platform/platform-tests/testSrc/com/intellij/history/integration/PatchingTestCase.java
platform/platform-tests/testSrc/com/intellij/history/integration/patches/PatchCreatorTest.java
platform/platform-tests/testSrc/com/intellij/history/integration/ui/DirectoryHistoryDialogPatchCreationTest.java
platform/platform-tests/testSrc/com/intellij/ide/fileTemplates/impl/LightFileTemplatesTest.java
platform/projectModel-api/src/com/intellij/openapi/roots/TestSourcesFilter.java
platform/util/src/com/intellij/util/containers/CharTrie.java
platform/util/src/com/intellij/util/io/PagedFileStorage.java
platform/util/src/com/intellij/util/ui/GraphicsUtil.java
platform/vcs-impl/src/com/intellij/openapi/diff/impl/patch/apply/GenericPatchApplier.java
platform/vcs-impl/src/com/intellij/openapi/vcs/VcsNotifier.java
platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogRefs.java
platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.java
platform/vcs-log/impl/src/com/intellij/vcs/log/data/RefsModel.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/CurrentBranchHighlighter.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/tables/GraphTableModel.java
platform/vcs-tests/src/com/intellij/openapi/vcs/TestVcsNotifier.java
platform/xdebugger-impl/src/com/intellij/xdebugger/attach/XLocalAttachDebuggerProvider.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledCompareToInspectionBase.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledHashcodeInspectionBase.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledToStringInspectionBase.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ThrowableNeverThrownInspectionMerger.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledSetUpInspectionBase.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledTearDownInspectionBase.java [deleted file]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/naming/MisspelledMethodNameInspectionBase.java [moved from plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/naming/MethodNamesDifferOnlyByCaseInspectionBase.java with 95% similarity]
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/naming/MisspelledMethodNameInspectionMerger.java [moved from plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledToStringInspection.java with 52% similarity]
plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledHashcodeInspection.java [deleted file]
plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledSetUpInspection.java [deleted file]
plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledTearDownInspection.java [deleted file]
plugins/InspectionGadgets/src/com/siyeh/ig/naming/MisspelledMethodNameInspection.java [moved from plugins/InspectionGadgets/src/com/siyeh/ig/naming/MethodNamesDifferOnlyByCaseInspection.java with 89% similarity]
plugins/InspectionGadgets/test/com/siyeh/igtest/naming/method_names_differ_only_by_case/MethodNamesDifferOnlyByCase.java
plugins/InspectionGadgets/testsrc/com/siyeh/ig/naming/MethodNamesDifferOnlyByCaseInspectionTest.java
plugins/git4idea/src/git4idea/branch/GitBranchIsNotFullyMergedDialog.java
plugins/git4idea/src/git4idea/branch/GitBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitBranchUiHandler.java
plugins/git4idea/src/git4idea/branch/GitBranchUiHandlerImpl.java
plugins/git4idea/src/git4idea/branch/GitBranchUtil.java
plugins/git4idea/src/git4idea/branch/GitBranchWorker.java
plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitMergeOperation.java
plugins/git4idea/src/git4idea/commands/Git.java
plugins/git4idea/src/git4idea/commands/GitImpl.java
plugins/git4idea/src/git4idea/config/GitVersionSpecialty.java
plugins/git4idea/src/git4idea/i18n/GitBundle.properties
plugins/git4idea/src/git4idea/repo/GitRepository.java
plugins/git4idea/src/git4idea/repo/GitRepositoryImpl.java
plugins/git4idea/src/git4idea/update/GitUpdateProcess.java
plugins/git4idea/tests/git4idea/branch/GitBranchWorkerTest.java [deleted file]
plugins/git4idea/tests/git4idea/branch/GitBranchWorkerTest.kt [new file with mode: 0644]
plugins/git4idea/tests/git4idea/rebase/GitMultiRepoRebaseTest.kt
plugins/git4idea/tests/git4idea/rebase/GitRebaseBaseTest.kt
plugins/git4idea/tests/git4idea/rebase/GitSingleRepoRebaseTest.kt
plugins/git4idea/tests/git4idea/test/GitPlatformTest.kt
plugins/git4idea/tests/git4idea/test/GitTestUtil.java
plugins/git4idea/tests/git4idea/test/MockGitRepository.java
plugins/git4idea/tests/git4idea/test/TestGit.kt
plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java
plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleManager.java
plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java [moved from plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleAsVirtualFile.java with 100% similarity]
plugins/properties/src/META-INF/plugin.xml
plugins/properties/src/com/intellij/lang/properties/customizeActions/CombinePropertiesFilesAction.java
plugins/properties/src/com/intellij/lang/properties/customizeActions/DissociateResourceBundleAction.java
plugins/properties/src/com/intellij/lang/properties/editor/GotoPropertyParentDeclarationHandler.java [new file with mode: 0644]
plugins/properties/src/com/intellij/lang/properties/editor/PropertiesCopyHandler.java
plugins/properties/src/com/intellij/lang/properties/editor/PropertiesInheritorsSearcher.java [new file with mode: 0644]
plugins/properties/src/com/intellij/lang/properties/editor/ResourceBundleEditorFileListener.java
plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleDeleteProvider.java
plugins/properties/src/com/intellij/lang/properties/projectView/ResourceBundleNode.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLBlockScalarImpl.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLPlainTextImpl.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLQuotedTextImpl.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLScalarImpl.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLScalarListImpl.java
plugins/yaml/src/org/jetbrains/yaml/psi/impl/YAMLScalarTextImpl.java
plugins/yaml/testSrc/org/jetbrains/yaml/psi/YAMLScalarContentTest.java
plugins/yaml/testSrc/org/jetbrains/yaml/psi/data/foldedStyle5.txt [new file with mode: 0644]
plugins/yaml/testSrc/org/jetbrains/yaml/psi/data/foldedStyle5.yml [new file with mode: 0644]
plugins/yaml/testSrc/org/jetbrains/yaml/psi/data/foldedStyle6.txt [new file with mode: 0644]
plugins/yaml/testSrc/org/jetbrains/yaml/psi/data/foldedStyle6.yml [new file with mode: 0644]
python/educational-core/course-creator/resources/META-INF/plugin.xml
python/educational-core/course-creator/src/com/jetbrains/edu/coursecreator/actions/CCPushTask.java [new file with mode: 0644]
python/educational-core/student/src/com/jetbrains/edu/learning/StudySerializationUtils.java
python/educational-core/student/src/com/jetbrains/edu/learning/checker/StudyCheckTask.java
python/educational-core/student/src/com/jetbrains/edu/learning/core/EduAnswerPlaceholderPainter.java
python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/AnswerPlaceholder.java
python/educational-core/student/src/com/jetbrains/edu/learning/courseFormat/Lesson.java
python/educational-core/student/src/com/jetbrains/edu/learning/courseGeneration/StudyProjectGenerator.java
python/educational-core/student/src/com/jetbrains/edu/learning/stepic/EduStepicConnector.java
python/ide/src/com/jetbrains/python/newProject/actions/PythonGenerateProjectCallback.java
python/testData/testRunner/env/unit/rerun_derived.py [new file with mode: 0644]
python/testSrc/com/jetbrains/env/python/testing/PyUnitTestProcessWithConsoleTestTask.java
python/testSrc/com/jetbrains/env/python/testing/PythonUnitTestingTest.java
xml/xml-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
xml/xml-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlUnusedNamespaceInspection.java
xml/xml-psi-impl/src/com/intellij/xml/DefaultXmlExtension.java
xml/xml-psi-impl/src/com/intellij/xml/XmlExtension.java

index 483f10f10a804d23c9965964109679a4ab6378ba..f5059ff959215a7980d7a479922b6a2cb59ad048 100644 (file)
@@ -15,34 +15,33 @@ SET IDE_HOME=%IDE_BIN_DIR%\..
 :: Try (in order): @@product_uc@@_JDK, @@vm_options@@.jdk, ..\jre, JDK_HOME, JAVA_HOME.
 :: ---------------------------------------------------------------------
 SET JDK=
-IF EXIST "%@@product_uc@@_JDK%" (
-  SET JDK=%@@product_uc@@_JDK%
-)
-IF "%JDK%" == "" (
-  SET BITS=64
-  SET USER_JDK64_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
-  SET BITS=
-  SET USER_JDK_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
-  IF EXIST "%USER_JDK64_FILE%" (
-    SET /P JDK=<%USER_JDK64_FILE%
-    IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
-  ) ELSE (
-    IF EXIST "%USER_JDK_FILE%" (
-      SET /P JDK=<%USER_JDK_FILE%
-      IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
-    )
-  )
-)
-IF "%JDK%" == "" (
-  IF EXIST "%IDE_HOME%\jre" SET JDK=%IDE_HOME%\jre
-)
-IF "%JDK%" == "" (
-  IF EXIST "%JDK_HOME%" SET JDK=%JDK_HOME%
+
+IF EXIST "%@@product_uc@@_JDK%" SET JDK=%@@product_uc@@_JDK%
+IF NOT "%JDK%" == "" GOTO check
+
+SET BITS=64
+SET USER_JDK64_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
+SET BITS=
+SET USER_JDK_FILE=%USERPROFILE%\.@@system_selector@@\config\@@vm_options@@.jdk
+IF EXIST "%USER_JDK64_FILE%" (
+  SET /P JDK=<%USER_JDK64_FILE%
+) ELSE (
+  IF EXIST "%USER_JDK_FILE%" SET /P JDK=<%USER_JDK_FILE%
 )
-IF "%JDK%" == "" (
-  IF EXIST "%JAVA_HOME%" SET JDK=%JAVA_HOME%
+IF NOT "%JDK%" == "" (
+  IF NOT EXIST "%JDK%" SET JDK=%IDE_HOME%\%JDK%
+  GOTO check
 )
 
+IF EXIST "%IDE_HOME%\jre" SET JDK=%IDE_HOME%\jre
+IF NOT "%JDK%" == "" GOTO check
+
+IF EXIST "%JDK_HOME%" SET JDK=%JDK_HOME%
+IF NOT "%JDK%" == "" GOTO check
+
+IF EXIST "%JAVA_HOME%" SET JDK=%JAVA_HOME%
+
+:check
 SET JAVA_EXE=%JDK%\bin\java.exe
 IF NOT EXIST "%JAVA_EXE%" SET JAVA_EXE=%JDK%\jre\bin\java.exe
 IF NOT EXIST "%JAVA_EXE%" (
index 1bcd93ef432f2da36c634445b6f9aa826b925748..c5eb7951615e6bba03027d6cfa07e9342065cce6 100644 (file)
@@ -19,9 +19,9 @@ import com.intellij.debugger.engine.DebugProcessImpl;
 import com.intellij.debugger.engine.JVMNameUtil;
 import com.intellij.debugger.engine.evaluation.EvaluateException;
 import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
-import com.intellij.psi.CommonClassNames;
+import com.intellij.psi.PsiPrimitiveType;
+import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
 import com.sun.jdi.*;
-import org.jetbrains.annotations.Nullable;
 
 import java.util.Collections;
 import java.util.List;
@@ -43,29 +43,12 @@ public class BoxingEvaluator implements Evaluator{
       return result;
     }
 
-    if (result instanceof BooleanValue) {
-      return convertToWrapper(context, (BooleanValue)result, CommonClassNames.JAVA_LANG_BOOLEAN);
-    }
-    if (result instanceof ByteValue) {
-      return convertToWrapper(context, (ByteValue)result, CommonClassNames.JAVA_LANG_BYTE);
-    }
-    if (result instanceof CharValue) {
-      return convertToWrapper(context, (CharValue)result, CommonClassNames.JAVA_LANG_CHARACTER);
-    }
-    if (result instanceof ShortValue) {
-      return convertToWrapper(context, (ShortValue)result, CommonClassNames.JAVA_LANG_SHORT);
-    }
-    if (result instanceof IntegerValue) {
-      return convertToWrapper(context, (IntegerValue)result, CommonClassNames.JAVA_LANG_INTEGER);
-    }
-    if (result instanceof LongValue) {
-      return convertToWrapper(context, (LongValue)result, CommonClassNames.JAVA_LANG_LONG);
-    }
-    if (result instanceof FloatValue) {
-      return convertToWrapper(context, (FloatValue)result, CommonClassNames.JAVA_LANG_FLOAT);
-    }
-    if (result instanceof DoubleValue) {
-      return convertToWrapper(context, (DoubleValue)result, CommonClassNames.JAVA_LANG_DOUBLE);
+    if (result instanceof PrimitiveValue) {
+      PrimitiveValue primitiveValue = (PrimitiveValue)result;
+      PsiPrimitiveType primitiveType = PsiJavaParserFacadeImpl.getPrimitiveType(primitiveValue.type().name());
+      if (primitiveType != null) {
+        return convertToWrapper(context, primitiveValue, primitiveType.getBoxedTypeName());
+      }
     }
     throw new EvaluateException("Cannot perform boxing conversion for a value of type " + ((Value)result).type().name());
   }
index c994079ed0d3b6a77b53e57817395b73215f3a39..d84212cfb06390f354a7559a795fa29d7c07a731 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.debugger.jdi;
 
+import com.intellij.util.ReflectionUtil;
 import com.intellij.util.ThrowableConsumer;
 import com.sun.jdi.*;
 import org.jetbrains.annotations.NotNull;
@@ -52,13 +53,23 @@ public class MethodBytecodeUtil {
     visit(classType, method, bytecodes, methodVisitor);
   }
 
+  public static byte[] getConstantPool(ReferenceType type) {
+    try {
+      return type.constantPool();
+    }
+    catch (NullPointerException e) { // workaround for JDK bug 6822627
+      ReflectionUtil.resetField(type, "constantPoolInfoGotten");
+      return type.constantPool();
+    }
+  }
+
   private static void visit(ReferenceType type, Method method, byte[] bytecodes, MethodVisitor methodVisitor) {
     try {
       try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(bos)) {
         dos.writeInt(0xCAFEBABE); // magic
         dos.writeInt(Opcodes.V1_8); // version
         dos.writeShort(type.constantPoolCount()); // constant_pool_count
-        dos.write(type.constantPool()); // constant_pool
+        dos.write(getConstantPool(type)); // constant_pool
         dos.writeShort(0); //             access_flags;
         dos.writeShort(0); //             this_class;
         dos.writeShort(0); //             super_class;
index c878a356dc0120b5114ae2cdcc0b3cd7527bd833..224e78431161ab74122d3942da4e8d278b1a7d8a 100644 (file)
@@ -20,6 +20,7 @@ import com.intellij.debugger.engine.evaluation.*;
 import com.intellij.debugger.engine.evaluation.expression.ExpressionEvaluator;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
+import com.intellij.psi.impl.PsiJavaParserFacadeImpl;
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.reference.SoftReference;
 import org.jetbrains.annotations.Nullable;
@@ -65,14 +66,24 @@ public abstract class CachedEvaluator {
   protected Cache initEvaluatorAndChildrenExpression(final Project project) {
     final Cache cache = new Cache();
     try {
-      PsiClass contextClass = DebuggerUtils.findClass(getClassName(), project, GlobalSearchScope.allScope(project));
-      if (contextClass instanceof PsiCompiledElement) {
-        contextClass = (PsiClass)((PsiCompiledElement)contextClass).getMirror();
+      String className = getClassName();
+      PsiClass contextClass;
+      PsiType contextType;
+      PsiPrimitiveType primitiveType = PsiJavaParserFacadeImpl.getPrimitiveType(className);
+      if (primitiveType != null) {
+        contextClass = JavaPsiFacade.getInstance(project).findClass(primitiveType.getBoxedTypeName(), GlobalSearchScope.allScope(project));
+        contextType = primitiveType;
       }
-      if(contextClass == null) {
-        throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS;
+      else {
+        contextClass = DebuggerUtils.findClass(className, project, GlobalSearchScope.allScope(project));
+        if (contextClass instanceof PsiCompiledElement) {
+          contextClass = (PsiClass)((PsiCompiledElement)contextClass).getMirror();
+        }
+        if (contextClass == null) {
+          throw EvaluateExceptionUtil.CANNOT_FIND_SOURCE_CLASS;
+        }
+        contextType = DebuggerUtils.getType(className, project);
       }
-      final PsiType contextType = DebuggerUtils.getType(getClassName(), project);
       cache.myPsiChildrenExpression = null;
       JavaCodeFragment codeFragment = myDefaultFragmentFactory.createCodeFragment(myReferenceExpression, contextClass, project);
       codeFragment.forceResolveScope(GlobalSearchScope.allScope(project));
index 9f3b1229aac834b6f4abf36e58372e6056ec4a8b..2f382f0ca80fd9f683213a7eed5ea0da04134784 100644 (file)
@@ -40,6 +40,7 @@ import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.ClassUtil;
 import com.intellij.psi.util.InheritanceUtil;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.PsiTypesUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.StringBuilderSpinAllocator;
 import com.intellij.util.containers.ContainerUtil;
@@ -266,10 +267,14 @@ public abstract class DebuggerUtils {
   }
 
   public static boolean instanceOf(@Nullable Type subType, @NotNull String superType) {
-    if (subType == null || subType instanceof PrimitiveType || subType instanceof VoidType) {
+    if (subType == null || subType instanceof VoidType) {
       return false;
     }
 
+    if (subType instanceof PrimitiveType) {
+      return superType.equals(subType.name());
+    }
+
     if (CommonClassNames.JAVA_LANG_OBJECT.equals(superType)) {
       return true;
     }
@@ -389,18 +394,16 @@ public abstract class DebuggerUtils {
   public static PsiType getType(@NotNull String className, @NotNull Project project) {
     ApplicationManager.getApplication().assertReadAccessAllowed();
 
-    final PsiManager psiManager = PsiManager.getInstance(project);
     try {
       if (getArrayClass(className) != null) {
-        return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createTypeFromText(className, null);
+        return JavaPsiFacade.getInstance(project).getElementFactory().createTypeFromText(className, null);
       }
-      if(project.isDefault()) {
+      if (project.isDefault()) {
         return null;
       }
-      final PsiClass aClass =
-        JavaPsiFacade.getInstance(psiManager.getProject()).findClass(className.replace('$', '.'), GlobalSearchScope.allScope(project));
+      PsiClass aClass = findClass(className, project, GlobalSearchScope.allScope(project));
       if (aClass != null) {
-        return JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory().createType(aClass);
+        return PsiTypesUtil.getClassType(aClass);
       }
     }
     catch (IncorrectOperationException e) {
index 13faebfeb79909fb959818e3d3180390006a0540..6d699ea589fc14f1adfe68b1c5ecc01589cd72d6 100644 (file)
@@ -24,6 +24,7 @@ import com.intellij.codeInsight.daemon.impl.quickfix.MoveFileFix;
 import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
 import com.intellij.codeInsight.intention.QuickFixFactory;
 import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.module.impl.scopes.ModulesScope;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectFileIndex;
@@ -75,21 +76,18 @@ public class ModuleHighlightUtil {
 
   @Nullable
   static HighlightInfo checkFileDuplicates(@NotNull PsiJavaModule element, @NotNull PsiFile file) {
-    VirtualFile vFile = file.getVirtualFile();
-    if (vFile != null) {
+    Module module = ModuleUtilCore.findModuleForPsiElement(element);
+    if (module != null) {
       Project project = file.getProject();
-      Module module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(vFile);
-      if (module != null) {
-        Collection<VirtualFile> others =
-          FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(Collections.singleton(module), project));
-        if (others.size() > 1) {
-          String message = JavaErrorMessages.message("module.file.duplicate");
-          HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range(element)).description(message).create();
-          others.stream().map(f -> PsiManager.getInstance(project).findFile(f)).filter(f -> f != file).findFirst().ifPresent(
-            duplicate -> QuickFixAction.registerQuickFixAction(info, new GoToSymbolFix(duplicate, JavaErrorMessages.message("module.open.duplicate.text")))
-          );
-          return info;
-        }
+      Collection<VirtualFile> others =
+        FilenameIndex.getVirtualFilesByName(project, MODULE_INFO_FILE, new ModulesScope(Collections.singleton(module), project));
+      if (others.size() > 1) {
+        String message = JavaErrorMessages.message("module.file.duplicate");
+        HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(range(element)).description(message).create();
+        others.stream().map(f -> PsiManager.getInstance(project).findFile(f)).filter(f -> f != file).findFirst().ifPresent(
+          duplicate -> QuickFixAction.registerQuickFixAction(info, new GoToSymbolFix(duplicate, JavaErrorMessages.message("module.open.duplicate.text")))
+        );
+        return info;
       }
     }
 
index f9525dc0a268390c56472fd8151111a39ac6cedc..f9f0e5e88008e5a893b69c997667431dc76ce8c2 100644 (file)
@@ -32,6 +32,7 @@ public class UnusedSymbolLocalInspectionBase extends BaseJavaLocalInspectionTool
   @NonNls public static final String SHORT_NAME = HighlightInfoType.UNUSED_SYMBOL_SHORT_NAME;
   @NonNls public static final String DISPLAY_NAME = HighlightInfoType.UNUSED_SYMBOL_DISPLAY_NAME;
   @NonNls public static final String UNUSED_PARAMETERS_SHORT_NAME = "UnusedParameters";
+  @NonNls public static final String UNUSED_ID = "unused";
 
   public boolean LOCAL_VARIABLE = true;
   public boolean FIELD = true;
@@ -126,7 +127,7 @@ public class UnusedSymbolLocalInspectionBase extends BaseJavaLocalInspectionTool
   @NotNull
   @NonNls
   public String getID() {
-    return "unused";
+    return UNUSED_ID;
   }
 
   @Override
index 5092410f419e55645261d35b220350593c96be2b..75be9546415beac8908ea421ae4965a3479bea65 100644 (file)
  */
 package com.intellij.codeInspection.deadCode;
 
-import com.intellij.codeInspection.ex.InspectionElementsMerger;
+import com.intellij.codeInspection.ex.InspectionElementsMergerBase;
 import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
 import com.intellij.openapi.util.WriteExternalException;
 import org.jdom.Element;
 
-public class UnusedDeclarationInspectionMerger extends InspectionElementsMerger {
+public class UnusedDeclarationInspectionMerger extends InspectionElementsMergerBase {
   private static final String UNUSED_SYMBOL = "UNUSED_SYMBOL";
   private static final String UNUSED_DECLARATION = "UnusedDeclaration";
 
index 6abd0970c83abc2545aab668a9da6e1726a6e87c..9ef81a97290408b065d0d0081564b1b2b1e21ea0 100644 (file)
@@ -193,7 +193,7 @@ public class UnusedParametersInspection extends GlobalJavaBatchInspectionTool {
     clearUsedParameters(refMethod, result, checkDeep);
 
     for (RefParameter parameter : result) {
-      if (parameter != null && !((RefElementImpl)parameter).isSuppressed(UnusedSymbolLocalInspectionBase.UNUSED_PARAMETERS_SHORT_NAME)) {
+      if (parameter != null && !((RefElementImpl)parameter).isSuppressed(UnusedSymbolLocalInspectionBase.UNUSED_PARAMETERS_SHORT_NAME, UnusedSymbolLocalInspectionBase.UNUSED_ID)) {
         res.add(parameter);
       }
     }
@@ -315,6 +315,6 @@ public class UnusedParametersInspection extends GlobalJavaBatchInspectionTool {
   @Nullable
   @Override
   public String getAlternativeID() {
-    return "unused";
+    return UnusedSymbolLocalInspectionBase.UNUSED_ID;
   }
 }
index 372aa1f881a32a8ee3321c19ca8e6335e14d89c5..a3f0c17d764ed635c9997364f7b2da6dccbdd99a 100644 (file)
@@ -301,9 +301,9 @@ public abstract class AbstractJavaBlock extends AbstractBlock implements JavaBlo
     if (parent != null) {
       final Indent defaultChildIndent = getChildIndent(parent, indentOptions);
       if (defaultChildIndent != null) return defaultChildIndent;
-    }
-    if (child.getTreeParent() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
-      return Indent.getNoneIndent();
+      if (parent.getPsi() instanceof PsiLambdaExpression && child instanceof PsiCodeBlock) {
+        return Indent.getNoneIndent();
+      }
     }
 
     return null;
index 639a8ea07db8f5603f5ecfae71e228eb87da2f5a..67210ee46d7a123929df9679faa76fa50487737b 100644 (file)
@@ -49,40 +49,28 @@ class Imports {
   }
 
   private static void writeImport(@NotNull DataOutput out, IndexTree.Import anImport) throws IOException {
-    SerializedUnit.writeQualifiedName(out, anImport.myFullname);
-    boolean hasAlias = anImport.myAlias != 0;
+    out.writeInt(NameEnvironment.fromString(anImport.myQualifier));
+    boolean hasAlias = anImport.myAlias != null;
     int flags = 0;
     flags = BitUtil.set(flags, IS_STATIC, anImport.myStaticImport);
     flags = BitUtil.set(flags, IS_ON_DEMAND, anImport.myOnDemand);
     flags = BitUtil.set(flags, HAS_ALIAS, hasAlias);
     out.writeByte(flags);
+    if (anImport.myImportedName != null) {
+      out.writeInt(NameEnvironment.hashIdentifier(anImport.myImportedName));
+    }
     if (hasAlias) {
-      out.writeInt(anImport.myAlias);
+      out.writeInt(NameEnvironment.hashIdentifier(anImport.myAlias));
     }
   }
 
   private Import readImport(UnitInputStream in) throws IOException {
-    int qualifier = 0;
-    int len = DataInputOutputUtil.readINT(in);
-    for (int i = 0; i < len - 1; i++) {
-      qualifier = in.names.qualifiedName(qualifier, in.readInt());
-    }
-    int lastId = in.readInt();
+    int qualifier = in.readInt();
     int flags = in.readByte();
+    int shortName = BitUtil.isSet(flags, IS_ON_DEMAND) ? 0 : in.readInt();
     int alias = BitUtil.isSet(flags, HAS_ALIAS) ? in.readInt() : 0;
 
-    boolean onDemand = BitUtil.isSet(flags, IS_ON_DEMAND);
-    boolean isStatic = BitUtil.isSet(flags, IS_STATIC);
-
-    int shortName;
-    if (onDemand) {
-      shortName = 0;
-      qualifier = in.names.qualifiedName(qualifier, lastId);
-    } else {
-      shortName = lastId;
-    }
-
-    return obtainImport(qualifier, shortName, alias, isStatic);
+    return obtainImport(qualifier, shortName, alias, BitUtil.isSet(flags, IS_STATIC));
   }
 
   private Import obtainImport(int qualifier, int shortName, int alias, boolean isStatic) {
index ab943317b08d97f629a50d546d0a7f7e4d89a6e3..e64a6d74f88caf6f45867075d825b9d3dfe50824 100644 (file)
 package com.intellij.psi.stubsHierarchy.impl;
 
 import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.CommonClassNames;
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-import com.intellij.util.io.DataInputOutputUtil;
+import com.intellij.psi.PsiNameHelper;
+import com.intellij.util.ArrayUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
+import java.util.List;
 
 class NameEnvironment extends UserDataHolderBase {
-  public static final int OBJECT_NAME = IndexTree.hashIdentifier("Object");
-  public static final int NO_NAME = 0;
-  @QNameHash final int java_lang;
-  public final QualifiedName java_lang_Enum;
-  public final QualifiedName java_lang_annotation_Annotation;
+  static final int OBJECT_NAME = hashIdentifier("Object");
+  static final int NO_NAME = 0;
+  @QNameHash final static int java_lang = fromString("java.lang");
+  static final QualifiedName java_lang_Enum = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ENUM));
+  static final QualifiedName java_lang_annotation_Annotation =
+    new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION));
 
-  NameEnvironment() {
-    java_lang = fromString("java.lang");
-    java_lang_Enum = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ENUM));
-    java_lang_annotation_Annotation = new QualifiedName.Interned(fromString(CommonClassNames.JAVA_LANG_ANNOTATION_ANNOTATION));
-  }
-
-  @QNameHash int fromString(String s) {
+  static @QNameHash int fromString(String s) {
     int id = 0;
-    for (int shortName : IndexTree.hashQualifiedName(s)) {
+    for (int shortName : hashQualifiedName(s)) {
       id = qualifiedName(id, shortName);
     }
     return id;
   }
 
-  /**
-   * @see SerializedUnit#writeQualifiedName(DataOutput, int[])
-   */
-  @QNameHash int readQualifiedName(DataInput in) throws IOException {
-    int id = 0;
-    int len = DataInputOutputUtil.readINT(in);
-    for (int i = 0; i < len; i++) {
-      id = qualifiedName(id, in.readInt());
+  static int hashIdentifier(@Nullable String s) {
+    if (StringUtil.isEmpty(s)) return 0;
+
+    // not using String.hashCode because this way there's less collisions for short package names like 'com'
+    int hash = 0;
+    for (int i = 0; i < s.length(); i++) {
+      hash = hash * 239 + s.charAt(i);
     }
-    return id;
+    return hash == 0 ? 1 : hash;
+  }
+
+  static int[] hashQualifiedName(@NotNull String qName) {
+    qName = PsiNameHelper.getQualifiedClassName(qName, true);
+    if (qName.isEmpty()) return ArrayUtil.EMPTY_INT_ARRAY;
+
+    List<String> components = StringUtil.split(qName, ".");
+    int[] result = new int[components.size()];
+    for (int i = 0; i < components.size(); i++) {
+      result[i] = hashIdentifier(components.get(i));
+    }
+    return result;
   }
 
-  int memberQualifiedName(@QNameHash int ownerName, @ShortName int name) {
+  static int memberQualifiedName(@QNameHash int ownerName, @ShortName int name) {
     return name == NO_NAME || ownerName == 0 ? 0 : qualifiedName(ownerName, name);
   }
 
-  @QNameHash int qualifiedName(@QNameHash int prefix, @ShortName int shortName) {
+  static @QNameHash int qualifiedName(@QNameHash int prefix, @ShortName int shortName) {
     int hash = prefix * 31 + shortName;
     return hash == 0 ? 1 : hash;
   }
index db9a6353f8b9dfc2fe41f45850946a6f3c91d963..ef5067fc6e4ef9dfa92e1e604d3abd4a6d256096 100644 (file)
@@ -66,10 +66,8 @@ class SerializedUnit {
     }
   }
 
-  /**
-   * @see NameEnvironment#readQualifiedName(DataInput)
-   */
-  static void writeQualifiedName(DataOutput out, @QNameHash int[] array) throws IOException {
+  private static void writeNameComponents(DataOutput out, String qName) throws IOException {
+    int[] array = NameEnvironment.hashQualifiedName(qName);
     DataInputOutputUtil.writeINT(out, array.length);
     for (int i : array) {
       out.writeInt(i);
@@ -90,15 +88,16 @@ class SerializedUnit {
   // unit
 
   private static void writeUnit(@NotNull DataOutput out, IndexTree.Unit value) throws IOException {
-    writeQualifiedName(out, value.myPackageName);
+    writeNameComponents(out, value.myPackageName);
     out.writeByte(value.myUnitType);
-    if (value.myUnitType != IndexTree.BYTECODE) {
+    boolean compiled = value.myUnitType == IndexTree.BYTECODE;
+    if (!compiled) {
       Imports.writeImports(out, value);
     }
     // class Declaration
     DataInputOutputUtil.writeINT(out, value.myDecls.length);
     for (IndexTree.ClassDecl def : value.myDecls) {
-      saveClassDecl(out, def);
+      saveClassDecl(out, def, compiled);
     }
   }
 
@@ -116,12 +115,12 @@ class SerializedUnit {
 
   // class
 
-  private static void saveClassDecl(@NotNull DataOutput out, IndexTree.ClassDecl value) throws IOException {
+  private static void saveClassDecl(@NotNull DataOutput out, IndexTree.ClassDecl value, boolean compiled) throws IOException {
     DataInputOutputUtil.writeINT(out, value.myStubId);
     DataInputOutputUtil.writeINT(out, value.myMods);
-    out.writeInt(value.myName);
-    writeSupers(out, value);
-    writeMembers(out, value.myDecls);
+    out.writeInt(NameEnvironment.hashIdentifier(value.myName));
+    writeSupers(out, value, compiled);
+    writeMembers(out, value.myDecls, compiled);
   }
 
   private static ClassSymbol readClassDecl(UnitInputStream in, UnitInfo info, Symbol owner, @QNameHash int ownerName) throws IOException {
@@ -130,7 +129,7 @@ class SerializedUnit {
     @ShortName int name = in.readInt();
     @CompactArray(QualifiedName.class) Object superNames = readSupers(in, info.isCompiled());
 
-    @QNameHash int qname = in.names.memberQualifiedName(ownerName, name);
+    @QNameHash int qname = NameEnvironment.memberQualifiedName(ownerName, name);
     ClassSymbol symbol = in.stubEnter.classEnter(info, owner, stubId, mods, name, superNames, qname, in.fileId);
 
     readMembers(in, info, qname, symbol);
@@ -139,10 +138,10 @@ class SerializedUnit {
 
   // supers
 
-  private static void writeSupers(@NotNull DataOutput out, IndexTree.ClassDecl value) throws IOException {
+  private static void writeSupers(@NotNull DataOutput out, IndexTree.ClassDecl value, boolean interned) throws IOException {
     DataInputOutputUtil.writeINT(out, value.mySupers.length);
-    for (int[] aSuper : value.mySupers) {
-      writeQualifiedName(out, aSuper);
+    for (String aSuper : value.mySupers) {
+      writeSuperName(out, interned, aSuper);
     }
   }
 
@@ -158,16 +157,24 @@ class SerializedUnit {
     return superNames;
   }
 
+  private static void writeSuperName(@NotNull DataOutput out, boolean interned, String aSuper) throws IOException {
+    if (interned) {
+      out.writeInt(NameEnvironment.fromString(aSuper));
+    } else {
+      writeNameComponents(out, aSuper);
+    }
+  }
+
   private static QualifiedName readSuperName(UnitInputStream in, boolean intern) throws IOException {
-    return intern ? new QualifiedName.Interned(in.names.readQualifiedName(in)) : readNameComponents(in);
+    return intern ? new QualifiedName.Interned(in.readInt()) : readNameComponents(in);
   }
 
   // members
 
-  private static void writeMembers(@NotNull DataOutput out, IndexTree.Decl[] decls) throws IOException {
+  private static void writeMembers(@NotNull DataOutput out, IndexTree.Decl[] decls, boolean compiled) throws IOException {
     DataInputOutputUtil.writeINT(out, decls.length);
     for (IndexTree.Decl def : decls) {
-      saveDecl(out, def);
+      saveDecl(out, def, compiled);
     }
   }
 
@@ -187,13 +194,13 @@ class SerializedUnit {
 
   // decl: class or member
 
-  private static void saveDecl(@NotNull DataOutput out, IndexTree.Decl value) throws IOException {
+  private static void saveDecl(@NotNull DataOutput out, IndexTree.Decl value, boolean compiled) throws IOException {
     if (value instanceof IndexTree.ClassDecl) {
       out.writeBoolean(true);
-      saveClassDecl(out, (IndexTree.ClassDecl)value);
+      saveClassDecl(out, (IndexTree.ClassDecl)value, compiled);
     } else if (value instanceof IndexTree.MemberDecl) {
       out.writeBoolean(false);
-      writeMembers(out, ((IndexTree.MemberDecl)value).myDecls);
+      writeMembers(out, ((IndexTree.MemberDecl)value).myDecls, compiled);
     }
   }
 
@@ -225,12 +232,10 @@ class SerializedUnit {
 class UnitInputStream extends DataInputStream {
   final int fileId;
   final StubEnter stubEnter;
-  final NameEnvironment names;
 
   UnitInputStream(InputStream in, int fileId, StubEnter stubEnter) {
     super(in);
     this.fileId = fileId;
     this.stubEnter = stubEnter;
-    this.names = stubEnter.myNameEnvironment;
   }
 }
index cc4cc55a2d7cb314c80b2cfd5bbee48e139b3142..2bd07184d4b81606c3a070ba5ddcca8749816b1d 100644 (file)
@@ -29,7 +29,6 @@ import static com.intellij.psi.stubsHierarchy.impl.Symbol.ClassSymbol;
 import static com.intellij.psi.stubsHierarchy.impl.Symbol.PackageSymbol;
 
 public class StubEnter {
-  final NameEnvironment myNameEnvironment;
   final Imports imports = new Imports();
   private final Symbols mySymbols;
   private final StubHierarchyConnector myStubHierarchyConnector;
@@ -37,9 +36,8 @@ public class StubEnter {
   private ArrayList<ClassSymbol> uncompleted = new ArrayList<ClassSymbol>();
 
   StubEnter(Symbols symbols) {
-    myNameEnvironment = symbols.myNameEnvironment;
     mySymbols = symbols;
-    myStubHierarchyConnector = new StubHierarchyConnector(myNameEnvironment, symbols);
+    myStubHierarchyConnector = new StubHierarchyConnector(symbols);
   }
 
   PackageSymbol readPackageName(DataInput in) throws IOException {
@@ -48,7 +46,7 @@ public class StubEnter {
     int len = DataInputOutputUtil.readINT(in);
     for (int i = 0; i < len; i++) {
       int shortName = in.readInt();
-      qname = myNameEnvironment.qualifiedName(qname, shortName);
+      qname = NameEnvironment.qualifiedName(qname, shortName);
       pkg = mySymbols.enterPackage(qname, shortName, pkg);
     }
     return pkg;
@@ -75,13 +73,13 @@ public class StubEnter {
   @CompactArray(QualifiedName.class)
   Object handleSpecialSupers(int flags, @CompactArray(QualifiedName.class) Object superNames) {
     if (BitUtil.isSet(flags, IndexTree.ANNOTATION)) {
-      return myNameEnvironment.java_lang_annotation_Annotation;
+      return NameEnvironment.java_lang_annotation_Annotation;
     }
 
     if (BitUtil.isSet(flags, IndexTree.ENUM)) {
-      if (superNames == null) return myNameEnvironment.java_lang_Enum;
-      if (superNames instanceof QualifiedName) return new QualifiedName[]{(QualifiedName)superNames, myNameEnvironment.java_lang_Enum};
-      return ArrayUtil.append((QualifiedName[])superNames, myNameEnvironment.java_lang_Enum);
+      if (superNames == null) return NameEnvironment.java_lang_Enum;
+      if (superNames instanceof QualifiedName) return new QualifiedName[]{(QualifiedName)superNames, NameEnvironment.java_lang_Enum};
+      return ArrayUtil.append((QualifiedName[])superNames, NameEnvironment.java_lang_Enum);
     }
 
     return superNames;
index 8d8112ddec82f41bcf931641e859576a67be5564..5a3c1f58c85a40d4ce020ef08eabf70301b69534 100644 (file)
@@ -21,11 +21,9 @@ import java.util.Iterator;
 import java.util.Set;
 
 public class StubHierarchyConnector {
-  private final NameEnvironment myNameEnvironment;
   private final StubResolver myResolve;
 
-  protected StubHierarchyConnector(NameEnvironment nameEnvironment, Symbols symbols) {
-    this.myNameEnvironment = nameEnvironment;
+  protected StubHierarchyConnector(Symbols symbols) {
     myResolve = new StubResolver(symbols, this);
   }
 
@@ -67,9 +65,9 @@ public class StubHierarchyConnector {
     c.setSupers(supertypes);
   }
 
-  private boolean isJavaLangObject(Symbol s) {
+  private static boolean isJavaLangObject(Symbol s) {
     return s.myShortName == NameEnvironment.OBJECT_NAME &&
            s.myOwner instanceof Symbol.PackageSymbol &&
-           ((Symbol.PackageSymbol)s.myOwner).myQualifiedName == myNameEnvironment.java_lang;
+           ((Symbol.PackageSymbol)s.myOwner).myQualifiedName == NameEnvironment.java_lang;
   }
 }
index 1e94cad878a35b47eff9705cc7afc63e139fc164..e6019223e13ba3da4a88fbd03802f6dc1132a989 100644 (file)
@@ -96,7 +96,7 @@ public class StubHierarchyIndex extends FileBasedIndexExtension<Integer, Seriali
 
   @Override
   public int getVersion() {
-    return IndexTree.STUB_HIERARCHY_ENABLED ? 7 + Arrays.stream(ourIndexers).mapToInt(StubHierarchyIndexer::getVersion).sum() : 0;
+    return IndexTree.STUB_HIERARCHY_ENABLED ? 8 + Arrays.stream(ourIndexers).mapToInt(StubHierarchyIndexer::getVersion).sum() : 0;
   }
 
   @NotNull
index 9e3c7520d032065cd229f008231b09de9121c36b..0375ce909ff63f3ef175c4372a8843758c13a204 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.psi.stubsHierarchy.impl;
 
+import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -24,16 +25,35 @@ import java.util.HashSet;
 import java.util.Set;
 
 public class StubResolver {
+  private static final Import[] DEFAULT_JAVA_IMPORTS = {importPackage("java.lang")};
+  private static final Import[] DEFAULT_GROOVY_IMPORTS = {
+    importPackage("java.lang"),
+    importPackage("java.util"),
+    importPackage("java.io"),
+    importPackage("java.net"),
+    importPackage("groovy.lang"),
+    importPackage("groovy.util"),
+    new Import(NameEnvironment.fromString("java.math"), NameEnvironment.hashIdentifier("BigInteger"), false),
+    new Import(NameEnvironment.fromString("java.math"), NameEnvironment.hashIdentifier("BigDecimal"), false),
+  };
   private final Symbols mySymbols;
-  private final NameEnvironment myNameEnvironment;
   private final StubHierarchyConnector myConnector;
 
   public StubResolver(Symbols symbols, StubHierarchyConnector connector) {
     this.mySymbols = symbols;
-    this.myNameEnvironment = symbols.myNameEnvironment;
     myConnector = connector;
   }
 
+  private static Import importPackage(String qname) {
+    return new Import(NameEnvironment.fromString(qname), 0, false);
+  }
+
+  private static Import[] getDefaultImports(byte type) {
+    if (type == IndexTree.JAVA) return DEFAULT_JAVA_IMPORTS;
+    if (type == IndexTree.GROOVY) return DEFAULT_GROOVY_IMPORTS;
+    return Imports.EMPTY_ARRAY;
+  }
+
   // resolve class `sym` extends/implements `baseId`
   Set<Symbol> resolveBase(Symbol.ClassSymbol sym, @ShortName int[] qname) throws IncompleteHierarchyException {
     Set<Symbol> result = resolveUnqualified(sym, qname[0], qname.length > 1);
@@ -91,7 +111,7 @@ public class StubResolver {
   }
 
   private void findIdentInPackage(Symbol.PackageSymbol pck, @ShortName int name, boolean processPackages, Set<Symbol> symbols) {
-    @QNameHash int fullname = mySymbols.myNameEnvironment.qualifiedName(pck.myQualifiedName, name);
+    @QNameHash int fullname = NameEnvironment.qualifiedName(pck.myQualifiedName, name);
     if (processPackages) {
       ContainerUtil.addIfNotNull(symbols, mySymbols.getPackage(fullname));
     }
@@ -132,7 +152,7 @@ public class StubResolver {
   }
 
   private void findGlobalType(UnitInfo info, @ShortName int name, Set<Symbol> symbols) throws IncompleteHierarchyException {
-    for (Import anImport : Translator.getDefaultImports(info.type, myNameEnvironment))
+    for (Import anImport : getDefaultImports(info.type))
       handleImport(anImport, name, symbols);
     for (Import anImport : info.imports)
       handleImport(anImport, name, symbols);
@@ -157,14 +177,14 @@ public class StubResolver {
             importNamedStatic(s, anImport.importedName, symbols);
       }
       else {
-        Collections.addAll(symbols, findGlobalType(myNameEnvironment.qualifiedName(anImport.qualifier, anImport.importedName)));
+        Collections.addAll(symbols, findGlobalType(NameEnvironment.qualifiedName(anImport.qualifier, anImport.importedName)));
       }
     }
   }
 
   // handling of `import prefix.*`
   private void importAll(@QNameHash int prefix, @ShortName int suffix, final Set<Symbol> symbols) {
-    Collections.addAll(symbols, findGlobalType(myNameEnvironment.qualifiedName(prefix, suffix)));
+    Collections.addAll(symbols, findGlobalType(NameEnvironment.qualifiedName(prefix, suffix)));
   }
 
   // handling of import static `tsym.name` as
index f74d19c06a1426905ae57423f503925862bea069..beb8cd346a6ed941a59729272117d8a426b714d4 100644 (file)
@@ -12,7 +12,6 @@ import java.util.List;
 
 public class Symbols {
   public final PackageSymbol myRootPackage = new PackageSymbol(null, 0, NameEnvironment.NO_NAME);
-  protected final NameEnvironment myNameEnvironment = new NameEnvironment();
   private final AnchorRepository myClassAnchors = new AnchorRepository();
 
   private List<ClassSymbol> myClassSymbols = new ArrayList<>(0x8000);
diff --git a/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Translator.java b/java/java-impl/src/com/intellij/psi/stubsHierarchy/impl/Translator.java
deleted file mode 100644 (file)
index 107ec71..0000000
+++ /dev/null
@@ -1,74 +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.psi.stubsHierarchy.impl;
-
-import com.intellij.openapi.util.Key;
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-
-public class Translator {
-  private static final Key<Import[]> DEFAULT_JAVA_IMPORTS_KEY = Key.create("java_imports");
-  private static final Key<Import[]> DEFAULT_GROOVY_IMPORTS_KEY = Key.create("groovy_imports");
-
-  private static Import[] getDefaultJavaImports(NameEnvironment nameEnvironment) {
-    Import[] imports = nameEnvironment.getUserData(DEFAULT_JAVA_IMPORTS_KEY);
-    if (imports == null) {
-      imports = createDefaultJavaImports(nameEnvironment);
-      nameEnvironment.putUserData(DEFAULT_JAVA_IMPORTS_KEY, imports);
-    }
-    return imports;
-  }
-
-  private static Import[] createDefaultJavaImports(NameEnvironment nameEnvironment) {
-    return new Import[]{
-      importPackage(nameEnvironment, "java.lang")
-    };
-  }
-
-  private static Import[] getDefaultGroovyImports(NameEnvironment nameEnvironment) {
-    Import[] imports = nameEnvironment.getUserData(DEFAULT_GROOVY_IMPORTS_KEY);
-    if (imports == null) {
-      imports = createDefaultGroovyImports(nameEnvironment);
-      nameEnvironment.putUserData(DEFAULT_GROOVY_IMPORTS_KEY, imports);
-    }
-    return imports;
-  }
-
-  private static Import[] createDefaultGroovyImports(NameEnvironment nameEnvironment) {
-    return new Import[] {
-      importPackage(nameEnvironment, "java.lang"),
-      importPackage(nameEnvironment, "java.util"),
-      importPackage(nameEnvironment, "java.io"),
-      importPackage(nameEnvironment, "java.net"),
-      importPackage(nameEnvironment, "groovy.lang"),
-      importPackage(nameEnvironment, "groovy.util"),
-      new Import(nameEnvironment.fromString("java.math"), IndexTree.hashIdentifier("BigInteger"), false),
-      new Import(nameEnvironment.fromString("java.math"), IndexTree.hashIdentifier("BigDecimal"), false),
-    };
-  }
-
-  private static Import importPackage(NameEnvironment nameEnvironment, String qname) {
-    return new Import(nameEnvironment.fromString(qname), 0, false);
-  }
-
-  public static Import[] getDefaultImports(byte type, NameEnvironment nameEnvironment) {
-    if (type == IndexTree.JAVA)
-      return getDefaultJavaImports(nameEnvironment);
-    if (type == IndexTree.GROOVY)
-      return getDefaultGroovyImports(nameEnvironment);
-    return Imports.EMPTY_ARRAY;
-  }
-
-}
index 9727110a24115d8b63d1c7948974461ce44cabf5..f2c613e57a78c730bd0f38cc83426d0cd964af4b 100644 (file)
@@ -15,8 +15,6 @@
  */
 package com.intellij.psi.stubsHierarchy.impl;
 
-import com.intellij.psi.impl.java.stubs.hierarchy.IndexTree;
-
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -43,7 +41,7 @@ import java.lang.annotation.Target;
 @interface QNameHash { }
 
 /**
- * int hash of a qualified name part, produced by {@link IndexTree#hashIdentifier(String)}
+ * int hash of a qualified name part, produced by {@link NameEnvironment#hashIdentifier(String)}
  */
 @Retention(RetentionPolicy.SOURCE)
 @Target(ElementType.TYPE_USE)
similarity index 52%
rename from plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledCompareToInspection.java
rename to java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/FunctionalExpressionStub.java
index d56c8d46959a9143ef6a0d0a71764d0a80e6a8cf..b926e4631d3f69804bbda4d13ef2494498ef9134 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
+ * 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.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.siyeh.ig.bugs;
+package com.intellij.psi.impl.java.stubs;
 
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
+import com.intellij.psi.PsiFunctionalExpression;
+import com.intellij.psi.stubs.IStubElementType;
+import com.intellij.psi.stubs.StubBase;
+import com.intellij.psi.stubs.StubElement;
 
-public class MisspelledCompareToInspection extends MisspelledCompareToInspectionBase {
-
-  @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix(HardcodedMethodConstants.COMPARE_TO);
+public class FunctionalExpressionStub<T extends PsiFunctionalExpression> extends StubBase<T> {
+  protected FunctionalExpressionStub(StubElement parent,
+                                     IStubElementType elementType) {
+    super(parent, elementType);
   }
 }
\ No newline at end of file
index 03591f90e27e718a159b408a4cae88fb8ffa0156..981e99112707c17fa00a040a99661d3568abcebd 100644 (file)
@@ -30,6 +30,8 @@ public interface JavaStubElementTypes {
   JavaAnnotationParameterListType ANNOTATION_PARAMETER_LIST = new JavaAnnotationParameterListType();
   JavaNameValuePairType NAME_VALUE_PAIR = new JavaNameValuePairType();
   JavaLiteralExpressionElementType LITERAL_EXPRESSION = new JavaLiteralExpressionElementType();
+  LambdaExpressionElementType LAMBDA_EXPRESSION = new LambdaExpressionElementType();
+  MethodReferenceElementType METHOD_REFERENCE = new MethodReferenceElementType();
   JavaParameterListElementType PARAMETER_LIST = new JavaParameterListElementType();
   JavaParameterElementType PARAMETER = new JavaParameterElementType();
   JavaTypeParameterElementType TYPE_PARAMETER = new JavaTypeParameterElementType();
@@ -135,4 +137,4 @@ public interface JavaStubElementTypes {
   };
 
   IStubFileElementType JAVA_FILE = new JavaFileElementType();
-}
\ No newline at end of file
+}
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/LambdaExpressionElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/LambdaExpressionElementType.java
new file mode 100644 (file)
index 0000000..8cab424
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * 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.psi.impl.java.stubs;
+
+import com.intellij.lang.ASTNode;
+import com.intellij.lang.LighterAST;
+import com.intellij.lang.LighterASTNode;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiLambdaExpression;
+import com.intellij.psi.impl.source.tree.*;
+import com.intellij.psi.impl.source.tree.java.PsiLambdaExpressionImpl;
+import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
+import com.intellij.psi.stubs.*;
+import com.intellij.psi.tree.IElementType;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+
+public class LambdaExpressionElementType extends JavaStubElementType<FunctionalExpressionStub<PsiLambdaExpression>,PsiLambdaExpression> {
+  public LambdaExpressionElementType() {
+    super("LAMBDA_EXPRESSION");
+  }
+
+  @Override
+  public PsiLambdaExpression createPsi(@NotNull ASTNode node) {
+    return new PsiLambdaExpressionImpl(node);
+  }
+
+  @Override
+  public FunctionalExpressionStub<PsiLambdaExpression> createStub(LighterAST tree, LighterASTNode node, StubElement parentStub) {
+    return new FunctionalExpressionStub<PsiLambdaExpression>(parentStub, this);
+  }
+
+  @Override
+  public PsiLambdaExpression createPsi(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub) {
+    return new PsiLambdaExpressionImpl(stub);
+  }
+
+  @Override
+  public void serialize(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub, @NotNull StubOutputStream dataStream) throws IOException {
+  }
+
+  @NotNull
+  @Override
+  public FunctionalExpressionStub<PsiLambdaExpression> deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
+    return new FunctionalExpressionStub<PsiLambdaExpression>(parentStub, this);
+  }
+
+  @Override
+  public void indexStub(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub, @NotNull IndexSink sink) {
+  }
+
+  @NotNull
+  @Override
+  public ASTNode createCompositeNode() {
+    return new CompositeElement(this) {
+      @Override
+      public void replaceChildInternal(@NotNull ASTNode child, @NotNull TreeElement newElement) {
+        if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType()) &&
+            ElementType.EXPRESSION_BIT_SET.contains(newElement.getElementType())) {
+          boolean needParenth = ReplaceExpressionUtil.isNeedParenthesis(child, newElement);
+          if (needParenth) {
+            newElement = JavaSourceUtil.addParenthToReplacedChild(JavaElementType.PARENTH_EXPRESSION, newElement, getManager());
+          }
+        }
+        super.replaceChildInternal(child, newElement);
+      }
+
+      @Override
+      public int getChildRole(ASTNode child) {
+        final IElementType elType = child.getElementType();
+        if (elType == JavaTokenType.ARROW) {
+          return ChildRole.ARROW;
+        } else if (elType == JavaElementType.PARAMETER_LIST) {
+          return ChildRole.PARAMETER_LIST;
+        } else if (elType == JavaElementType.CODE_BLOCK) {
+          return ChildRole.LBRACE;
+        } else {
+          return ChildRole.EXPRESSION;
+        }
+      }
+    };
+  }
+}
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/MethodReferenceElementType.java b/java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/MethodReferenceElementType.java
new file mode 100644 (file)
index 0000000..41cb46f
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * 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.psi.impl.java.stubs;
+
+import com.intellij.lang.ASTNode;
+import com.intellij.lang.LighterAST;
+import com.intellij.lang.LighterASTNode;
+import com.intellij.psi.JavaTokenType;
+import com.intellij.psi.PsiMethodReferenceExpression;
+import com.intellij.psi.impl.source.tree.*;
+import com.intellij.psi.impl.source.tree.java.PsiMethodReferenceExpressionImpl;
+import com.intellij.psi.impl.source.tree.java.ReplaceExpressionUtil;
+import com.intellij.psi.stubs.*;
+import com.intellij.psi.tree.IElementType;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+
+public class MethodReferenceElementType extends
+                                        JavaStubElementType<FunctionalExpressionStub<PsiMethodReferenceExpression>, PsiMethodReferenceExpression> {
+  public MethodReferenceElementType() {
+    super("METHOD_REF_EXPRESSION");
+  }
+
+  @Override
+  public PsiMethodReferenceExpression createPsi(@NotNull ASTNode node) {
+    return new PsiMethodReferenceExpressionImpl(node);
+  }
+
+  @Override
+  public FunctionalExpressionStub<PsiMethodReferenceExpression> createStub(LighterAST tree, LighterASTNode node, StubElement parentStub) {
+    return new FunctionalExpressionStub<PsiMethodReferenceExpression>(parentStub, this);
+  }
+
+  @Override
+  public PsiMethodReferenceExpression createPsi(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub) {
+    return new PsiMethodReferenceExpressionImpl(stub);
+  }
+
+  @Override
+  public void serialize(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub, @NotNull StubOutputStream dataStream) throws IOException {
+  }
+
+  @NotNull
+  @Override
+  public FunctionalExpressionStub<PsiMethodReferenceExpression> deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
+    return new FunctionalExpressionStub<PsiMethodReferenceExpression>(parentStub, this);
+  }
+
+  @Override
+  public void indexStub(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub, @NotNull IndexSink sink) {
+  }
+
+  @NotNull
+  @Override
+  public ASTNode createCompositeNode() {
+    return new CompositeElement(this) {
+      @Override
+      public void replaceChildInternal(@NotNull ASTNode child, @NotNull TreeElement newElement) {
+        if (ElementType.EXPRESSION_BIT_SET.contains(child.getElementType()) &&
+            ElementType.EXPRESSION_BIT_SET.contains(newElement.getElementType())) {
+          boolean needParenth = ReplaceExpressionUtil.isNeedParenthesis(child, newElement);
+          if (needParenth) {
+            newElement = JavaSourceUtil.addParenthToReplacedChild(JavaElementType.PARENTH_EXPRESSION, newElement, getManager());
+          }
+        }
+        super.replaceChildInternal(child, newElement);
+      }
+
+
+      @Override
+      public int getChildRole(ASTNode child) {
+        final IElementType elType = child.getElementType();
+        if (elType == JavaTokenType.DOUBLE_COLON) {
+          return ChildRole.DOUBLE_COLON;
+        } else if (elType == JavaTokenType.IDENTIFIER) {
+          return ChildRole.REFERENCE_NAME;
+        } else if (elType == JavaElementType.REFERENCE_EXPRESSION) {
+          return ChildRole.CLASS_REFERENCE;
+        }
+        return ChildRole.EXPRESSION;
+      }
+
+    };
+  }
+}
index 2ac445793882251130b83d74955ec87f4b86980a..708b7e609b874f910bcae0b0cca77140a2a3c7a2 100644 (file)
@@ -18,14 +18,9 @@ package com.intellij.psi.impl.java.stubs.hierarchy;
 
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.psi.PsiNameHelper;
-import com.intellij.util.ArrayUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Arrays;
-import java.util.List;
-
 public class IndexTree {
   public static final boolean STUB_HIERARCHY_ENABLED = Registry.is("java.hierarchy.service");
 
@@ -41,123 +36,37 @@ public class IndexTree {
   public static final byte JAVA = 1;
   public static final byte GROOVY = 2;
 
-  public static int hashIdentifier(@Nullable String s) {
-    if (StringUtil.isEmpty(s)) return 0;
-
-    // not using String.hashCode because this way there's less collisions for short package names like 'com'
-    int hash = 0;
-    for (int i = 0; i < s.length(); i++) {
-      hash = hash * 239 + s.charAt(i);
-    }
-    return hash == 0 ? 1 : hash;
-  }
-
-  public static int[] hashQualifiedName(@NotNull String qName) {
-    qName = PsiNameHelper.getQualifiedClassName(qName, true);
-    if (qName.isEmpty()) return ArrayUtil.EMPTY_INT_ARRAY;
-
-    List<String> components = StringUtil.split(qName, ".");
-    int[] result = new int[components.size()];
-    for (int i = 0; i < components.size(); i++) {
-      result[i] = hashIdentifier(components.get(i));
-    }
-    return result;
-  }
-
-  private static int[][] hashQualifiedNameArray(String[] supers) {
-    int[][] superHashes = new int[supers.length][];
-    for (int i = 0; i < supers.length; i++) {
-      superHashes[i] = hashQualifiedName(supers[i]);
-    }
-    return superHashes;
-  }
-
   public static class Unit {
-    @NotNull public final int[] myPackageName;
+    @NotNull public final String myPackageName;
     public final byte myUnitType;
     public final Import[] imports;
     public final ClassDecl[] myDecls;
 
     public Unit(@Nullable String packageName, byte unitType, Import[] imports, ClassDecl[] decls) {
-      this(hashQualifiedName(StringUtil.notNullize(packageName)), unitType, imports, decls);
-    }
-
-    public Unit(@NotNull int[] packageName, byte unitType, Import[] imports, ClassDecl[] decls) {
-      myPackageName = packageName;
+      myPackageName = StringUtil.notNullize(packageName);
       myUnitType = unitType;
       this.imports = imports;
       myDecls = decls;
     }
 
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) return true;
-      if (o == null || getClass() != o.getClass()) return false;
-
-      Unit unit = (Unit)o;
-
-      if (myUnitType != unit.myUnitType) return false;
-      if (!Arrays.equals(myPackageName, unit.myPackageName)) return false;
-      if (!Arrays.equals(imports, unit.imports)) return false;
-      if (!Arrays.equals(myDecls, unit.myDecls)) return false;
-
-      return true;
-    }
-
-    @Override
-    public int hashCode() {
-      int hash = myUnitType * 31 + Arrays.hashCode(myPackageName);
-      for (ClassDecl decl : myDecls) {
-        int name = decl.myName;
-        if (name != 0) {
-          return hash * 31 + name;
-        }
-      }
-      return hash;
-    }
   }
 
   public static class Import {
     public static final Import[] EMPTY_ARRAY = new Import[0];
-    public final int[] myFullname;
+    @NotNull public final String myQualifier;
+    @Nullable public final String myImportedName;
     public final boolean myStaticImport;
     public final boolean myOnDemand;
-    public final int myAlias;
+    @Nullable public final String myAlias;
 
     public Import(String fullname, boolean staticImport, boolean onDemand, @Nullable String alias) {
-      this(hashQualifiedName(fullname), staticImport, onDemand, hashIdentifier(alias));
-    }
-
-    public Import(int[] fullname, boolean staticImport, boolean onDemand, int alias) {
-      myFullname = fullname;
+      myQualifier = onDemand ? fullname : StringUtil.getPackageName(fullname);
+      myImportedName = onDemand ? null : StringUtil.getShortName(fullname);
       myStaticImport = staticImport;
       myOnDemand = onDemand;
       myAlias = alias;
     }
 
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) return true;
-      if (o == null || getClass() != o.getClass()) return false;
-
-      Import anImport = (Import)o;
-
-      if (myStaticImport != anImport.myStaticImport) return false;
-      if (myOnDemand != anImport.myOnDemand) return false;
-      if (!Arrays.equals(myFullname, anImport.myFullname)) return false;
-      if (myAlias != anImport.myAlias) return false;
-
-      return true;
-    }
-
-    @Override
-    public int hashCode() {
-      int result = Arrays.hashCode(myFullname);
-      result = 31 * result + (myStaticImport ? 1 : 0);
-      result = 31 * result + (myOnDemand ? 1 : 0);
-      result = 31 * result + myAlias;
-      return result;
-    }
   }
 
   public static abstract class Decl {
@@ -173,14 +82,10 @@ public class IndexTree {
     public static final ClassDecl[] EMPTY_ARRAY = new ClassDecl[0];
     public final int myStubId;
     public final int myMods;
-    public final int myName;
-    public final int[][] mySupers;
+    public final String myName;
+    public final String[] mySupers;
 
     public ClassDecl(int stubId, int mods, @Nullable String name, String[] supers, Decl[] decls) {
-      this(stubId, mods, hashIdentifier(name), hashQualifiedNameArray(supers), decls);
-    }
-
-    public ClassDecl(int stubId, int mods, int name, int[][] supers, Decl[] decls) {
       super(decls);
       assert stubId > 0;
       myStubId = stubId;
@@ -189,27 +94,6 @@ public class IndexTree {
       mySupers = supers;
     }
 
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) return true;
-      if (o == null || getClass() != o.getClass()) return false;
-
-      ClassDecl classDecl = (ClassDecl)o;
-      if (myStubId != classDecl.myStubId) return false;
-      if (myMods != classDecl.myMods) return false;
-      if (myName != classDecl.myName) return false;
-      if (!Arrays.deepEquals(mySupers, classDecl.mySupers)) return false;
-      if (!Arrays.equals(myDecls, classDecl.myDecls)) return false;
-      return true;
-    }
-
-    @Override
-    public int hashCode() {
-      int result = myStubId;
-      result = 31 * result + myMods;
-      result = 31 * result + myName;
-      return result;
-    }
   }
 
   public static class MemberDecl extends Decl {
@@ -218,19 +102,6 @@ public class IndexTree {
       super(decls);
     }
 
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) return true;
-      if (o == null || getClass() != o.getClass()) return false;
-      MemberDecl that = (MemberDecl)o;
-      if (!Arrays.equals(myDecls, that.myDecls)) return false;
-      return true;
-    }
-
-    @Override
-    public int hashCode() {
-      return Arrays.hashCode(myDecls);
-    }
   }
 
 }
index 324c86edf580fa3017a2fe3400bfa19b9a46f77f..85fbce060fb7025459d1d1e85de811c08edd2005 100644 (file)
@@ -38,7 +38,7 @@ import java.io.IOException;
  * @author max
  */
 public class JavaFileElementType extends ILightStubFileElementType<PsiJavaFileStub> {
-  public static final int STUB_VERSION = 26;
+  public static final int STUB_VERSION = 27;
 
   public JavaFileElementType() {
     super("java.FILE", JavaLanguage.INSTANCE);
@@ -111,4 +111,4 @@ public class JavaFileElementType extends ILightStubFileElementType<PsiJavaFileSt
   @Override
   @SuppressWarnings("LambdaUnfriendlyMethodOverload")
   public void indexStub(@NotNull PsiJavaFileStub stub, @NotNull IndexSink sink) { }
-}
\ No newline at end of file
+}
index 3f6b9309f86c16a7931b158f37fe3b09dc25215a..b13629f0ac2c1b81fc2c55ef53a75041a05a9c64 100644 (file)
@@ -103,7 +103,8 @@ public class JavaLightStubBuilder extends LightStubBuilder {
 
   private static class CodeBlockVisitor extends RecursiveTreeElementWalkingVisitor implements LighterLazyParseableNode.Visitor {
     private static final TokenSet BLOCK_ELEMENTS = TokenSet.create(
-      JavaElementType.ANNOTATION, JavaElementType.CLASS, JavaElementType.ANONYMOUS_CLASS);
+      JavaElementType.ANNOTATION, JavaElementType.CLASS, JavaElementType.ANONYMOUS_CLASS,
+      JavaElementType.LAMBDA_EXPRESSION, JavaElementType.METHOD_REF_EXPRESSION);
 
     private boolean result = true;
 
@@ -127,8 +128,8 @@ public class JavaLightStubBuilder extends LightStubBuilder {
         return true;
       }
 
-      // annotations
-      if (type == JavaTokenType.AT) {
+      // annotations, method refs & lambdas
+      if (type == JavaTokenType.AT || type == JavaTokenType.ARROW || type == JavaTokenType.DOUBLE_COLON) {
         return (result = false);
       }
       // anonymous classes
@@ -150,4 +151,4 @@ public class JavaLightStubBuilder extends LightStubBuilder {
       return true;
     }
   }
-}
\ No newline at end of file
+}
index cb33d967c737c810cb753425929fade0a4116187..8b090449e12fca4492af2f27d1b5af053eb3d4c9 100644 (file)
@@ -557,23 +557,23 @@ public class PsiClassImpl extends JavaStubPsiElement<PsiClassStub<?>> implements
   }
 
   @Nullable
-  private static PsiElement calcBasesResolveContext(PsiClass aClass,
-                                                    String className,
+  private static PsiElement calcBasesResolveContext(PsiElement scope,
+                                                    String baseClassName,
                                                     boolean isInitialClass,
                                                     final PsiElement defaultResolveContext) {
-    final PsiClassStub stub = ((PsiClassImpl)aClass).getStub();
-    if (stub == null || stub.isAnonymousInQualifiedNew()) {
-      return aClass.getParent();
+    final StubElement stub = ((StubBasedPsiElementBase<?>)scope).getStub();
+    if (stub == null || stub instanceof PsiClassStub && ((PsiClassStub)stub).isAnonymousInQualifiedNew()) {
+      return scope.getParent();
     }
 
-    boolean isAnonOrLocal = isAnonymousOrLocal(aClass);
-
-    if (!isAnonOrLocal) {
-      return isInitialClass ? defaultResolveContext : aClass;
-    }
+    if (scope instanceof PsiClass) {
+      if (!isAnonymousOrLocal((PsiClass)scope)) {
+        return isInitialClass ? defaultResolveContext : scope;
+      }
 
-    if (!isInitialClass) {
-      if (aClass.findInnerClassByName(className, true) != null) return aClass;
+      if (!isInitialClass) {
+        if (((PsiClass)scope).findInnerClassByName(baseClassName, true) != null) return scope;
+      }
     }
 
     final StubElement parentStub = stub.getParentStub();
@@ -582,43 +582,38 @@ public class PsiClassImpl extends JavaStubPsiElement<PsiClassStub<?>> implements
       LOG.error(stub + " parent is " + parentStub);
       return null;
     }
-    final StubBasedPsiElementBase<?> context = (StubBasedPsiElementBase)psi;
-    @SuppressWarnings("unchecked")
-    PsiClass[] classesInScope = (PsiClass[])parentStub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY);
 
-    boolean needPreciseContext = false;
-    if (classesInScope.length > 1) {
-      for (PsiClass scopeClass : classesInScope) {
-        if (scopeClass == aClass) continue;
-        String className1 = scopeClass.getName();
-        if (className.equals(className1)) {
-          needPreciseContext = true;
-          break;
-        }
-      }
-    }
-    else {
-      if (classesInScope.length != 1) {
-        LOG.error("Parent stub: " + parentStub.getStubType() + "; children: " + parentStub.getChildrenStubs() + "; \ntext:" + context.getText());
-      }
-      LOG.assertTrue(classesInScope[0] == aClass);
+    if (hasChildClassStub(parentStub, baseClassName, scope)) {
+      return scope.getParent();
     }
 
-    if (needPreciseContext) {
-      return aClass.getParent();
+    if (psi instanceof PsiClass || psi instanceof PsiLambdaExpression) {
+      return calcBasesResolveContext(psi, baseClassName, false, defaultResolveContext);
     }
-    else {
-      if (context instanceof PsiClass) {
-        return calcBasesResolveContext((PsiClass)context, className, false, defaultResolveContext);
-      }
-      else if (context instanceof PsiMember) {
-        return calcBasesResolveContext(((PsiMember)context).getContainingClass(), className, false, defaultResolveContext);
+    if (psi instanceof PsiMember) {
+      return calcBasesResolveContext(((PsiMember)psi).getContainingClass(), baseClassName, false, defaultResolveContext);
+    }
+    LOG.error(parentStub);
+    return psi;
+  }
+
+  private static boolean hasChildClassStub(StubElement parentStub, String className, PsiElement place) {
+    PsiClass[] classesInScope = (PsiClass[])parentStub.getChildrenByType(Constants.CLASS_BIT_SET, PsiClass.ARRAY_FACTORY);
+
+    for (PsiClass scopeClass : classesInScope) {
+      if (scopeClass == place) continue;
+      if (className.equals(scopeClass.getName())) {
+        return true;
       }
-      else {
-        LOG.assertTrue(false);
-        return context;
+    }
+
+    if (place instanceof PsiClass) {
+      if (classesInScope.length == 0) {
+        LOG.error("Parent stub: " + parentStub.getStubType() + "; children: " + parentStub.getChildrenStubs() + "; \ntext:" + parentStub.getPsi().getText());
       }
+      LOG.assertTrue(Arrays.asList(classesInScope).contains(place));
     }
+    return false;
   }
 
   @Override
index f1e0f2e083ca846308c6af645cef69077fb31a0e..89497290f92db615f5d648c1fa60f041be96687e 100644 (file)
@@ -84,6 +84,8 @@ public interface JavaElementType {
   IElementType EXTENDS_BOUND_LIST = JavaStubElementTypes.EXTENDS_BOUND_LIST;
   IElementType THROWS_LIST = JavaStubElementTypes.THROWS_LIST;
   IElementType MODULE = JavaStubElementTypes.MODULE;
+  IElementType LAMBDA_EXPRESSION = JavaStubElementTypes.LAMBDA_EXPRESSION;
+  IElementType METHOD_REF_EXPRESSION = JavaStubElementTypes.METHOD_REFERENCE;
 
   IElementType IMPORT_STATIC_REFERENCE = new JavaCompositeElementType("IMPORT_STATIC_REFERENCE", PsiImportStaticReferenceElementImpl.class);
   IElementType TYPE = new JavaCompositeElementType("TYPE", PsiTypeElementImpl.class);
@@ -110,8 +112,6 @@ public interface JavaElementType {
   IElementType INSTANCE_OF_EXPRESSION = new JavaCompositeElementType("INSTANCE_OF_EXPRESSION", PsiInstanceOfExpressionImpl.class);
   IElementType CLASS_OBJECT_ACCESS_EXPRESSION = new JavaCompositeElementType("CLASS_OBJECT_ACCESS_EXPRESSION", PsiClassObjectAccessExpressionImpl.class);
   IElementType EMPTY_EXPRESSION = new JavaCompositeElementType("EMPTY_EXPRESSION", PsiEmptyExpressionImpl.class, true);
-  IElementType METHOD_REF_EXPRESSION = new JavaCompositeElementType("METHOD_REF_EXPRESSION", PsiMethodReferenceExpressionImpl.class);
-  IElementType LAMBDA_EXPRESSION = new JavaCompositeElementType("LAMBDA_EXPRESSION", PsiLambdaExpressionImpl.class);
   IElementType EXPRESSION_LIST = new JavaCompositeElementType("EXPRESSION_LIST", PsiExpressionListImpl.class, true);
   IElementType EMPTY_STATEMENT = new JavaCompositeElementType("EMPTY_STATEMENT", PsiEmptyStatementImpl.class);
   IElementType BLOCK_STATEMENT = new JavaCompositeElementType("BLOCK_STATEMENT", PsiBlockStatementImpl.class);
@@ -294,4 +294,4 @@ public interface JavaElementType {
     }
   }
   IElementType DUMMY_ELEMENT = new JavaDummyElementType();
-}
\ No newline at end of file
+}
index cdb71a7419e2f5e1cc776a16c6d0d2fcd0f93240..649a0a63f05dacd6579c016a45aa5413cf94e860 100644 (file)
@@ -21,13 +21,13 @@ import com.intellij.openapi.util.Computable;
 import com.intellij.psi.*;
 import com.intellij.psi.controlFlow.*;
 import com.intellij.psi.impl.PsiImplUtil;
+import com.intellij.psi.impl.java.stubs.FunctionalExpressionStub;
+import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
 import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
 import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
-import com.intellij.psi.impl.source.tree.ChildRole;
-import com.intellij.psi.impl.source.tree.JavaElementType;
 import com.intellij.psi.infos.MethodCandidateInfo;
 import com.intellij.psi.scope.PsiScopeProcessor;
-import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import org.jetbrains.annotations.NotNull;
@@ -36,7 +36,8 @@ import org.jetbrains.annotations.Nullable;
 import javax.swing.*;
 import java.util.Map;
 
-public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements PsiLambdaExpression {
+public class PsiLambdaExpressionImpl extends JavaStubPsiElement<FunctionalExpressionStub<PsiLambdaExpression>>
+  implements PsiLambdaExpression {
 
   private static final ControlFlowPolicy ourPolicy = new ControlFlowPolicy() {
     @Nullable
@@ -56,8 +57,12 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi
     }
   };
 
-  public PsiLambdaExpressionImpl() {
-    super(JavaElementType.LAMBDA_EXPRESSION);
+  public PsiLambdaExpressionImpl(@NotNull FunctionalExpressionStub<PsiLambdaExpression> stub) {
+    super(stub, JavaStubElementTypes.LAMBDA_EXPRESSION);
+  }
+
+  public PsiLambdaExpressionImpl(@NotNull ASTNode node) {
+    super(node);
   }
 
   @NotNull
@@ -67,17 +72,8 @@ public class PsiLambdaExpressionImpl extends ExpressionPsiElement implements Psi
   }
 
   @Override
-  public int getChildRole(ASTNode child) {
-    final IElementType elType = child.getElementType();
-    if (elType == JavaTokenType.ARROW) {
-      return ChildRole.ARROW;
-    } else if (elType == JavaElementType.PARAMETER_LIST) {
-      return ChildRole.PARAMETER_LIST;
-    } else if (elType == JavaElementType.CODE_BLOCK) {
-      return ChildRole.LBRACE;
-    } else {
-      return ChildRole.EXPRESSION;
-    }
+  public PsiElement getParent() {
+    return getParentByTree();
   }
 
   @Override
index fe910bde5fb6b1435d5175a33d53ab0715b8f20e..1967a50f68ff44409349e9ab09fcd599bd891461 100644 (file)
@@ -24,6 +24,7 @@ import com.intellij.psi.impl.PsiManagerEx;
 import com.intellij.psi.impl.ResolveScopeManager;
 import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
 import com.intellij.psi.impl.java.stubs.impl.PsiLiteralStub;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
 import com.intellij.psi.impl.source.tree.CompositeElement;
 import com.intellij.psi.impl.source.tree.LeafElement;
 import com.intellij.psi.impl.source.tree.injected.StringLiteralEscaper;
@@ -38,7 +39,7 @@ import org.jetbrains.annotations.Nullable;
 import java.util.Locale;
 
 public class PsiLiteralExpressionImpl
-  extends StubBasedPsiElementBase<PsiLiteralStub>
+  extends JavaStubPsiElement<PsiLiteralStub>
        implements PsiLiteralExpression, PsiLanguageInjectionHost, ContributedReferenceHost {
   @NonNls private static final String QUOT = "&quot;";
 
index ce572483c1998dfbf1e09d48d3ebc1a0f5f17296..1ab3723edb45857166ce2659df53863420e7cefc 100644 (file)
@@ -23,10 +23,12 @@ import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.CheckUtil;
 import com.intellij.psi.impl.PsiImplUtil;
+import com.intellij.psi.impl.java.stubs.FunctionalExpressionStub;
+import com.intellij.psi.impl.java.stubs.JavaStubElementTypes;
+import com.intellij.psi.impl.source.JavaStubPsiElement;
 import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
 import com.intellij.psi.impl.source.resolve.graphInference.InferenceSession;
 import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
-import com.intellij.psi.impl.source.tree.ChildRole;
 import com.intellij.psi.impl.source.tree.JavaElementType;
 import com.intellij.psi.infos.MethodCandidateInfo;
 import com.intellij.psi.scope.ElementClassFilter;
@@ -35,8 +37,8 @@ import com.intellij.psi.scope.PsiScopeProcessor;
 import com.intellij.psi.scope.conflictResolvers.DuplicateConflictResolver;
 import com.intellij.psi.scope.processor.FilterScopeProcessor;
 import com.intellij.psi.scope.util.PsiScopesUtil;
-import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.*;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
@@ -45,15 +47,25 @@ import org.jetbrains.annotations.Nullable;
 import javax.swing.*;
 import java.util.*;
 
-public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase implements PsiMethodReferenceExpression {
+public class PsiMethodReferenceExpressionImpl extends JavaStubPsiElement<FunctionalExpressionStub<PsiMethodReferenceExpression>>
+  implements PsiMethodReferenceExpression {
   private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiMethodReferenceExpressionImpl");
   private static final MethodReferenceResolver RESOLVER = new MethodReferenceResolver();
 
-  public PsiMethodReferenceExpressionImpl() {
-    super(JavaElementType.METHOD_REF_EXPRESSION);
+  public PsiMethodReferenceExpressionImpl(@NotNull FunctionalExpressionStub<PsiMethodReferenceExpression> stub) {
+    super(stub, JavaStubElementTypes.METHOD_REFERENCE);
+  }
+
+  public PsiMethodReferenceExpressionImpl(@NotNull ASTNode node) {
+    super(node);
   }
 
 
+  @Override
+  public PsiElement getParent() {
+    return getParentByTree();
+  }
+
   @Override
   public PsiTypeElement getQualifierType() {
     final PsiElement qualifier = getQualifier();
@@ -284,19 +296,6 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
     }
   }
 
-  @Override
-  public int getChildRole(ASTNode child) {
-    final IElementType elType = child.getElementType();
-    if (elType == JavaTokenType.DOUBLE_COLON) {
-      return ChildRole.DOUBLE_COLON;
-    } else if (elType == JavaTokenType.IDENTIFIER) {
-      return ChildRole.REFERENCE_NAME;
-    } else if (elType == JavaElementType.REFERENCE_EXPRESSION) {
-      return ChildRole.CLASS_REFERENCE;
-    }
-    return ChildRole.EXPRESSION;
-  }
-
   @NotNull
   @Override
   public JavaResolveResult[] multiResolve(boolean incompleteCode) {
@@ -316,7 +315,7 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
       final int offsetInParent = element.getStartOffsetInParent();
       return new TextRange(offsetInParent, offsetInParent + element.getTextLength());
     }
-    final PsiElement colons = findPsiChildByType(JavaTokenType.DOUBLE_COLON);
+    final PsiElement colons = findChildByType(JavaTokenType.DOUBLE_COLON);
     if (colons != null) {
       final int offsetInParent = colons.getStartOffsetInParent();
       return new TextRange(offsetInParent, offsetInParent + colons.getTextLength());
@@ -375,9 +374,9 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
 
   @Override
   public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
-    PsiElement oldIdentifier = findChildByRoleAsPsiElement(ChildRole.REFERENCE_NAME);
+    PsiElement oldIdentifier = findChildByType(JavaTokenType.IDENTIFIER);
     if (oldIdentifier == null) {
-      oldIdentifier = findChildByRoleAsPsiElement(ChildRole.CLASS_REFERENCE);
+      oldIdentifier = findChildByType(JavaElementType.REFERENCE_EXPRESSION);
     }
     if (oldIdentifier == null) {
       throw new IncorrectOperationException();
@@ -478,4 +477,72 @@ public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase
   public Icon getIcon(int flags) {
     return AllIcons.Nodes.MethodReference;
   }
+
+  @Override
+  public PsiElement bindToElementViaStaticImport(@NotNull final PsiClass qualifierClass) throws IncorrectOperationException {
+    throw new IncorrectOperationException();
+  }
+
+  @Override
+  public PsiElement getElement() {
+    return this;
+  }
+
+  @Override
+  public PsiElement resolve() {
+    return advancedResolve(false).getElement();
+  }
+
+  @NotNull
+  @Override
+  public Object[] getVariants() {
+    // this reference's variants are rather obtained with processVariants()
+    return ArrayUtil.EMPTY_OBJECT_ARRAY;
+  }
+
+  @Override
+  public boolean isSoft() {
+    return false;
+  }
+
+  @Override
+  public PsiReference getReference() {
+    return this;
+  }
+
+  @NotNull
+  @Override
+  public JavaResolveResult advancedResolve(boolean incompleteCode) {
+    final JavaResolveResult[] results = multiResolve(incompleteCode);
+    return results.length == 1 ? results[0] : JavaResolveResult.EMPTY;
+  }
+
+  @Override
+  public String getReferenceName() {
+    final PsiElement element = getReferenceNameElement();
+    return element != null ? element.getText() : null;
+  }
+
+  @Override
+  public PsiReferenceParameterList getParameterList() {
+    return PsiTreeUtil.getChildOfType(this, PsiReferenceParameterList.class);
+  }
+
+  @NotNull
+  @Override
+  public PsiType[] getTypeParameters() {
+    final PsiReferenceParameterList parameterList = getParameterList();
+    return parameterList != null ? parameterList.getTypeArguments() : PsiType.EMPTY_ARRAY;
+  }
+
+  @Override
+  public boolean isQualified() {
+    return getQualifier() != null;
+  }
+
+  @Override
+  public String getQualifiedName() {
+    return getCanonicalText();
+  }
+
 }
index f2b5752b9eef71752eec5dea7a82a5ce0aa5a37f..1897fa90b92068f94798fbb1e573d8d611049d37 100644 (file)
@@ -2,4 +2,8 @@ public class Test {
   public void foo(@SuppressWarnings("UnusedParameters") boolean b) {
 
   }
+
+  public void foo(@SuppressWarnings("unused") boolean b) {
+
+  }
 }
diff --git a/java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java b/java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java
new file mode 100644 (file)
index 0000000..5b581ce
--- /dev/null
@@ -0,0 +1,6 @@
+class Test {
+  {
+    Double d = 1.0;
+    <caret>d.byteValue();
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java.after b/java/java-tests/testData/refactoring/inlineLocal/ParenthesisAroundCast.java.after
new file mode 100644 (file)
index 0000000..d210d8a
--- /dev/null
@@ -0,0 +1,5 @@
+class Test {
+  {
+      ((Double) 1.0).byteValue();
+  }
+}
\ No newline at end of file
index 91a9bfa8556b2c1924fe6bfa7fe2c4f0869e77d8..6b049b7d6ee5656e0b834d23070117c2aacfa7af 100644 (file)
@@ -357,6 +357,22 @@ public class InspectionProfileTest extends LightIdeaTestCase {
                          "</profile>");
   }
 
+  public void testMergedMisspelledInspections() throws Exception {
+    checkMergedNoChanges("<profile version=\"1.0\">\n" +
+                         "  <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
+                         "  <inspection_tool class=\"MethodNamesDifferOnlyByCase\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
+                         "    <option name=\"ignoreIfMethodIsOverride\" value=\"false\" />\n" +
+                         "  </inspection_tool>\n" +
+                         "</profile>");
+    checkMergedNoChanges("<profile version=\"1.0\">\n" +
+                         "  <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
+                         "  <inspection_tool class=\"MethodNamesDifferOnlyByCase\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\">\n" +
+                         "    <option name=\"ignoreIfMethodIsOverride\" value=\"false\" />\n" +
+                         "  </inspection_tool>\n" +
+                         "  <inspection_tool class=\"MisspelledSetUp\" enabled=\"true\" level=\"WARNING\" enabled_by_default=\"false\" />\n" +
+                         "</profile>");
+  }
+
   public void testDisabledUnusedDeclarationWithChanges() throws Exception {
     checkMergedNoChanges("<profile version=\"1.0\">\n" +
                          "  <option name=\"myName\" value=\"" + PROFILE + "\" />\n" +
index 937668d7789a8b7e0507e98b94d4e2b5ee96186f..13fca2e78688ccabe9b2b1418c631a19f57d679f 100644 (file)
@@ -235,7 +235,8 @@ public class JavaStubBuilderTest extends LightIdeaTestCase {
            "      MODIFIER_LIST:PsiModifierListStub[mask=0]\n" +
            "      ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=O.P]\n" +
            "      ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=Y inqualifnew]\n" +
-           "      ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=R]\n");
+           "      LAMBDA_EXPRESSION:FunctionalExpressionStub\n" +
+           "        ANONYMOUS_CLASS:PsiClassStub[anonymous name=null fqn=null baseref=R]\n");
   }
 
   public void testEnums() {
@@ -435,8 +436,9 @@ public class JavaStubBuilderTest extends LightIdeaTestCase {
            "        ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
            "      ANNOTATION:PsiAnnotationStub[@A5]\n" +
            "        ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
-           "      ANNOTATION:PsiAnnotationStub[@A6]\n" +
-           "        ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
+           "      METHOD_REF_EXPRESSION:FunctionalExpressionStub\n" +
+           "        ANNOTATION:PsiAnnotationStub[@A6]\n" +
+           "          ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
            "      ANNOTATION:PsiAnnotationStub[@A7]\n" +
            "        ANNOTATION_PARAMETER_LIST:PsiAnnotationParameterListStubImpl\n" +
            "      ANNOTATION:PsiAnnotationStub[@A8]\n" +
index 7de0d9894a06000cf11c4499e463cd2eebdc30e0..ee93409993482d99b1d0cc90f40d168db1ac9b63 100644 (file)
@@ -21,6 +21,7 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
 import com.intellij.openapi.vfs.VfsUtil
 import com.intellij.psi.impl.source.PsiFileImpl
 import com.intellij.psi.search.GlobalSearchScope
+import com.intellij.psi.search.searches.DirectClassInheritorsSearch
 import com.intellij.psi.search.searches.OverridingMethodsSearch
 import com.intellij.psi.util.PsiTreeUtil
 import com.intellij.reference.SoftReference
@@ -119,6 +120,7 @@ class A {
 
       class MyInner extends Inner {}
     };
+    Runnable r = () -> { new B() {}; };
 }
 
 class B {
@@ -128,6 +130,7 @@ class B {
 """)
     assert !file.contentsLoaded
     PsiClass bClass = ((PsiJavaFile) file).classes[1]
+    assert DirectClassInheritorsSearch.search(bClass).findAll().size() == 2
     assert !file.contentsLoaded
 
     def fooMethod = bClass.methods[0]
index 40be3a539aa35baf89de2b0a7e72075ccf147805..dfae3086b50551cf6c99ec365e233e1b1bcfbd16 100644 (file)
@@ -276,6 +276,10 @@ public class InlineLocalTest extends LightCodeInsightTestCase {
     doTest(false);
   }
 
+  public void testParenthesisAroundCast() throws Exception {
+    doTest(false);
+  }
+
   public void testLocalVarInsideLambdaBodyWriteUsage() throws Exception {
     doTest(true, "Cannot perform refactoring.\n" +
                  "Variable 'hello' is accessed for writing");
index e1c97dfa9cfe96297e99f0f7173b0bdd6335895d..a9a66c757d72ecd4fc9afdd9c45fa26759230b2a 100644 (file)
@@ -16,6 +16,9 @@
 package com.intellij.codeInsight;
 
 import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
+import com.intellij.ide.fileTemplates.FileTemplate;
+import com.intellij.ide.fileTemplates.FileTemplateManager;
+import com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl;
 import com.intellij.injected.editor.EditorWindow;
 import com.intellij.openapi.actionSystem.IdeActions;
 import com.intellij.openapi.application.ApplicationManager;
@@ -57,10 +60,7 @@ import org.jetbrains.annotations.Nullable;
 import java.io.File;
 import java.io.IOException;
 import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 
 /**
  * @author Mike
@@ -81,6 +81,21 @@ public abstract class CodeInsightTestCase extends PsiTestCase {
     return editor;
   }
 
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    FileTemplateManager manager = FileTemplateManager.getDefaultInstance();
+    for (String tname : Arrays.asList("Class", "AnnotationType", "Enum", "Interface")) {
+      for (FileTemplate template : manager.getInternalTemplates()) {
+        if (tname.equals(template.getName())) {
+          String text = "package $PACKAGE_NAME$;\npublic " + manager.internalTemplateToSubject(tname) + " $NAME$ { }";
+          template.setText(FileTemplateManagerImpl.normalizeText(text));
+          break;
+        }
+      }
+    }
+  }
+
   @Override
   protected void tearDown() throws Exception {
     try {
index e379c1291af605b39dd7fe6b1a5836c04aca8f5d..1a545090af9b59dc4a52d52b1612f7d1bf41fbed 100644 (file)
 package com.intellij.codeInspection;
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
+import com.intellij.codeInspection.ex.InspectionElementsMerger;
 import com.intellij.lang.Language;
 import com.intellij.lang.injection.InjectedLanguageManager;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.WriteExternalException;
@@ -81,6 +83,18 @@ public abstract class InspectionProfileEntry implements BatchSuppressableTool {
         return true;
       }
     }
+
+    final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(getShortName());
+    if (merger != null) {
+      for (String sourceToolId : merger.getSourceToolNames()) {
+        for (InspectionSuppressor suppressor : suppressors) {
+          if (isSuppressed(sourceToolId, suppressor, element)) {
+            return true;
+          }
+        }
+      }
+    }
+
     return false;
   }
 
diff --git a/platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java b/platform/analysis-api/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java
new file mode 100644 (file)
index 0000000..b4c321b
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.codeInspection.ex;
+
+import com.intellij.openapi.extensions.ExtensionPointName;
+import com.intellij.openapi.extensions.Extensions;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.HashMap;
+import java.util.Map;
+
+
+/**
+ * Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}
+ *
+ * {@see com.intellij.codeInspection.ex.InspectionElementsMergerBase} to provide more fine control over xml
+ */
+public abstract class InspectionElementsMerger {
+  public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
+  private static Map<String, InspectionElementsMerger> ourMergers;
+
+  @Nullable
+  public synchronized static InspectionElementsMerger getMerger(String shortName) {
+    if (ourMergers == null) {
+      ourMergers = new HashMap<>();
+      for (InspectionElementsMerger merger : Extensions.getExtensions(EP_NAME)) {
+        ourMergers.put(merger.getMergedToolName(), merger);
+      }
+    }
+    return ourMergers.get(shortName);
+  }
+
+  public abstract String   getMergedToolName();
+  public abstract String[] getSourceToolNames();
+}
index 3e3faf2f23be3e822be4c82e7986d70c1d8f45e5..2f11113986ef1f718051dd2be412e40690e8a97d 100644 (file)
@@ -208,7 +208,7 @@ public class GlobalInspectionContextBase extends UserDataHolderBase implements G
   }
 
   public boolean isToCheckMember(@NotNull RefElement owner, @NotNull InspectionProfileEntry tool) {
-    return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool) && !((RefElementImpl)owner).isSuppressed(tool.getShortName());
+    return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool) && !((RefElementImpl)owner).isSuppressed(tool.getShortName(), tool.getAlternativeID());
   }
 
   public boolean isToCheckFile(PsiFile file, @NotNull InspectionProfileEntry tool) {
index 44ea4a205a38a5c38cfe3a38ffbc7aa173eafa15..4ab2c77092cced95fd11c68b8245122555f45c6a 100644 (file)
@@ -42,7 +42,7 @@ public class GlobalInspectionContextUtil {
 
 
   public static boolean isToCheckMember(@NotNull RefElement owner, @NotNull InspectionProfileEntry tool, Tools tools, ProfileManager profileManager) {
-    return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool, tools, profileManager) && !((RefElementImpl)owner).isSuppressed(tool.getShortName());
+    return isToCheckFile(((RefElementImpl)owner).getContainingFile(), tool, tools, profileManager) && !((RefElementImpl)owner).isSuppressed(tool.getShortName(), tool.getAlternativeID());
   }
 
   public static boolean isToCheckFile(PsiFile file, @NotNull InspectionProfileEntry tool, Tools tools, ProfileManager profileManager) {
similarity index 90%
rename from platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionElementsMerger.java
rename to platform/analysis-impl/src/com/intellij/codeInspection/ex/InspectionElementsMergerBase.java
index 910df0c1ba366ad0512a77c3f88c8fb2a290b6ac..991a41de47be8c34594855ef63482623ddfbace2 100644 (file)
@@ -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.
 package com.intellij.codeInspection.ex;
 
 import com.intellij.lang.annotation.HighlightSeverity;
-import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.util.JDOMUtil;
 import com.intellij.openapi.util.WriteExternalException;
 import org.jdom.Element;
 
 import java.util.*;
 
-/**
- * Merges multiple inspections settings {@link #getSourceToolNames()} into another one {@link #getMergedToolName()}
- */
-public abstract class InspectionElementsMerger {
-  public static final ExtensionPointName<InspectionElementsMerger> EP_NAME = ExtensionPointName.create("com.intellij.inspectionElementsMerger");
 
-  protected abstract String   getMergedToolName();
-  protected abstract String[] getSourceToolNames();
+public abstract class InspectionElementsMergerBase extends InspectionElementsMerger {
 
   /**
    * serialize old inspection settings as they could appear in old profiles
@@ -158,4 +151,22 @@ public abstract class InspectionElementsMerger {
       }
     }
   }
+
+  public static class InspectionElementsMergerDelegate extends InspectionElementsMergerBase {
+    private final InspectionElementsMerger myMerger;
+
+    public InspectionElementsMergerDelegate(InspectionElementsMerger merger) {
+      myMerger = merger;
+    }
+
+    @Override
+    public String getMergedToolName() {
+      return myMerger.getMergedToolName();
+    }
+
+    @Override
+    public String[] getSourceToolNames() {
+      return myMerger.getSourceToolNames();
+    }
+  }
 }
index f2c65d612ba67de299c088aedc61f64bee0d744d..3690e3c16b0f9f54730a21683ecd59140da977cf 100644 (file)
@@ -71,8 +71,7 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
   @NonNls private static final String USED_LEVELS = "used_levels";
   public static final String DEFAULT_PROFILE_NAME = "Default";
   @TestOnly
-  public static boolean INIT_INSPECTIONS;
-  private static Map<String, InspectionElementsMerger> ourMergers;
+  public static boolean INIT_INSPECTIONS = false;
   private final InspectionToolRegistrar myRegistrar;
   @NotNull
   private final Map<String, Element> myInspectionsSettings = new TreeMap<>();
@@ -125,17 +124,6 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
     myProfileManager = profileManager;
   }
 
-  @NotNull
-  private static synchronized Map<String, InspectionElementsMerger> getMergers() {
-    if (ourMergers == null) {
-      ourMergers = new LinkedHashMap<>();
-      for (InspectionElementsMerger merger : Extensions.getExtensions(InspectionElementsMerger.EP_NAME)) {
-        ourMergers.put(merger.getMergedToolName(), merger);
-      }
-    }
-    return ourMergers;
-  }
-
   @NotNull
   public static InspectionProfileImpl createSimple(@NotNull String name,
                                                    @NotNull Project project,
@@ -339,10 +327,10 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
 
   private void markSettingsMerged(@NotNull String toolName, @NotNull Element element) {
     //add marker if already merged but result is now default (-> empty node)
-    final String mergedName = InspectionElementsMerger.getMergedMarkerName(toolName);
-    if (!myInspectionsSettings.containsKey(mergedName)) {
-      final InspectionElementsMerger merger = getMergers().get(toolName);
-      if (merger != null && merger.markSettingsMerged(myInspectionsSettings)) {
+    final String mergedName = InspectionElementsMergerBase.getMergedMarkerName(toolName);
+    if (!myUninstalledInspectionsSettings.containsKey(mergedName)) {
+      final InspectionElementsMergerBase merger = getMerger(toolName);
+      if (merger != null && merger.markSettingsMerged(myUninstalledInspectionsSettings)) {
         element.addContent(new Element(INSPECTION_TOOL_TAG).setAttribute(CLASS_TAG, mergedName));
       }
     }
@@ -350,8 +338,8 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
 
   private boolean areSettingsMerged(String toolName, Element inspectionElement) {
     //skip merged settings as they could be restored from already provided data
-    final InspectionElementsMerger merger = getMergers().get(toolName);
-    return merger != null && merger.areSettingsMerged(myInspectionsSettings, inspectionElement);
+    final InspectionElementsMergerBase merger = getMerger(toolName);
+    return merger != null && merger.areSettingsMerged(myUninstalledInspectionsSettings, inspectionElement);
   }
 
   public void collectDependentInspections(@NotNull InspectionToolWrapper toolWrapper,
@@ -634,8 +622,8 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
       if (element != null) {
         toolsList.readExternal(element, this, dependencies);
       }
-      else if (!myInspectionsSettings.containsKey(InspectionElementsMerger.getMergedMarkerName(shortName))) {
-        final InspectionElementsMerger merger = getMergers().get(shortName);
+      else if (!myUninstalledInspectionsSettings.containsKey(InspectionElementsMergerBase.getMergedMarkerName(shortName))) {
+        final InspectionElementsMergerBase merger = getMerger(shortName);
         if (merger != null) {
           final Element merged = merger.merge(myInspectionsSettings);
           if (merged != null) {
@@ -650,6 +638,25 @@ public class InspectionProfileImpl extends ProfileEx implements ModifiableModel,
     myTools.put(shortName, toolsList);
   }
 
+  @Nullable
+  private static InspectionElementsMergerBase getMerger(String shortName) {
+    final InspectionElementsMerger merger = InspectionElementsMerger.getMerger(shortName);
+    if (merger instanceof InspectionElementsMergerBase) {
+      return (InspectionElementsMergerBase)merger;
+    }
+    return merger != null ? new InspectionElementsMergerBase() {
+      @Override
+      public String getMergedToolName() {
+        return merger.getMergedToolName();
+      }
+
+      @Override
+      public String[] getSourceToolNames() {
+        return merger.getSourceToolNames();
+      }
+    } : null;
+  }
+
   @Nullable
   @Transient
   public String[] getScopesOrder() {
index c587148d7313826facd37ba8ef53e77e8e3016c9..d3e02082de9459c4b1de11a560751325c469f55e 100644 (file)
@@ -31,6 +31,7 @@ import com.intellij.openapi.application.ApplicationManager
 import com.intellij.openapi.application.PathManager
 import com.intellij.openapi.application.impl.ApplicationImpl
 import com.intellij.openapi.components.*
+import com.intellij.openapi.components.ex.ComponentManagerEx
 import com.intellij.openapi.components.impl.ServiceManagerImpl
 import com.intellij.openapi.components.impl.stores.StateStorageManager
 import com.intellij.openapi.components.impl.stores.StoreUtil
@@ -167,7 +168,7 @@ fun getExportableComponentsMap(onlyExisting: Boolean,
   }
 
   @Suppress("DEPRECATION")
-  ApplicationManager.getApplication().getComponents(ExportableApplicationComponent::class.java).forEach(processor)
+  (ApplicationManager.getApplication() as ComponentManagerEx).getComponentInstancesOfType(ExportableApplicationComponent::class.java).forEach(processor)
   ServiceBean.loadServicesFromBeans(ExportableComponent.EXTENSION_POINT, ExportableComponent::class.java).forEach(processor)
 
   val configPath = storageManager.expandMacros(ROOT_CONFIG)
diff --git a/platform/configuration-store-impl/testSrc/DoNotStorePasswordTest.kt b/platform/configuration-store-impl/testSrc/DoNotStorePasswordTest.kt
new file mode 100644 (file)
index 0000000..7dc9291
--- /dev/null
@@ -0,0 +1,106 @@
+
+import com.intellij.openapi.application.ApplicationManager
+import com.intellij.openapi.application.impl.ApplicationImpl
+import com.intellij.openapi.components.PersistentStateComponent
+import com.intellij.openapi.components.impl.ComponentManagerImpl
+import com.intellij.openapi.components.impl.ServiceManagerImpl
+import com.intellij.openapi.components.impl.stores.StoreUtil
+import com.intellij.openapi.extensions.PluginDescriptor
+import com.intellij.testFramework.ProjectRule
+import com.intellij.util.PairProcessor
+import com.intellij.util.xmlb.XmlSerializerUtil
+import org.jdom.Attribute
+import org.jdom.Element
+import org.junit.ClassRule
+import org.junit.Test
+import java.lang.reflect.ParameterizedType
+import java.lang.reflect.Type
+import java.util.Collection
+
+class DoNotStorePasswordTest {
+  companion object {
+    @JvmField
+    @ClassRule
+    val projectRule = ProjectRule()
+  }
+
+  @Test
+  fun printPasswordComponents() {
+    val processor = PairProcessor<Class<*>, PluginDescriptor> { aClass, pluginDescriptor ->
+      val stateAnnotation = StoreUtil.getStateSpec(aClass)
+      if (stateAnnotation == null || stateAnnotation.name.isNullOrEmpty()) {
+        return@PairProcessor true
+      }
+
+      for (i in aClass.genericInterfaces) {
+        if (checkType(i)) {
+          return@PairProcessor true
+        }
+      }
+
+
+      // public static class Project extends WebServersConfigManagerBaseImpl<WebServersConfigManagerBaseImpl.State> {
+      // so, we check not only PersistentStateComponent
+      checkType(aClass.genericSuperclass)
+
+      true
+    }
+
+    val app = ApplicationManager.getApplication() as ApplicationImpl
+    ServiceManagerImpl.processAllImplementationClasses(app, processor)
+    // yes, we don't use default project here to be sure
+    ServiceManagerImpl.processAllImplementationClasses(projectRule.project as ComponentManagerImpl, processor)
+
+    @Suppress("DEPRECATION")
+    for (c in app.getComponentInstancesOfType(PersistentStateComponent::class.java)) {
+      processor.process(c.javaClass, null)
+    }
+    @Suppress("DEPRECATION")
+    for (c in (projectRule.project as ComponentManagerImpl).getComponentInstancesOfType(PersistentStateComponent::class.java)) {
+      processor.process(c.javaClass, null)
+    }
+  }
+
+  fun isSavePasswordField(name: String) = name.contains("remember", ignoreCase = true) || name.contains("keep", ignoreCase = true) || name.contains("save", ignoreCase = true)
+
+  fun check(clazz: Class<*>) {
+    if (clazz === Attribute::class.java || clazz === Element::class.java) {
+      return
+    }
+
+    for (accessor in XmlSerializerUtil.getAccessors(clazz)) {
+      val name = accessor.name
+      if (name.contains("password", ignoreCase = true) && !isSavePasswordField(name)) {
+        System.out.println("${clazz.typeName}.${accessor.name}")
+      }
+      else if (!accessor.valueClass.isPrimitive) {
+        @Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
+        if (Collection::class.java.isAssignableFrom(accessor.valueClass)) {
+          val genericType = accessor.genericType
+          if (genericType is ParameterizedType) {
+            check(genericType.actualTypeArguments[0] as Class<*>)
+          }
+        }
+        else if (accessor.valueClass != clazz) {
+          check(accessor.valueClass)
+        }
+      }
+    }
+  }
+
+  private fun checkType(type: Type): Boolean {
+    if (type !is ParameterizedType || !PersistentStateComponent::class.java.isAssignableFrom(type.rawType as Class<*>)) {
+      return false
+    }
+
+    type.actualTypeArguments[0].let {
+      if (it is ParameterizedType) {
+        check(it.rawType as Class<*>)
+      }
+      else {
+        check(it as Class<*>)
+      }
+    }
+    return true
+  }
+}
\ No newline at end of file
index f1740da0f6d9c76accd65ef8e5ac7e4e0a94bff4..5d30ba8f960cba08c37e8a41d247dd37a900d7ec 100644 (file)
@@ -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.
@@ -128,7 +128,11 @@ public abstract class GlobalSearchScope extends SearchScope implements ProjectAw
 
   @NotNull
   public GlobalSearchScope union(@NotNull final LocalSearchScope scope) {
-    return new GlobalSearchScope(scope.getScope()[0].getProject()) {
+    PsiElement[] localScopeElements = scope.getScope();
+    if (localScopeElements.length == 0) {
+      return this;
+    }
+    return new GlobalSearchScope(localScopeElements[0].getProject()) {
       @Override
       public boolean contains(@NotNull VirtualFile file) {
         return GlobalSearchScope.this.contains(file) || scope.isInScope(file);
index 42c3e9ea995a168a86b85234e34ac28d761c2248..98cd4ede78b0fb5998576948ed305e3fdc58cb24 100644 (file)
@@ -115,12 +115,14 @@ public class LocalSearchScope extends SearchScope {
     if (this == o) return true;
     if (!(o instanceof LocalSearchScope)) return false;
 
-    final LocalSearchScope localSearchScope = (LocalSearchScope)o;
+    LocalSearchScope other = (LocalSearchScope)o;
+
+    if (other.myIgnoreInjectedPsi != myIgnoreInjectedPsi) return false;
+    if (other.myScope.length != myScope.length) return false;
+    if (!Comparing.strEqual(myDisplayName, other.myDisplayName)) return false; // scopes like "Current file" and "Changed files" should be different event if empty
 
-    if (localSearchScope.myIgnoreInjectedPsi != myIgnoreInjectedPsi) return false;
-    if (localSearchScope.myScope.length != myScope.length) return false;
     for (final PsiElement scopeElement : myScope) {
-      final PsiElement[] thatScope = localSearchScope.myScope;
+      final PsiElement[] thatScope = other.myScope;
       for (final PsiElement thatScopeElement : thatScope) {
         if (!Comparing.equal(scopeElement, thatScopeElement)) return false;
       }
index f105f64fcbec53d8ebf20c7368dfbf0101575a48..2c6e51fc9d8a2688ebc8099166cbdc619c2f54db 100644 (file)
@@ -49,15 +49,15 @@ import java.util.List;
 public abstract class OptionTreeWithPreviewPanel extends CustomizableLanguageCodeStylePanel {
   private static final Logger LOG = Logger.getInstance("#com.intellij.application.options.CodeStyleSpacesPanel");
   protected JTree myOptionsTree;
-  private final ArrayList<BooleanOptionKey> myKeys = new ArrayList<BooleanOptionKey>();
+  protected final ArrayList<BooleanOptionKey> myKeys = new ArrayList<>();
   protected final JPanel myPanel = new JPanel(new GridBagLayout());
 
   private boolean myShowAllStandardOptions = false;
-  private Set<String> myAllowedOptions = new HashSet<String>();
-  private MultiMap<String, CustomBooleanOptionInfo> myCustomOptions = new MultiMap<String, CustomBooleanOptionInfo>();
+  private Set<String> myAllowedOptions = new HashSet<>();
+  private MultiMap<String, CustomBooleanOptionInfo> myCustomOptions = new MultiMap<>();
   protected boolean isFirstUpdate = true;
-  private final Map<String, String> myRenamedFields = new THashMap<String, String>();
-  private final Map<String, String> myRemappedGroups = new THashMap<String, String>();
+  private final Map<String, String> myRenamedFields = new THashMap<>();
+  private final Map<String, String> myRemappedGroups = new THashMap<>();
 
 
   public OptionTreeWithPreviewPanel(CodeStyleSettings settings) {
index 94c8eac43ff1e00ed9921d2411522d4ec87a8029..b68b5ce746ea769670bd51b46815678cdb4d0b06 100644 (file)
@@ -56,6 +56,7 @@ import com.intellij.openapi.util.TextRange;
 import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
+import com.intellij.util.CommonProcessors;
 import com.intellij.util.Processor;
 import com.intellij.util.Processors;
 import com.intellij.util.containers.ContainerUtil;
@@ -83,11 +84,11 @@ public class ShowIntentionsPass extends TextEditorHighlightingPass {
     final int offset = ((EditorEx)editor).getExpectedCaretOffset();
     final Project project = file.getProject();
 
-    final List<HighlightInfo.IntentionActionDescriptor> result = new ArrayList<>();
-    DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true, info -> {
-      addAvailableActionsForGroups(info, editor, file, result, passId, offset);
-      return true;
-    });
+    List<HighlightInfo> infos = new ArrayList<>();
+    DaemonCodeAnalyzerImpl.processHighlightsNearOffset(editor.getDocument(), project, HighlightSeverity.INFORMATION, offset, true,
+                                                       new CommonProcessors.CollectProcessor<>(infos));
+    List<HighlightInfo.IntentionActionDescriptor> result = new ArrayList<>();
+    infos.forEach(info->addAvailableActionsForGroups(info, editor, file, result, passId, offset));
     return result;
   }
 
index 6eb3c423f2bef968559c2753674bffe395e0a20b..203472cc02f4189703c579f1b97e90e480d3ad3f 100644 (file)
@@ -71,7 +71,9 @@ public class ExportToHTMLDialog extends DialogWrapper{
     }
     final String text = exportToHTMLSettings.OUTPUT_DIRECTORY;
     myTargetDirectoryField.setText(text);
-    myTargetDirectoryField.setPreferredSize(new Dimension(GraphicsUtil.stringWidth(text, myTargetDirectoryField.getFont()) + 100, myTargetDirectoryField.getPreferredSize().height));
+    if (text != null) {
+      myTargetDirectoryField.setPreferredSize(new Dimension(GraphicsUtil.stringWidth(text, myTargetDirectoryField.getFont()) + 100, myTargetDirectoryField.getPreferredSize().height));
+    }
   }
 
   public void apply() {
index 7d4117fc6a34b2fb5ce6293419dd160c2988610d..9c40b617a34b03d22900c1089fd297bd8a4c5fde 100644 (file)
@@ -19,12 +19,14 @@ import com.intellij.application.options.TabbedLanguageCodeStylePanel;
 import com.intellij.lang.Language;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.options.ConfigurationException;
+import com.intellij.openapi.util.Disposer;
 import com.intellij.psi.codeStyle.CodeStyleSettings;
 import com.intellij.psi.codeStyle.CodeStyleSettingsCodeFragmentFilter;
 import com.intellij.psi.codeStyle.LanguageCodeStyleSettingsProvider;
 import com.intellij.ui.components.JBScrollPane;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
@@ -41,6 +43,7 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
   private final CodeStyleSettingsCodeFragmentFilter.CodeStyleSettingsToShow mySettingsToShow;
   private final SelectedTextFormatter mySelectedTextFormatter;
   private SpacesPanelWithoutPreview mySpacesPanel;
+  private WrappingAndBracesPanelWithoutPreview myWrappingPanel;
 
   private Runnable mySomethingChangedCallback;
 
@@ -76,14 +79,30 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
 
   @Override
   protected void initTabs(CodeStyleSettings settings) {
-    mySpacesPanel = new SpacesPanelWithoutPreview(settings);
-    addTab(mySpacesPanel);
-    addTab(new WrappingAndBracesPanelWithoutPreview(settings));
+    SpacesPanelWithoutPreview panel = getSpacesPanel(settings);
+    if (panel != null) {
+      mySpacesPanel = panel;
+      addTab(mySpacesPanel);
+    }
+
+    myWrappingPanel = new WrappingAndBracesPanelWithoutPreview(settings);
+    addTab(myWrappingPanel);
     reset(getSettings());
   }
 
+  @Nullable
+  private SpacesPanelWithoutPreview getSpacesPanel(CodeStyleSettings settings) {
+    SpacesPanelWithoutPreview spacesPanel = new SpacesPanelWithoutPreview(settings);
+    if (spacesPanel.hasSomethingToShow()) {
+      return spacesPanel;
+    }
+    Disposer.dispose(spacesPanel);
+    return null;
+  }
+
   public JComponent getPreferredFocusedComponent() {
-    return mySpacesPanel.getPreferredFocusedComponent();
+    return mySpacesPanel != null ? mySpacesPanel.getPreferredFocusedComponent() 
+                                 : myWrappingPanel.getPreferredFocusedComponent();
   }
 
   public static CodeStyleSettingsCodeFragmentFilter.CodeStyleSettingsToShow calcSettingNamesToShow(CodeStyleSettingsCodeFragmentFilter filter) {
@@ -97,7 +116,8 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
         return true;
       }
     }
-    return false;
+
+    return !provider.getSupportedFields().isEmpty();
   }
 
   private void reformatSelectedTextWithNewSettings() {
@@ -129,6 +149,10 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
     @Override
     protected void init() {
       List<String> settingNames = mySettingsToShow.getSettings(getSettingsType());
+      if (settingNames.isEmpty()) {
+        settingNames = mySettingsToShow.getOtherSetting();
+      }
+      
       String[] names = ContainerUtil.toArray(settingNames, new String[settingNames.size()]);
       showStandardOptions(names);
       initTables();
@@ -149,6 +173,10 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
       isFirstUpdate = false;
     }
     
+    public boolean hasSomethingToShow() {
+      return !myKeys.isEmpty();
+    }
+    
     @Override
     public JComponent getPanel() {
       return myPanel;
@@ -174,6 +202,10 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
     @Override
     protected void init() {
       Collection<String> settingNames = mySettingsToShow.getSettings(getSettingsType());
+      if (settingNames.isEmpty()) {
+        settingNames = mySettingsToShow.getOtherSetting();
+      }
+      
       initTables();
 
       Collection<String> fields = populateWithAssociatedFields(settingNames);
@@ -186,7 +218,7 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
       JBScrollPane scrollPane = new JBScrollPane(myTreeTable) {
         @Override
         public Dimension getMinimumSize() {
-          return super.getPreferredSize();
+          return myTreeTable.getPreferredSize();
         }
       };
 
@@ -229,5 +261,9 @@ class CodeFragmentCodeStyleSettingsPanel extends TabbedLanguageCodeStylePanel {
     protected String getPreviewText() {
       return null;
     }
+
+    public JComponent getPreferredFocusedComponent() {
+      return myTreeTable;
+    }
   }
 }
index f77ac709fed57c3f70f8194765ad8f96234f5ae8..ef3b4cf248de8f49d4a278ead91aee3ef7900cbe 100644 (file)
@@ -18,6 +18,7 @@ package com.intellij.formatting.contextConfiguration;
 import com.intellij.application.options.codeStyle.CodeStyleSchemesModel;
 import com.intellij.codeInsight.CodeInsightBundle;
 import com.intellij.codeInsight.intention.IntentionAction;
+import com.intellij.internal.statistic.UsageTrigger;
 import com.intellij.lang.Language;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
@@ -28,7 +29,6 @@ import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.ui.OptionAction;
-import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.openapi.util.text.StringUtil;
@@ -47,7 +47,8 @@ import static com.intellij.psi.codeStyle.CodeStyleSettingsCodeFragmentFilter.Cod
 
 public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction {
   private static final Logger LOG = Logger.getInstance(ConfigureCodeStyleOnSelectedFragment.class);
-  
+  private static final String ID = "configure.code.style.on.selected.fragment";
+
   @Nls
   @NotNull
   @Override
@@ -78,6 +79,7 @@ public class ConfigureCodeStyleOnSelectedFragment implements IntentionAction {
 
   @Override
   public void invoke(@NotNull final Project project, final Editor editor, final PsiFile file) throws IncorrectOperationException {
+    UsageTrigger.trigger(ID);
     SelectedTextFormatter textFormatter = new SelectedTextFormatter(project, editor, file);
     CodeStyleSettingsToShow settingsToShow = calculateAffectingSettings(editor, file);
     CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(project);
index 6782c8cc545e8bd80230f84c8f279b65ef3c1fe6..683b0e2557abe0427de44eaedc53fddec236639a 100644 (file)
@@ -54,7 +54,6 @@ import com.intellij.ui.ColorUtil;
 import com.intellij.ui.JBColor;
 import com.intellij.ui.RetrievableIcon;
 import com.intellij.util.PlatformIcons;
-import com.intellij.util.containers.WeakHashMap;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -69,7 +68,7 @@ public class Bookmark implements Navigatable, Comparable<Bookmark> {
   private final VirtualFile myFile;
   @NotNull private OpenFileDescriptor myTarget;
   private final Project myProject;
-  private WeakHashMap<Document, Reference<RangeHighlighterEx>> myHighlighterRefs;
+  private Reference<RangeHighlighterEx> myHighlighterRef;
 
   private String myDescription;
   private char myMnemonic = 0;
@@ -135,10 +134,7 @@ public class Bookmark implements Navigatable, Comparable<Bookmark> {
     else {
       highlighter = null;
     }
-    if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();
-    if (highlighter != null) {
-      myHighlighterRefs.put(markup.getDocument(), new WeakReference<RangeHighlighterEx>(highlighter));
-    }
+    myHighlighterRef = highlighter == null ? null : new WeakReference<RangeHighlighterEx>(highlighter);
     return highlighter;
   }
 
@@ -148,7 +144,6 @@ public class Bookmark implements Navigatable, Comparable<Bookmark> {
   }
 
   public void release() {
-    try {
       int line = getLine();
       if (line < 0) {
         return;
@@ -160,18 +155,15 @@ public class Bookmark implements Navigatable, Comparable<Bookmark> {
       if (markupDocument.getLineCount() <= line) return;
       RangeHighlighterEx highlighter = findMyHighlighter();
       if (highlighter != null) {
+        myHighlighterRef = null;
         highlighter.dispose();
       }
-    } finally {
-      myHighlighterRefs = null;
-    }
   }
 
   private RangeHighlighterEx findMyHighlighter() {
     final Document document = getDocument();
     if (document == null) return null;
-    Reference<RangeHighlighterEx> reference = myHighlighterRefs != null ? myHighlighterRefs.get(document) : null;
-    RangeHighlighterEx result = SoftReference.dereference(reference);
+    RangeHighlighterEx result = SoftReference.dereference(myHighlighterRef);
     if (result != null) {
       return result;
     }
@@ -190,10 +182,7 @@ public class Bookmark implements Navigatable, Comparable<Bookmark> {
       return true;
     });
     result = found.get();
-    if (result != null) {
-      if (myHighlighterRefs == null) myHighlighterRefs = new WeakHashMap<>();
-      myHighlighterRefs.put(document, new WeakReference<RangeHighlighterEx>(result));
-    }
+    myHighlighterRef = result == null ? null : new WeakReference<RangeHighlighterEx>(result);
     return result;
   }
 
index 62f5c3790d2e8dc316f205f63a7d93738d44b99a..a0b5a1de95fbbe31ff3bacde969d3c23baa01d09 100644 (file)
  */
 package com.intellij.ide.fileTemplates.impl;
 
-import com.intellij.openapi.components.PersistentStateComponent;
 import com.intellij.openapi.components.State;
 import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.project.ProjectManager;
-import org.jdom.Element;
-import org.jetbrains.annotations.Nullable;
+import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author Dmitry Avdeev
@@ -30,19 +28,9 @@ import org.jetbrains.annotations.Nullable;
   storages = @Storage(FileTemplateSettings.EXPORTABLE_SETTINGS_FILE),
   additionalExportFile = FileTemplatesLoader.TEMPLATES_DIR
 )
-public class ExportableFileTemplateSettings implements PersistentStateComponent<Element> {
-  @Nullable
-  @Override
-  public Element getState() {
-    return getSettingInstance().getState();
-  }
-
-  @Override
-  public void loadState(Element state) {
-    getSettingInstance().loadState(state);
-  }
+public class ExportableFileTemplateSettings extends FileTemplateSettings {
 
-  private static FileTemplateSettings getSettingInstance() {
-    return FileTemplateSettings.getInstance(ProjectManager.getInstance().getDefaultProject());
+  public ExportableFileTemplateSettings(@NotNull FileTypeManagerEx typeManager) {
+    super(typeManager);
   }
 }
index a80f45eaf824ceccd0944df9bcc6d1b07303621c..0d74f3be97f73b2c0ff34c3e36d5e222b8663376 100644 (file)
@@ -23,10 +23,7 @@ import com.intellij.ide.fileTemplates.FileTemplatesScheme;
 import com.intellij.ide.fileTemplates.InternalTemplateBean;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ApplicationNamesInfo;
-import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.State;
-import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.components.StoragePathMacros;
+import com.intellij.openapi.components.*;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
@@ -56,58 +53,29 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   private final State myState = new State();
   private final FileTypeManagerEx myTypeManager;
+  private final FileTemplateSettings myProjectSettings;
+  private final ExportableFileTemplateSettings myDefaultSettings;
   private final Project myProject;
 
-  /** Null for default project. */
-  @Nullable
   private final FileTemplatesScheme myProjectScheme;
   private FileTemplatesScheme myScheme = FileTemplatesScheme.DEFAULT;
   private boolean myInitialized;
 
-  private final FTManager myInternalTemplatesManager;
-  private final FTManager myDefaultTemplatesManager;
-  private final FTManager myPatternsManager;
-  private final FTManager myCodeTemplatesManager;
-  private final FTManager myJ2eeTemplatesManager;
-  private final FTManager[] myAllManagers;
-  private final URL myDefaultTemplateDescription;
-  private final URL myDefaultIncludeDescription;
-
-  public static FileTemplateManagerImpl getInstanceImpl(Project project) {
+  public static FileTemplateManagerImpl getInstanceImpl(@NotNull Project project) {
     return (FileTemplateManagerImpl)getInstance(project);
   }
 
   public FileTemplateManagerImpl(@NotNull FileTypeManagerEx typeManager,
-                                 FileTemplatesLoader loader,
+                                 FileTemplateSettings projectSettings,
+                                 ExportableFileTemplateSettings defaultSettings,
                                  /*need this to ensure disposal of the service _after_ project manager*/
                                  @SuppressWarnings("UnusedParameters") ProjectManager pm,
                                  final Project project) {
     myTypeManager = typeManager;
+    myProjectSettings = projectSettings;
+    myDefaultSettings = defaultSettings;
     myProject = project;
 
-    myInternalTemplatesManager = loader.getInternalTemplatesManager();
-    myDefaultTemplatesManager = loader.getDefaultTemplatesManager();
-    myPatternsManager = loader.getPatternsManager();
-    myCodeTemplatesManager = loader.getCodeTemplatesManager();
-    myJ2eeTemplatesManager = loader.getJ2eeTemplatesManager();
-    myAllManagers = new FTManager[] { myInternalTemplatesManager, myDefaultTemplatesManager, myPatternsManager, myCodeTemplatesManager, myJ2eeTemplatesManager };
-
-    myDefaultTemplateDescription = loader.getDefaultTemplateDescription();
-    myDefaultIncludeDescription = loader.getDefaultIncludeDescription();
-
-    if (ApplicationManager.getApplication().isUnitTestMode()) {
-      for (String tname : Arrays.asList("Class", "AnnotationType", "Enum", "Interface")) {
-        for (FileTemplate template : myInternalTemplatesManager.getAllTemplates(true)) {
-          if (tname.equals(template.getName())) {
-            myInternalTemplatesManager.removeTemplate(((FileTemplateBase)template).getQualifiedName());
-            break;
-          }
-        }
-        final FileTemplateBase template = myInternalTemplatesManager.addTemplate(tname, "java");
-        template.setText(normalizeText(getTestClassTemplateText(tname)));
-      }
-    }
-
     myProjectScheme = project.isDefault() ? null : new FileTemplatesScheme("Project") {
       @NotNull
       @Override
@@ -123,6 +91,10 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
     };
   }
 
+  private FileTemplateSettings getSettings() {
+      return myScheme == FileTemplatesScheme.DEFAULT ? myDefaultSettings : myProjectSettings;
+  }
+
   @NotNull
   @Override
   public FileTemplatesScheme getCurrentScheme() {
@@ -131,7 +103,7 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   @Override
   public void setCurrentScheme(@NotNull FileTemplatesScheme scheme) {
-    for (FTManager child : myAllManagers) {
+    for (FTManager child : getAllManagers()) {
       child.saveTemplates();
     }
     setScheme(scheme);
@@ -139,7 +111,7 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   private void setScheme(@NotNull FileTemplatesScheme scheme) {
     myScheme = scheme;
-    for (FTManager manager : myAllManagers) {
+    for (FTManager manager : getAllManagers()) {
       manager.setScheme(scheme);
     }
     myInitialized = true;
@@ -172,25 +144,25 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
   @Override
   @NotNull
   public FileTemplate[] getAllTemplates() {
-    final Collection<FileTemplateBase> templates = myDefaultTemplatesManager.getAllTemplates(false);
+    final Collection<FileTemplateBase> templates = getSettings().getDefaultTemplatesManager().getAllTemplates(false);
     return templates.toArray(new FileTemplate[templates.size()]);
   }
 
   @Override
   public FileTemplate getTemplate(@NotNull String templateName) {
-    return myDefaultTemplatesManager.findTemplateByName(templateName);
+    return getSettings().getDefaultTemplatesManager().findTemplateByName(templateName);
   }
 
   @Override
   @NotNull
   public FileTemplate addTemplate(@NotNull String name, @NotNull String extension) {
-    return myDefaultTemplatesManager.addTemplate(name, extension);
+    return getSettings().getDefaultTemplatesManager().addTemplate(name, extension);
   }
 
   @Override
   public void removeTemplate(@NotNull FileTemplate template) {
     final String qName = ((FileTemplateBase)template).getQualifiedName();
-    for (FTManager manager : myAllManagers) {
+    for (FTManager manager : getAllManagers()) {
       manager.removeTemplate(qName);
     }
   }
@@ -255,7 +227,7 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
   }
 
   private void validateRecentNames() {
-    final Collection<FileTemplateBase> allTemplates = myDefaultTemplatesManager.getAllTemplates(false);
+    final Collection<FileTemplateBase> allTemplates = getSettings().getDefaultTemplatesManager().getAllTemplates(false);
     final List<String> allNames = new ArrayList<>(allTemplates.size());
     for (FileTemplate fileTemplate : allTemplates) {
       allNames.add(fileTemplate.getName());
@@ -285,7 +257,7 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
       }
       else {
         final String text = normalizeText(getDefaultClassTemplateText(templateName));
-        template = myInternalTemplatesManager.addTemplate(templateName, "java");
+        template = getSettings().getInternalTemplatesManager().addTemplate(templateName, "java");
         template.setText(text);
       }
     }
@@ -294,18 +266,17 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   @Override
   public FileTemplate findInternalTemplate(@NotNull @NonNls String templateName) {
-    LOG.assertTrue(myInternalTemplatesManager != null);
-    FileTemplateBase template = myInternalTemplatesManager.findTemplateByName(templateName);
+    FileTemplateBase template = getSettings().getInternalTemplatesManager().findTemplateByName(templateName);
 
     if (template == null) {
       // todo: review the hack and try to get rid of this weird logic completely
-      template = myDefaultTemplatesManager.findTemplateByName(templateName);
+      template = getSettings().getDefaultTemplatesManager().findTemplateByName(templateName);
     }
     return template;
   }
 
   @NotNull
-  private static String normalizeText(@NotNull String text) {
+  public static String normalizeText(@NotNull String text) {
     text = StringUtil.convertLineSeparators(text);
     text = StringUtil.replace(text, "$NAME$", "${NAME}");
     text = StringUtil.replace(text, "$PACKAGE_NAME$", "${PACKAGE_NAME}");
@@ -315,12 +286,6 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
     return text;
   }
 
-  @NonNls
-  @NotNull
-  private String getTestClassTemplateText(@NotNull @NonNls String templateName) {
-    return "package $PACKAGE_NAME$;\npublic " + internalTemplateToSubject(templateName) + " $NAME$ { }";
-  }
-
   @Override
   @NotNull
   public String internalTemplateToSubject(@NotNull @NonNls String templateName) {
@@ -348,12 +313,12 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   @Override
   public FileTemplate getCodeTemplate(@NotNull @NonNls String templateName) {
-    return getTemplateFromManager(templateName, myCodeTemplatesManager);
+    return getTemplateFromManager(templateName, getSettings().getCodeTemplatesManager());
   }
 
   @Override
   public FileTemplate getJ2eeTemplate(@NotNull @NonNls String templateName) {
-    return getTemplateFromManager(templateName, myJ2eeTemplatesManager);
+    return getTemplateFromManager(templateName, getSettings().getJ2eeTemplatesManager());
   }
 
   @Nullable
@@ -380,7 +345,7 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
   public FileTemplate getDefaultTemplate(@NotNull final String name) {
     final String templateQName = myTypeManager.getExtension(name).isEmpty()? FileTemplateBase.getQualifiedName(name, "java") : name;
 
-    for (FTManager manager : myAllManagers) {
+    for (FTManager manager : getAllManagers()) {
       final FileTemplateBase template = manager.getTemplate(templateQName);
       if (template instanceof BundledFileTemplate) {
         final BundledFileTemplate copy = ((BundledFileTemplate)template).clone();
@@ -397,32 +362,32 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
   @Override
   @NotNull
   public FileTemplate[] getAllPatterns() {
-    final Collection<FileTemplateBase> allTemplates = myPatternsManager.getAllTemplates(false);
+    final Collection<FileTemplateBase> allTemplates = getSettings().getPatternsManager().getAllTemplates(false);
     return allTemplates.toArray(new FileTemplate[allTemplates.size()]);
   }
 
   @Override
   public FileTemplate getPattern(@NotNull String name) {
-    return myPatternsManager.findTemplateByName(name);
+    return getSettings().getPatternsManager().findTemplateByName(name);
   }
 
   @Override
   @NotNull
   public FileTemplate[] getAllCodeTemplates() {
-    final Collection<FileTemplateBase> templates = myCodeTemplatesManager.getAllTemplates(false);
+    final Collection<FileTemplateBase> templates = getSettings().getCodeTemplatesManager().getAllTemplates(false);
     return templates.toArray(new FileTemplate[templates.size()]);
   }
 
   @Override
   @NotNull
   public FileTemplate[] getAllJ2eeTemplates() {
-    final Collection<FileTemplateBase> templates = myJ2eeTemplatesManager.getAllTemplates(false);
+    final Collection<FileTemplateBase> templates = getSettings().getJ2eeTemplatesManager().getAllTemplates(false);
     return templates.toArray(new FileTemplate[templates.size()]);
   }
 
   @Override
   public void setTemplates(@NotNull String templatesCategory, @NotNull Collection<FileTemplate> templates) {
-    for (FTManager manager : myAllManagers) {
+    for (FTManager manager : getAllManagers()) {
       if (templatesCategory.equals(manager.getName())) {
         manager.updateTemplates(templates);
         manager.saveTemplates();
@@ -433,17 +398,17 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
 
   @Override
   public void saveAllTemplates() {
-    for (FTManager manager : myAllManagers) {
+    for (FTManager manager : getAllManagers()) {
       manager.saveTemplates();
     }
   }
 
   public URL getDefaultTemplateDescription() {
-    return myDefaultTemplateDescription;
+    return myDefaultSettings.getDefaultTemplateDescription();
   }
 
   public URL getDefaultIncludeDescription() {
-    return myDefaultIncludeDescription;
+    return myDefaultSettings.getDefaultIncludeDescription();
   }
 
   private Date myTestDate;
@@ -464,12 +429,11 @@ public class FileTemplateManagerImpl extends FileTemplateManager implements Pers
   public void loadState(State state) {
     XmlSerializerUtil.copyBean(state, myState);
     FileTemplatesScheme scheme = myProjectScheme != null && myProjectScheme.getName().equals(state.SCHEME) ? myProjectScheme : FileTemplatesScheme.DEFAULT;
-    FileTemplateSettings.getInstance(scheme.getProject());
     setScheme(scheme);
   }
 
-  FTManager[] getAllManagers() {
-    return myAllManagers;
+  private FTManager[] getAllManagers() {
+    return getSettings().getAllManagers();
   }
 
   public static class State {
index 17e0a2428cfdb286c23b40633b993203a264bda4..51078bdb77c2b52f5db13962f5c67fc84fb5d955 100644 (file)
 package com.intellij.ide.fileTemplates.impl;
 
 import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.components.State;
 import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.project.Project;
+import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
 import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.util.List;
@@ -35,7 +35,7 @@ import java.util.Locale;
   name = "ExportableFileTemplateSettings",
   storages = @Storage(FileTemplateSettings.EXPORTABLE_SETTINGS_FILE)
 )
-public class FileTemplateSettings implements PersistentStateComponent<Element> {
+public class FileTemplateSettings extends FileTemplatesLoader implements PersistentStateComponent<Element> {
   public final static String EXPORTABLE_SETTINGS_FILE = "file.template.settings.xml";
 
   static final String ELEMENT_TEMPLATE = "template";
@@ -43,15 +43,9 @@ public class FileTemplateSettings implements PersistentStateComponent<Element> {
   static final String ATTRIBUTE_REFORMAT = "reformat";
   static final String ATTRIBUTE_LIVE_TEMPLATE = "live-template-enabled";
   static final String ATTRIBUTE_ENABLED = "enabled";
-  private final Project myProject;
 
-  public FileTemplateSettings(Project project) {
-    myProject = project;
-  }
-
-
-  static FileTemplateSettings getInstance(Project project) {
-    return ServiceManager.getService(project, FileTemplateSettings.class);
+  public FileTemplateSettings(@NotNull FileTypeManagerEx typeManager) {
+    super(typeManager);
   }
 
   @Nullable
@@ -91,10 +85,6 @@ public class FileTemplateSettings implements PersistentStateComponent<Element> {
     return element;
   }
 
-  private FTManager[] getAllManagers() {
-    return FileTemplateManagerImpl.getInstanceImpl(myProject).getAllManagers();
-  }
-
   @Override
   public void loadState(Element state) {
     doLoad(state);
index ecca89f3567902412a9218b30b5cb36007c6e5a6..99fca776c27478bb6f9e2ff1569af4321e42bd36 100644 (file)
@@ -29,6 +29,7 @@ import com.intellij.openapi.application.ApplicationBundle;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ApplicationNamesInfo;
 import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider;
 import com.intellij.openapi.project.DumbModePermission;
 import com.intellij.openapi.project.DumbService;
 import com.intellij.openapi.project.Project;
@@ -189,13 +190,14 @@ public class DeleteHandler {
       }
     }
 
-    CommandProcessor.getInstance().executeCommand(project, () -> {
+    CommandProcessor.getInstance().executeCommand(project, () -> NonProjectFileWritingAccessProvider.disableChecksDuring(() -> {
       Collection<PsiElement> directories = ContainerUtil.newSmartList();
       for (PsiElement e : elements) {
         if (e instanceof PsiFileSystemItem && e.getParent() != null) {
           directories.add(e.getParent());
         }
       }
+
       if (!CommonRefactoringUtil.checkReadOnlyStatus(project, Arrays.asList(elements), directories, false)) {
         return;
       }
@@ -263,7 +265,7 @@ public class DeleteHandler {
           }
         });
       }
-    }, RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
+    }), RefactoringBundle.message("safe.delete.command", RefactoringUIUtil.calculatePsiElementDescriptionList(elements)), null);
   }
 
   private static boolean clearReadOnlyFlag(final VirtualFile virtualFile, final Project project) {
index 957680ebe74d03dfe2e1ddfc341773bc38dd6ef4..28f76f500e59bb6d1c467f5d3cc165bdbe664080 100644 (file)
@@ -84,6 +84,7 @@ public class PsiElementModuleRenderer extends DefaultListCellRenderer{
     setText(myText);
     setBorder(BorderFactory.createEmptyBorder(0, 0, 0, UIUtil.getListCellHPadding()));
     setHorizontalTextPosition(SwingConstants.LEFT);
+    setHorizontalAlignment(SwingConstants.RIGHT); // align icon to the right
     setBackground(selected ? UIUtil.getListSelectionBackground() : UIUtil.getListBackground());
     setForeground(selected ? UIUtil.getListSelectionForeground() : UIUtil.getInactiveTextColor());
 
index 15af5e38e3e33d8a27be2b4bfb18250585207fff..aaf1a8836fb1036117e6e495c4c5f44f38b45bbb 100644 (file)
@@ -83,6 +83,12 @@ public class CodeStyleSettingsCodeFragmentFilter {
         typeToTask.put(type, task);
       }
 
+      Set<String> otherFields = myProvider.getSupportedFields();
+      final FilterFieldsTask otherFieldsTask = new FilterFieldsTask(otherFields);
+      if (!otherFields.isEmpty()) {
+        compositeTask.addTask(otherFieldsTask);
+      }
+      
       progressTask.setTask(compositeTask);
       progressTask.setMinIterationTime(10);
       ProgressManager.getInstance().run(progressTask);
@@ -93,6 +99,11 @@ public class CodeStyleSettingsCodeFragmentFilter {
           FilterFieldsTask task = typeToTask.get(type);
           return task.getAffectedFields();
         }
+        
+        @Override
+        public List<String> getOtherSetting() {
+          return ContainerUtil.newArrayList(otherFieldsTask.getAffectedFields());
+        }
       };
     }
     finally {
@@ -208,6 +219,8 @@ public class CodeStyleSettingsCodeFragmentFilter {
 
   public interface CodeStyleSettingsToShow {
     List<String> getSettings(LanguageCodeStyleSettingsProvider.SettingsType type);
+
+    List<String> getOtherSetting();
   }
 }
 
index 9d98ba26c2937170b5f603e8932d40341058efe6..2228187ddcd2d8e7985d7b162fafee79fb99360f 100644 (file)
@@ -68,7 +68,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
                                                boolean currentSelection,
                                                boolean usageView,
                                                boolean showEmptyScopes) {
-    Collection<SearchScope> result = showEmptyScopes ? ContainerUtil.newArrayList() : ContainerUtil.newLinkedHashSet();
+    Collection<SearchScope> result = ContainerUtil.newLinkedHashSet();
     result.add(GlobalSearchScope.projectScope(project));
     if (suggestSearchInLibs) {
       result.add(GlobalSearchScope.allScope(project));
@@ -90,8 +90,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
     final Editor selectedTextEditor = ApplicationManager.getApplication().isDispatchThread()
                                       ? FileEditorManager.getInstance(project).getSelectedTextEditor()
                                       : null;
-    final PsiFile psiFile =
-      (selectedTextEditor != null) ? PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument()) : null;
+    PsiFile psiFile = selectedTextEditor == null ? null : PsiDocumentManager.getInstance(project).getPsiFile(selectedTextEditor.getDocument());
     PsiFile currentFile = psiFile;
 
     if (dataContext != null) {
@@ -136,7 +135,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
           if (endElement != null) {
             final PsiElement parent = PsiTreeUtil.findCommonParent(startElement, endElement);
             if (parent != null) {
-              final List<PsiElement> elements = new ArrayList<PsiElement>();
+              final List<PsiElement> elements = new ArrayList<>();
               final PsiElement[] children = parent.getChildren();
               TextRange selection = new TextRange(start, end);
               for (PsiElement child : children) {
@@ -162,13 +161,12 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
       if (selectedUsageView != null && !selectedUsageView.isSearchInProgress()) {
         final Set<Usage> usages = ContainerUtil.newTroveSet(selectedUsageView.getUsages());
         usages.removeAll(selectedUsageView.getExcludedUsages());
-        final List<PsiElement> results = new ArrayList<PsiElement>(usages.size());
 
         if (prevSearchFiles) {
           final Set<VirtualFile> files = collectFiles(usages, true);
           if (!files.isEmpty()) {
             GlobalSearchScope prev = new GlobalSearchScope(project) {
-              private Set<VirtualFile> myFiles = null;
+              private Set<VirtualFile> myFiles;
 
               @NotNull
               @Override
@@ -203,6 +201,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
           }
         }
         else {
+          final List<PsiElement> results = new ArrayList<>(usages.size());
           for (Usage usage : usages) {
             if (usage instanceof PsiElementUsage) {
               final PsiElement element = ((PsiElementUsage)usage).getElement();
@@ -294,7 +293,7 @@ public class PredefinedSearchScopeProviderImpl extends PredefinedSearchScopeProv
   }
 
   protected static Set<VirtualFile> collectFiles(Set<Usage> usages, boolean findFirst) {
-    final Set<VirtualFile> files = new HashSet<VirtualFile>();
+    final Set<VirtualFile> files = new HashSet<>();
     for (Usage usage : usages) {
       if (usage instanceof PsiElementUsage) {
         PsiElement psiElement = ((PsiElementUsage)usage).getElement();
index 2e3883f9e1c6e2ef5fbed43d0a2593ad19844657..c9b4f8710d7a438868c0754fb7c11c0c1320e058 100644 (file)
@@ -19,6 +19,7 @@ package com.intellij.refactoring.safeDelete;
 import com.intellij.ide.IdeBundle;
 import com.intellij.ide.util.DeleteUtil;
 import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider;
 import com.intellij.openapi.help.HelpManager;
 import com.intellij.openapi.project.DumbModePermission;
 import com.intellij.openapi.project.DumbService;
@@ -201,11 +202,14 @@ public class SafeDeleteDialog extends DialogWrapper {
     }
 
     DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, () -> {
-      if (myCallback != null && isSafeDelete()) {
-        myCallback.run(SafeDeleteDialog.this);
-      } else {
-        SafeDeleteDialog.super.doOKAction();
-      }
+      NonProjectFileWritingAccessProvider.disableChecksDuring(() -> {
+        if (myCallback != null && isSafeDelete()) {
+          myCallback.run(SafeDeleteDialog.this);
+        }
+        else {
+          SafeDeleteDialog.super.doOKAction();
+        }
+      });
     });
 
     final RefactoringSettings refactoringSettings = RefactoringSettings.getInstance();
index 719b0eef935461c6045f0e9beafaf16d493580dd..d01b7d8a3255b2a4b65667ca04d4521f08332c0a 100644 (file)
@@ -57,7 +57,8 @@ public class FileColorsModel implements Cloneable {
   static {
     predefinedScopeNameToPropertyKey = new THashMap<String, String>();
     predefinedScopeNameToPropertyKey.put(NonProjectFilesScope.NAME, "file.colors.enable.non.project");
-    if (PlatformUtils.isIntelliJ() || PlatformUtils.isRubyMine()) {
+    // These IDEs have TestScope registered (via PackagesScopesProvider or TestScopeProvider)
+    if (PlatformUtils.isIntelliJ() || PlatformUtils.isRubyMine() || PlatformUtils.isPhpStorm() || PlatformUtils.isWebStorm()) {
         predefinedScopeNameToPropertyKey.put(TestsScope.NAME, "file.colors.enable.tests");
     }
 
index 0be25906c1b28f5f1ef3813e3dce9506d6033ee7..1d3a8a7bc364c67ba0b9a0e2c6feaf5d75b4be92 100644 (file)
@@ -2003,7 +2003,6 @@ public class FileBasedIndexImpl extends FileBasedIndex {
 
     private UnindexedFilesFinder(@Nullable ProgressIndicator indicator) {
       myProgressIndicator = indicator;
-      if (!myInitialized) waitUntilIndicesAreInitialized();
     }
 
     @NotNull
index ca0d41c73428c55b441e5224e56c6f649c7c50f1..c554aae210f705b5848af9e6c8af1b9e2525369d 100644 (file)
@@ -24,6 +24,7 @@ import com.intellij.openapi.options.SettingsEditor;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.*;
 import com.intellij.ui.components.JBList;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.ui.FormBuilder;
 import com.intellij.util.ui.GridBag;
 import com.intellij.util.ui.UIUtil;
@@ -33,6 +34,8 @@ import javax.swing.*;
 import javax.swing.event.DocumentEvent;
 import java.awt.*;
 import java.awt.event.MouseEvent;
+import java.util.Arrays;
+import java.util.Set;
 
 /**
  * @author Yura Cangea, dsl
@@ -92,21 +95,27 @@ public class CustomFileTypeEditor extends SettingsEditor<AbstractFileType> {
       mySupportParens.setSelected(table.isHasParens());
       mySupportEscapes.setSelected(table.isHasStringEscapes());
 
-      for (String s : table.getKeywords1()) {
+      for (String s : sorted(table.getKeywords1())) {
         myKeywordModels[0].addElement(s);
       }
-      for (String s : table.getKeywords2()) {
+      for (String s : sorted(table.getKeywords2())) {
         myKeywordModels[1].addElement(s);
       }
-      for (String s : table.getKeywords3()) {
+      for (String s : sorted(table.getKeywords3())) {
         myKeywordModels[2].addElement(s);
       }
-      for (String s : table.getKeywords4()) {
+      for (String s : sorted(table.getKeywords4())) {
         myKeywordModels[3].addElement(s);
       }
     }
   }
 
+  private static String[] sorted(Set<String> keywords) {
+    String[] strings = ArrayUtil.toStringArray(keywords);
+    Arrays.sort(strings);
+    return strings;
+  }
+
   @Override
   public void applyEditorTo(AbstractFileType type) throws ConfigurationException {
     if (myFileTypeName.getText().trim().length() == 0) {
index a719954e09204d84a4621e920d4312c73bdfd3e4..a0bc57dfa76cd951b3ecaf13614bcd0acdfa346c 100644 (file)
@@ -38,8 +38,6 @@ import java.awt.*;
 public abstract class AbstractUpdateDialog extends DialogWrapper {
   private final boolean myEnableLink;
 
-  protected String myLicenseInfo = null;
-
   protected AbstractUpdateDialog(boolean enableLink) {
     super(true);
     myEnableLink = enableLink;
index c02f38318e61cf41d719c0c122066c2e37b9c468..936b5c5dd69632a14409da0c46a1d935840742a8 100644 (file)
@@ -48,6 +48,7 @@ class UpdateChannel(node: Element) {
   val status: ChannelStatus = ChannelStatus.fromCode(node.getAttributeValue("status"))
   val licensing: String = node.getAttributeValue("licensing", LICENSING_PRODUCTION)
   val homePageUrl: String? = node.getAttributeValue("url")
+  val evalDays: Int = node.getAttributeValue("evalDays")?.toInt() ?: 30
   val builds: List<BuildInfo> = node.getChildren("build").map { BuildInfo(it) }
 
   override fun toString() = id
index c99e04ce2c841622f109aed151b3c92c9e5c2f03..8c946311e3a01590ef575e4da16c25a764d6f86e 100644 (file)
@@ -37,6 +37,7 @@ import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
+import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.io.File;
 import java.io.IOException;
@@ -56,6 +57,9 @@ class UpdateInfoDialog extends AbstractUpdateDialog {
   private final PatchInfo myPatch;
   private final boolean myWriteProtected;
 
+  private String myLicenseInfo = null;
+  private Color myLicenseInfoColor = null;
+
   UpdateInfoDialog(@NotNull UpdateChannel channel,
                    @NotNull BuildInfo newBuild,
                    @Nullable PatchInfo patch,
@@ -88,12 +92,20 @@ class UpdateInfoDialog extends AbstractUpdateDialog {
       }
       else {
         Date buildDate = build.getReleaseDate();
-        Date expiration = facade.getLicenseExpirationDate();
-        if (buildDate != null && facade.isPerpetualForProduct(buildDate)) {
-          myLicenseInfo = IdeBundle.message("updates.fallback.build");
-        }
-        else if (expiration != null && expiration.after(new Date())) {
-          myLicenseInfo = IdeBundle.message("updates.subscription.active.till", DateFormatUtil.formatAboutDialogDate(expiration));
+        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");
+          }
         }
       }
     }
@@ -255,7 +267,7 @@ class UpdateInfoDialog extends AbstractUpdateDialog {
       }
 
       if (myLicenseInfo != null) {
-        configureMessageArea(myLicenseArea, myLicenseInfo, null, null);
+        configureMessageArea(myLicenseArea, myLicenseInfo, myLicenseInfoColor, null);
       }
     }
   }
index a274e91f9fd30f2dd76a0ba74c3fca23b9320fab..acc83f362be01c94056815df78a94afe660e24c3 100644 (file)
@@ -28,11 +28,14 @@ import com.intellij.openapi.wm.impl.ToolWindowImpl;
 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.
  *
@@ -153,6 +156,13 @@ public final class RequestFocusInToolWindowCmd extends FinalizableCommand {
           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() {
index 4cc49749ac9be004e78895bf6d0efb83cbc47e5d..377dd050371f896b24ad7d5235cde177e25b4f70 100644 (file)
@@ -38,6 +38,8 @@ public abstract class LicensingFacade {
 
   public abstract boolean isEvaluationLicense();
 
+  public abstract boolean isApplicableForProduct(@NotNull Date productBuildDate);
+
   public abstract boolean isPerpetualForProduct(@NotNull Date productBuildDate);
 
   @Nullable
index 4d0415780810d3053164b80c8c82fb60780c0f3b..7377f305ada4fab51558864f3803e3afa0bb42f2 100644 (file)
@@ -913,8 +913,10 @@ updates.error.plugin.description.failed=Failed to load plugin descriptions from:
 update.notifications.title=Platform and Plugin Updates
 update.notifications.group=Platform and Plugin Updates
 updates.channel.bundled.key=The new version has an expiration date and does not require a license key.
+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.subscription.active.till=Your subscription is active until {0}.
+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 <a href=\"update\">update</a>.
 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 <a href="update">update</a>: {1}
index 9ebe7af9091f37e58bf5162e9ca61c7e89319375..267552d578145992915b637e2bc7e48d16fdae94 100644 (file)
@@ -30,7 +30,6 @@
                     serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplateManagerImpl"/>
     <projectService serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplateSettings"/>
     <applicationService serviceImplementation="com.intellij.ide.fileTemplates.impl.ExportableFileTemplateSettings"/>
-    <applicationService serviceImplementation="com.intellij.ide.fileTemplates.impl.FileTemplatesLoader"/>
 
     <applicationService serviceInterface="com.intellij.ide.PsiCopyPasteManager"
                         serviceImplementation="com.intellij.ide.PsiCopyPasteManager"/>
index 162113e6a5bd3ba0f41f0adde3d28dc7de1aa0e6..8b29d64ddb4f5a5d0d8bbd7a63cdf573ddef269c 100644 (file)
@@ -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.1479 163.1374.5 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.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
index 5c7ecdea6a1a5346b66e3502b0aee8856666277f..a19b87c8b7893f5da0cdd702566d5842185e2903 100644 (file)
@@ -23,6 +23,7 @@ import com.intellij.openapi.diff.impl.patch.PatchVirtualFileReader;
 import com.intellij.openapi.diff.impl.patch.formove.PatchApplier;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
+import org.jetbrains.annotations.NotNull;
 
 import java.io.File;
 import java.io.IOException;
@@ -52,4 +53,10 @@ public abstract class PatchingTestCase extends IntegrationTestCase {
 
     new PatchApplier<BinaryFilePatch>(myProject, myRoot, patches, null, null, null).execute();
   }
+
+  protected static void createChildDataWithContent(@NotNull VirtualFile dir, @NotNull String name) throws IOException {
+    createChildData(dir, name);
+    VirtualFile file = dir.findChild(name);
+    setFileText(file, "some content");
+  }
 }
index 31face320d8124319cdd3a1689ecefb3952e9818..d36ef226fbecef161b24da2cf4ecdf727479a3c5 100644 (file)
@@ -19,14 +19,19 @@ package com.intellij.history.integration.patches;
 import com.intellij.history.core.revisions.Difference;
 import com.intellij.history.core.revisions.Revision;
 import com.intellij.history.integration.PatchingTestCase;
+import com.intellij.idea.Bombed;
 import com.intellij.openapi.vcs.changes.Change;
 import com.intellij.openapi.vfs.VirtualFile;
 
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.List;
 
 public class PatchCreatorTest extends PatchingTestCase {
-  public void testCreationPatch() throws Exception {
+
+  @Bombed(user = "Nadya Zabrodina", day = 1, month = Calendar.OCTOBER,
+    description = "Now we are not able to apply empty file creation patch; git special tag needed or smth like that")
+  public void testCreationEmptyPatch() throws Exception {
     createChildData(myRoot, "f.txt");
 
     createPatchBetweenRevisions(1, 0);
@@ -37,14 +42,14 @@ public class PatchCreatorTest extends PatchingTestCase {
   }
 
   public void testPatchBetweenTwoOldRevisions() throws Exception {
-    createChildData(myRoot, "f1.txt");
-    createChildData(myRoot, "f2.txt");
-    createChildData(myRoot, "f3.txt");
+    createChildDataWithContent(myRoot, "f1.txt");
+    createChildDataWithContent(myRoot, "f2.txt");
+    createChildDataWithContent(myRoot, "f3.txt");
 
-    createPatchBetweenRevisions(3, 1);
+    createPatchBetweenRevisions(6, 1);
     clearRoot();
     applyPatch();
-
+    myRoot.refresh(false, true);
     assertNotNull(myRoot.findChild("f1.txt"));
     assertNotNull(myRoot.findChild("f2.txt"));
     assertNull(myRoot.findChild("f3.txt"));
@@ -52,7 +57,7 @@ public class PatchCreatorTest extends PatchingTestCase {
 
   public void testRename() throws Exception {
     VirtualFile f = createChildData(myRoot, "f.txt");
-    setBinaryContent(f,new byte[]{'x'});
+    setBinaryContent(f, new byte[]{'x'});
 
     rename(f, "ff.txt");
 
@@ -67,9 +72,8 @@ public class PatchCreatorTest extends PatchingTestCase {
   }
 
   public void testReversePatch() throws Exception {
-    createChildData(myRoot, "f.txt");
-
-    createPatchBetweenRevisions(1, 0, true);
+    createChildDataWithContent(myRoot, "f.txt");
+    createPatchBetweenRevisions(2, 0, true);
     applyPatch();
 
     assertNull(myRoot.findChild("f.txt"));
@@ -77,7 +81,7 @@ public class PatchCreatorTest extends PatchingTestCase {
 
   public void testDirectoryCreationWithFiles() throws Exception {
     VirtualFile dir = createChildDirectory(myRoot, "dir");
-    createChildData(dir, "f.txt");
+    createChildDataWithContent(dir, "f.txt");
 
     createPatchBetweenRevisions(2, 0, false);
     clearRoot();
@@ -90,15 +94,15 @@ public class PatchCreatorTest extends PatchingTestCase {
 
   public void testDirectoryDeletionWithFiles() throws Exception {
     VirtualFile dir = createChildDirectory(myRoot, "dir");
-    createChildData(dir, "f1.txt");
-    createChildData(dir, "f2.txt");
+    createChildDataWithContent(dir, "f1.txt");
+    createChildDataWithContent(dir, "f2.txt");
 
     delete(dir);
     createPatchBetweenRevisions(1, 0, false);
 
     dir = createChildDirectory(myRoot, "dir");
-    createChildData(dir, "f1.txt");
-    createChildData(dir, "f2.txt");
+    createChildDataWithContent(dir, "f1.txt");
+    createChildDataWithContent(dir, "f2.txt");
 
     applyPatch();
 
@@ -109,7 +113,7 @@ public class PatchCreatorTest extends PatchingTestCase {
 
   public void testDirectoryRename() throws Exception {
     VirtualFile dir = createChildDirectory(myRoot, "dir1");
-    createChildData(dir, "f.txt");
+    createChildDataWithContent(dir, "f.txt");
 
     rename(dir, "dir2");
 
index 5cacba564cc4afc3c474ebfcfd16b3a01d6f7a33..d739ac5bf2b9238f12baf04ac77fa6f4dd533ddb 100644 (file)
@@ -23,14 +23,14 @@ import java.nio.charset.Charset;
 
 public class DirectoryHistoryDialogPatchCreationTest extends PatchingTestCase {
   public void testPatchCreation() throws Exception {
-    createChildData(myRoot, "f1.txt");
-    createChildData(myRoot, "f2.txt");
-    createChildData(myRoot, "f3.txt");
+    createChildDataWithContent(myRoot, "f1.txt");
+    createChildDataWithContent(myRoot, "f2.txt");
+    createChildDataWithContent(myRoot, "f3.txt");
 
     DirectoryHistoryDialogModel m = new DirectoryHistoryDialogModel(myProject, myGateway, getVcs(), myRoot);
-    assertSize(3, m.getRevisions());
+    assertSize(6, m.getRevisions());
 
-    m.selectRevisions(0, 2);
+    m.selectRevisions(0, 5);
     m.createPatch(patchFilePath, myProject.getBasePath(), false, Charset.defaultCharset());
     clearRoot();
 
index 41d737c0751de1a9f65028ccf4a00c3b7fcd9439..f925c43f6fcba34b37816d51e732ea0f332ffffd 100644 (file)
@@ -19,6 +19,7 @@ import com.intellij.ide.fileTemplates.FileTemplate;
 import com.intellij.ide.fileTemplates.FileTemplateManager;
 import com.intellij.ide.fileTemplates.FileTemplatesScheme;
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.util.Disposer;
@@ -120,7 +121,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
       String newText = "good bye";
       template.setText(newText);
       assertEquals(newText, manager.getTemplate(TEST_TEMPLATE_TXT).getText());
-
+      manager.saveAllTemplates();
       PlatformTestUtil.saveProject(project);
       closeProject(project);
 
@@ -152,7 +153,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
       myTemplateManager.removeTemplate(template);
       assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
       myTemplateManager.setCurrentScheme(myTemplateManager.getProjectScheme());
-      assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
+      assertNotNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
       myTemplateManager.setCurrentScheme(FileTemplatesScheme.DEFAULT);
       assertNull(myTemplateManager.getTemplate(TEST_TEMPLATE_TXT));
     }
@@ -168,7 +169,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
     assertTrue(template.isReformatCode());
     template.setReformatCode(false);
 
-    FileTemplateSettings settings = FileTemplateSettings.getInstance(getProject());
+    FileTemplateSettings settings = ServiceManager.getService(ExportableFileTemplateSettings.class);
     Element state = settings.getState();
     assertNotNull(state);
     Element element = state.getChildren().get(0).getChildren().get(0);
@@ -180,7 +181,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
     assertFalse(((FileTemplateBase)myTemplateManager.getTemplate(TEST_TEMPLATE_TXT)).isLiveTemplateEnabledByDefault());
     FileTemplateBase template = (FileTemplateBase)myTemplateManager.getTemplate("templateWithLiveTemplate.txt");
     assertTrue(template.isLiveTemplateEnabledByDefault());
-    FileTemplateSettings settings = FileTemplateSettings.getInstance(getProject());
+    FileTemplateSettings settings = ServiceManager.getService(ExportableFileTemplateSettings.class);
     assertNull(settings.getState());
     template.setLiveTemplateEnabled(false);
     Element state = settings.getState();
index 66b9b617348a1044c953bd54266c7a8310ed6ae4..be20208355334a86718183be3f9f4a60c1e0a1bc 100644 (file)
@@ -26,7 +26,7 @@ import org.jetbrains.annotations.NotNull;
  * By default, IntelliJ Platform considers files as tests only if they are located under test
  * sources root {@link FileIndex#isInTestSourceContent(VirtualFile)}.
  * <p>
- * However there plenty frameworks and languages which keep test files just nearby production files.
+ * However there are plenty frameworks and languages which keep test files just nearby production files.
  * E.g. *_test.go files are test files in Go language and some js/dart files are test files depending
  * on their content. The extensions allow IDE to highlight such files with a green background,
  * properly check if they are included in built-in search scopes, etc.
@@ -35,7 +35,6 @@ import org.jetbrains.annotations.NotNull;
  * @since 2016.3
  * @author zolotov
  */
-
 public abstract class TestSourcesFilter {
   public static final ExtensionPointName<TestSourcesFilter> EP_NAME = ExtensionPointName.create("com.intellij.testSourcesFilter");
 
index 6023eea89f706356a3e63b1ad8a8da3261e4b1d1..c7b6d8aa2d58e6eb98503bfd1dafc74bb8b2c1ba 100644 (file)
  */
 package com.intellij.util.containers;
 
+import com.intellij.util.ArrayFactory;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.text.StringFactory;
-
-import java.util.ArrayList;
+import org.jetbrains.annotations.NotNull;
 
 public class CharTrie {
-  private ArrayList<Node> myAllNodes;
-
-  private static class Node {
-    private final char myChar;
-    private final int myParent;
-    private IntArrayList myChildren;
-
-    Node(int parent, char c) {
-      myChar = c;
-      myParent = parent;
-    }
-  }
+  private int myAllNodesSize;
+  private char[] myAllNodesChars;
+  private char[] myAllNodesParents; // unsigned short
+  private char[][] myAllNodesChildren; // unsigned short
 
   public CharTrie() {
     init();
   }
 
   private void init() {
-    myAllNodes = new ArrayList<Node>();
-    final Node root = new Node(-1, (char)0);
-    myAllNodes.add(root);
+    myAllNodesChars = null;
+    myAllNodesParents = null;
+    myAllNodesChildren = null;
+    myAllNodesSize = 0;
+    addNode(-1, (char)0);
+  }
+
+  private void addNode(int parentIndex, char ch) {
+    if (myAllNodesSize == 0) {
+      int initialCapacity = 10;
+      myAllNodesChars = new char[initialCapacity];
+      myAllNodesParents = new char[initialCapacity];
+      myAllNodesChildren = new char[initialCapacity][];
+    } else if (myAllNodesSize >= myAllNodesChars.length) {
+      int increment = Math.max(myAllNodesSize >> 2, 10);
+
+      int newSize = myAllNodesSize + increment;
+      myAllNodesChars = ArrayUtil.realloc(myAllNodesChars, newSize);
+      myAllNodesParents = ArrayUtil.realloc(myAllNodesParents, newSize);
+      myAllNodesChildren = ArrayUtil.realloc(myAllNodesChildren, newSize, FACTORY);
+    }
+
+    myAllNodesChars[myAllNodesSize] = ch;
+    myAllNodesParents[myAllNodesSize] = (char)parentIndex;
+    myAllNodesChildren[myAllNodesSize] = null;
+    ++myAllNodesSize;
+    assert myAllNodesSize < Character.MAX_VALUE;
   }
 
   public int size() {
-    return myAllNodes.size();
+    return myAllNodesSize;
   }
 
   /**
@@ -98,18 +115,16 @@ public class CharTrie {
     int length = 0;
     int run = hashCode;
     while (run > 0) {
-      final CharTrie.Node node = myAllNodes.get(run);
       length++;
-      run = node.myParent;
+      run = myAllNodesParents[run];
     }
 
     char[] result = new char[length];
     run = hashCode;
     for (int i = 0; i < length; i++) {
       assert run > 0;
-      final CharTrie.Node node = myAllNodes.get(run);
-      result[length - i - 1] = node.myChar;
-      run = node.myParent;
+      result[length - i - 1] = myAllNodesChars[run];
+      run = myAllNodesParents[run];
     }
 
     return result;
@@ -131,18 +146,16 @@ public class CharTrie {
     int length = 0;
     int run = hashCode;
     while (run > 0) {
-      final CharTrie.Node node = myAllNodes.get(run);
       length++;
-      run = node.myParent;
+      run = myAllNodesParents[run];
     }
 
     char[] result = new char[length];
     run = hashCode;
     for (int i = 0; i < length; i++) {
       assert run > 0;
-      final CharTrie.Node node = myAllNodes.get(run);
-      result[i] = node.myChar;
-      run = node.myParent;
+      result[i] = myAllNodesChars[run];
+      run = myAllNodesParents[run];
     }
 
     return result;
@@ -151,23 +164,26 @@ public class CharTrie {
   public int findSubNode(int parentIndex, char c) {
     return getSubNode(parentIndex, c, false);
   }
-  
+
+  private static final int LENGTH_SLOT_LENGTH = 1;
+
   private int getSubNode(int parentIndex, char c, boolean createIfNotExists) {
-    CharTrie.Node parentNode = myAllNodes.get(parentIndex);
-    if (parentNode.myChildren == null) {
+    if (myAllNodesChildren[parentIndex] == null) {
       if (!createIfNotExists) {
         return 0;
       }
-      parentNode.myChildren = new IntArrayList(1);
+      char[] chars = new char[1 + LENGTH_SLOT_LENGTH];
+      myAllNodesChildren[parentIndex] = chars;
     }
-    IntArrayList children = parentNode.myChildren;
+
+    char[] children = myAllNodesChildren[parentIndex];
+    char childrenCount = children[children.length - LENGTH_SLOT_LENGTH];
     int left = 0;
-    int right = children.size() - 1;
+    int right = childrenCount - 1;
     while (left <= right) {
       int middle = (left + right) >> 1;
-      int index = children.get(middle);
-      CharTrie.Node node = myAllNodes.get(index);
-      int comp = node.myChar - c;
+      int index = children[middle];
+      int comp = myAllNodesChars[index] - c;
       if (comp == 0) {
         return index;
       }
@@ -181,14 +197,33 @@ public class CharTrie {
     if (!createIfNotExists) {
       return 0;
     }
-    
-    int index = myAllNodes.size();
-    children.add(left, index);
-    myAllNodes.add(new CharTrie.Node(parentIndex, c));
+
+    if (childrenCount == children.length - LENGTH_SLOT_LENGTH) {
+      children = myAllNodesChildren[parentIndex] = ArrayUtil.realloc(children, (children.length * 3 / 2 + 1) + LENGTH_SLOT_LENGTH);
+    }
+
+    if (left != childrenCount) {
+      System.arraycopy(children, left, children, left + 1, childrenCount - left);
+    }
+
+    int index = myAllNodesSize;
+    children[left] = (char)index;
+    assert childrenCount + 1 < Character.MAX_VALUE;
+    children[children.length - LENGTH_SLOT_LENGTH] = (char)(childrenCount + 1);
+
+    addNode(parentIndex, c);
     return index;
   }
 
   public void clear() {
     init();
   }
+
+  private static final ArrayFactory<char[]> FACTORY = new ArrayFactory<char[]>() {
+    @NotNull
+    @Override
+    public char[][] create(int count) {
+      return new char[count][];
+    }
+  };
 }
index cd2fe3f489f14159a59db3700958b0ae8f2f1440..7da6f919d14a718e41f047724f97f8825222621c 100644 (file)
@@ -27,7 +27,6 @@ import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.RandomAccessFile;
 import java.lang.reflect.Field;
@@ -334,43 +333,14 @@ public class PagedFileStorage implements Forceable {
 
     final long started = IOStatistics.DEBUG ? System.currentTimeMillis():0;
     myStorageLockContext.myStorageLock.invalidateBuffer(myStorageIndex | (int)(oldSize / myPageSize)); // TODO long page
-
     final long unmapAllFinished = IOStatistics.DEBUG ? System.currentTimeMillis():0;
 
-    mySize = -1;
+    resizeFile(newSize);
 
+    // it is not guaranteed that new partition will consist of null
+    // after resize, so we should fill it manually
     long delta = newSize - oldSize;
-
-    if (delta > 0) {
-      // it is not guaranteed that new partition will consist of null
-      // after resize, so we should fill it manually
-      byte[] buff = new byte[MAX_FILLER_SIZE];
-      Arrays.fill(buff, (byte)0);
-      FileOutputStream stream = new FileOutputStream(myFile, true);
-
-      try {
-        while (delta > 0) {
-          final int filled = Math.min((int)delta, MAX_FILLER_SIZE);
-          stream.write(buff, 0, filled);
-          delta -= filled;
-        }
-      } finally {
-        stream.getFD().sync();
-        stream.close();
-      }
-    }
-    else {
-      RandomAccessFile raf = new RandomAccessFile(myFile, RW);
-      try {
-        raf.setLength(newSize);
-        raf.getFD().sync();
-      }
-      finally {
-        raf.close();
-      }
-    }
-
-    mySize = newSize;
+    if (delta > 0) fillWithZeros(oldSize, delta);
 
     if (IOStatistics.DEBUG) {
       long finished = System.currentTimeMillis();
@@ -380,8 +350,32 @@ public class PagedFileStorage implements Forceable {
     }
   }
 
+  private void resizeFile(long newSize) throws IOException {
+    mySize = -1;
+    RandomAccessFile raf = new RandomAccessFile(myFile, RW);
+    try {
+      raf.setLength(newSize);
+    }
+    finally {
+      raf.close();
+    }
+    mySize = newSize;
+  }
+
   private static final int MAX_FILLER_SIZE = 8192;
 
+  private void fillWithZeros(long from, long length) {
+    byte[] buff = new byte[MAX_FILLER_SIZE];
+    Arrays.fill(buff, (byte)0);
+
+    while (length > 0) {
+      final int filled = Math.min((int)length, MAX_FILLER_SIZE);
+      put(from, buff, 0, filled);
+      length -= filled;
+      from += filled;
+    }
+  }
+
   public final long length() {
     long size = mySize;
     if (size == -1) {
index da223902b78ec3d34a1c92e670798191388cf867..3d635f657f2804f2f045a2be97c9defacbf6b260 100644 (file)
@@ -41,7 +41,7 @@ public class GraphicsUtil {
     setupAntialiasing(g2, true, false);
   }
 
-  public static int stringWidth(String text, Font font) {
+  public static int stringWidth(@NotNull String text, Font font) {
     setupAntialiasing(ourGraphics, true, true);
     return ourGraphics.getFontMetrics(font).stringWidth(text);
   }
index cd1ec959c12bb213e0ee814dbccf6f413374dbca..9db55395370b25edf04ad37b29223a906937bc2f 100644 (file)
@@ -43,6 +43,7 @@ public class GenericPatchApplier {
   private final TreeMap<TextRange, MyAppliedData> myTransformations;
   private final List<String> myLines;
   private final List<PatchHunk> myHunks;
+  private final boolean myBaseFileEndsWithNewLine;
   private boolean myHadAlreadyAppliedMet;
 
   private final ArrayList<SplitHunk> myNotBound;
@@ -61,6 +62,7 @@ public class GenericPatchApplier {
     debug("GenericPatchApplier created, hunks: " + hunks.size());
     myLines = new ArrayList<String>();
     Collections.addAll(myLines, LineTokenizer.tokenize(text, false));
+    myBaseFileEndsWithNewLine = StringUtil.endsWithLineBreak(text);
     myHunks = hunks;
     final Comparator<TextRange> textRangeComparator =
       (o1, o2) -> new Integer(o1.getStartOffset()).compareTo(new Integer(o2.getStartOffset()));
@@ -1041,16 +1043,25 @@ public class GenericPatchApplier {
     for (SplitHunk hunk : myNotBound) {
       linesToSb(sb, hunk.getAfterAll());
     }
-    iterateTransformations(range -> linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1)), range -> {
+    iterateTransformations(range -> {
+      linesToSb(sb, myLines.subList(range.getStartOffset(), range.getEndOffset() + 1));
+      if (containsLastLine(range) && myBaseFileEndsWithNewLine) {
+        sb.append('\n');
+      }
+    }, range -> {
       final MyAppliedData appliedData = myTransformations.get(range);
       linesToSb(sb, appliedData.getList());
+      if (containsLastLine(range) && !mySuppressNewLineInEnd) {
+        sb.append('\n');
+      }
     });
-    if (! mySuppressNewLineInEnd) {
-      sb.append('\n');
-    }
     return sb.toString();
   }
 
+  private boolean containsLastLine(@NotNull TextRange range) {
+    return range.getEndOffset() == myLines.size() - 1;
+  }
+
   private static void linesToSb(final StringBuilder sb, final List<String> list) {
     if (sb.length() > 0 && !list.isEmpty()) {
       sb.append("\n");
index 900f15352b3abc78e24328ed2e8ad60afa37fbd3..96c0fe770d92ade268bbe958b75e0ed0966db73c 100644 (file)
@@ -46,9 +46,11 @@ public class VcsNotifier {
   }
 
   @NotNull
-  private static Notification createNotification(@NotNull NotificationGroup notificationGroup,
-                                                 @NotNull String title, @NotNull String message, @NotNull NotificationType type,
-                                                 @Nullable NotificationListener listener) {
+  public static Notification createNotification(@NotNull NotificationGroup notificationGroup,
+                                                @NotNull String title,
+                                                @NotNull String message,
+                                                @NotNull NotificationType type,
+                                                @Nullable NotificationListener listener) {
     // title can be empty; message can't be neither null, nor empty
     if (StringUtil.isEmptyOrSpaces(message)) {
       message = title;
@@ -59,13 +61,22 @@ public class VcsNotifier {
   }
 
   @NotNull
-  protected Notification notify(@NotNull NotificationGroup notificationGroup, @NotNull String title, @NotNull String message,
-                                @NotNull NotificationType type, @Nullable NotificationListener listener) {
+  public Notification notify(@NotNull NotificationGroup notificationGroup,
+                             @NotNull String title,
+                             @NotNull String message,
+                             @NotNull NotificationType type,
+                             @Nullable NotificationListener listener) {
     Notification notification = createNotification(notificationGroup, title, message, type, listener);
     notification.notify(myProject);
     return notification;
   }
 
+  @NotNull
+  public Notification notify(@NotNull Notification notification) {
+    notification.notify(myProject);
+    return notification;
+  }
+
   @NotNull
   public Notification notifyError(@NotNull String title, @NotNull String message) {
     return notifyError(title, message, null);
index 5cbbab3826334bfa5464212edcc60cb51dbb8b83..0834a00a530ba4732ac0068292a4d86e8c99d80c 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.vcs.log;
 
+import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.Collection;
@@ -31,7 +32,7 @@ public interface VcsLogRefs {
   Collection<VcsRef> getBranches();
 
   @NotNull
-  Collection<VcsRef> refsToCommit(int commit);
+  Collection<VcsRef> refsToCommit(@NotNull Hash hash, @NotNull VirtualFile root);
 
   @NotNull
   Collection<VcsRef> getAllRefs();
index 2c227a7235d642b7dddea2499e098cb099a2cd54..e6b47f7c32c163bd9d69a1c785abce5120036ec0 100644 (file)
@@ -134,11 +134,11 @@ public class ContainingBranchesGetter {
     PermanentGraph<Integer> graph = dataPack.getPermanentGraph();
     VcsLogRefs refs = dataPack.getRefsModel();
 
-    VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
-                                          vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
-    if (branchRef == null) return Conditions.alwaysFalse();
     ContainedInBranchCondition condition = myConditions.get(root);
     if (condition == null || !condition.getBranch().equals(branchName)) {
+      VcsRef branchRef = ContainerUtil.find(refs.getBranches(),
+                                            vcsRef -> vcsRef.getRoot().equals(root) && vcsRef.getName().equals(branchName));
+      if (branchRef == null) return Conditions.alwaysFalse();
       condition = new ContainedInBranchCondition(graph.getContainedInBranchCondition(
         Collections.singleton(myLogData.getCommitIndex(branchRef.getCommitHash(), branchRef.getRoot()))), branchName);
       myConditions.put(root, condition);
index 8cc73c9715328a8d2e8112265dbc102e7fc008bf..671181ce3e54c8a57510e881bbbd4d14f13ed331 100644 (file)
@@ -5,10 +5,7 @@ import com.google.common.collect.Iterators;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.SmartList;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.vcs.log.CommitId;
-import com.intellij.vcs.log.VcsLogHashMap;
-import com.intellij.vcs.log.VcsLogRefs;
-import com.intellij.vcs.log.VcsRef;
+import com.intellij.vcs.log.*;
 import gnu.trove.TIntObjectHashMap;
 import org.jetbrains.annotations.NotNull;
 
@@ -18,6 +15,7 @@ import java.util.stream.Collectors;
 public class RefsModel implements VcsLogRefs {
   @NotNull private final Collection<VcsRef> myBranches;
   @NotNull private final Map<VirtualFile, Set<VcsRef>> myRefs;
+  @NotNull private final VcsLogHashMap myHashMap;
   @NotNull private final TIntObjectHashMap<SmartList<VcsRef>> myRefsToHashes;
   @NotNull private final TIntObjectHashMap<VirtualFile> myRootsToHeadIndices;
 
@@ -25,6 +23,7 @@ public class RefsModel implements VcsLogRefs {
                    @NotNull final Set<Integer> heads,
                    @NotNull final VcsLogHashMap hashMap) {
     myRefs = refsByRoot;
+    myHashMap = hashMap;
 
     Iterable<VcsRef> allRefs = Iterables.concat(refsByRoot.values());
 
@@ -67,7 +66,7 @@ public class RefsModel implements VcsLogRefs {
   @NotNull
   public Collection<VcsRef> branchesToCommit(int index) {
     Collection<VcsRef> refs = refsToCommit(index);
-    return refs.stream().filter(ref -> ref.getType().isBranch()).collect(Collectors.toList());
+    return ContainerUtil.filter(refs, ref -> ref.getType().isBranch());
   }
 
   @NotNull
@@ -82,6 +81,10 @@ public class RefsModel implements VcsLogRefs {
 
   @NotNull
   @Override
+  public Collection<VcsRef> refsToCommit(@NotNull Hash hash, @NotNull VirtualFile root) {
+    return refsToCommit(myHashMap.getCommitIndex(hash, root));
+  }
+
   public Collection<VcsRef> refsToCommit(int index) {
     if (myRefsToHashes.containsKey(index)) {
       return myRefsToHashes.get(index);
@@ -102,7 +105,7 @@ public class RefsModel implements VcsLogRefs {
       @Override
       public Iterator<VcsRef> iterator() {
         List<Iterator<VcsRef>> iterators = myRefs.values().stream().map(Set::iterator).collect(Collectors.toList());
-        return Iterators.concat(iterators.toArray(new Iterator[iterators.size()]));
+        return Iterators.concat(iterators.iterator());
       }
 
       @Override
index fa0e093fe4450b7efd736222815883f88dfdff5d..ca9d80a38d409ee50b1e77eb4ec72143f81016a5 100644 (file)
 package com.intellij.vcs.log.ui;
 
 import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.Conditions;
+import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.ui.JBColor;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.vcs.log.*;
 import com.intellij.vcs.log.data.VcsLogData;
 import com.intellij.vcs.log.impl.VcsLogUtil;
@@ -24,12 +27,14 @@ import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
+import java.util.Map;
 
 public class CurrentBranchHighlighter implements VcsLogHighlighter {
   private static final JBColor CURRENT_BRANCH_BG = new JBColor(new Color(228, 250, 255), new Color(63, 71, 73));
   private static final String HEAD = "HEAD";
   @NotNull private final VcsLogData myLogData;
   @NotNull private final VcsLogUi myLogUi;
+  @NotNull private final Map<VirtualFile, Condition<CommitId>> myConditions = ContainerUtil.newHashMap();
   @Nullable private String mySingleFilteredBranch;
 
   public CurrentBranchHighlighter(@NotNull VcsLogData logData, @NotNull VcsLogUi logUi) {
@@ -41,14 +46,20 @@ public class CurrentBranchHighlighter implements VcsLogHighlighter {
   @Override
   public VcsCommitStyle getStyle(@NotNull VcsShortCommitDetails details, boolean isSelected) {
     if (isSelected || !myLogUi.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT;
-    VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
-    String currentBranch = provider.getCurrentBranch(details.getRoot());
-    if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
-      Condition<CommitId> condition =
-        myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
-      if (condition.value(new CommitId(details.getId(), details.getRoot()))) {
-        return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
+    Condition<CommitId> condition = myConditions.get(details.getRoot());
+    if (condition == null) {
+      VcsLogProvider provider = myLogData.getLogProvider(details.getRoot());
+      String currentBranch = provider.getCurrentBranch(details.getRoot());
+      if (!HEAD.equals(mySingleFilteredBranch) && currentBranch != null && !(currentBranch.equals(mySingleFilteredBranch))) {
+        condition = myLogData.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
+        myConditions.put(details.getRoot(), condition);
       }
+      else {
+        condition = Conditions.alwaysFalse();
+      }
+    }
+    if (condition != null && condition.value(new CommitId(details.getId(), details.getRoot()))) {
+      return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
     }
     return VcsCommitStyle.DEFAULT;
   }
@@ -57,6 +68,7 @@ public class CurrentBranchHighlighter implements VcsLogHighlighter {
   public void update(@NotNull VcsLogDataPack dataPack, boolean refreshHappened) {
     VcsLogBranchFilter branchFilter = dataPack.getFilters().getBranchFilter();
     mySingleFilteredBranch = branchFilter == null ? null : VcsLogUtil.getSingleFilteredBranch(branchFilter, dataPack.getRefs());
+    myConditions.clear();
   }
 
   public static class Factory implements VcsLogHighlighterFactory {
index 26a7f412e372c32273f45b089e05741260673008..8bd3f3d67b466e115f023558c9d61109b8ef62c4 100644 (file)
@@ -33,6 +33,7 @@ import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.JBUI;
 import com.intellij.util.ui.StatusText;
 import com.intellij.vcs.log.VcsFullCommitDetails;
+import com.intellij.vcs.log.data.RefsModel;
 import com.intellij.vcs.log.data.VcsLogData;
 import com.intellij.vcs.log.data.VisiblePack;
 import com.intellij.vcs.log.ui.VcsLogColorManager;
@@ -222,7 +223,7 @@ class DetailsPanel extends JPanel implements EditorColorsListener {
       for (int i = 0; i < mySelection.size(); i++) {
         CommitPanel commitPanel = getCommitPanel(i);
         Integer commit = myDataPack.getVisibleGraph().getRowInfo(mySelection.get(i)).getCommit();
-        commitPanel.setCommit(detailsList.get(i), myDataPack.getRefs().refsToCommit(commit));
+        commitPanel.setCommit(detailsList.get(i), ((RefsModel)myDataPack.getRefs()).refsToCommit(commit));
       }
 
       if (!ContainerUtil.intersects(myCommitDetails, newCommitDetails)) {
index f2caff73d23c5c01c9c77b65d7237a9885bddff8..05ff746652315982b79983c5c129fa7e5ca30505 100644 (file)
@@ -7,10 +7,7 @@ import com.intellij.util.NotNullFunction;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.text.DateFormatUtil;
 import com.intellij.vcs.log.*;
-import com.intellij.vcs.log.data.CommitIdByStringCondition;
-import com.intellij.vcs.log.data.DataGetter;
-import com.intellij.vcs.log.data.VcsLogData;
-import com.intellij.vcs.log.data.VisiblePack;
+import com.intellij.vcs.log.data.*;
 import com.intellij.vcs.log.impl.VcsLogUtil;
 import com.intellij.vcs.log.ui.VcsLogUiImpl;
 import com.intellij.vcs.log.ui.render.GraphCommitCell;
@@ -186,7 +183,7 @@ public class GraphTableModel extends AbstractTableModel {
 
   @NotNull
   private Collection<VcsRef> getRefsAtRow(int row) {
-    return myDataPack.getRefs().refsToCommit(getIdAtRow(row));
+    return ((RefsModel)myDataPack.getRefs()).refsToCommit(getIdAtRow(row));
   }
 
   @NotNull
index d69395e7437a6dc97a391bb545e0e2e84a3674be..32a1db9a53f3c3904b1f719e5114ef8d2ff7c7d2 100644 (file)
@@ -25,7 +25,7 @@ import org.jetbrains.annotations.Nullable;
 
 public class TestVcsNotifier extends VcsNotifier {
 
-  public static final String TEST_NOTIFICATION_GROUP = "Test";
+  private static final String TEST_NOTIFICATION_GROUP = "Test";
 
   private Notification myLastNotification;
 
@@ -45,6 +45,12 @@ public class TestVcsNotifier extends VcsNotifier {
     return myLastNotification;
   }
 
+  @NotNull
+  public Notification notify(@NotNull Notification notification) {
+    myLastNotification = notification;
+    return myLastNotification;
+  }
+
   public void cleanup() {
     myLastNotification = null;
   }
index 6989c9329039881bcf3b6100a3bd5ebc3ea2462e..a3bf2bb0c29bb735f0f625b3855e50498b1a54bd 100644 (file)
@@ -32,7 +32,9 @@ public interface XLocalAttachDebuggerProvider {
    * 
    */
   @NotNull
-  XLocalAttachGroup getAttachGroup();
+  default XLocalAttachGroup getAttachGroup() {
+    return XLocalAttachGroup.DEFAULT;
+  }
 
   /**
    *  Attach to Local Process action invokes {@link #getAvailableDebuggers} method for every running process.
index a92efd6b7282acc0a6e51eb5323b52e8ca5d1006..3d44b1829183c357a621ac870e251e32df27af16 100644 (file)
@@ -3,6 +3,7 @@
   <extensions defaultExtensionNs="com.intellij">
 
     <inspectionElementsMerger implementation="com.siyeh.ig.bugs.ThrowableNeverThrownInspectionMerger"/>
+    <inspectionElementsMerger implementation="com.siyeh.ig.naming.MisspelledMethodNameInspectionMerger"/>
 
     <!--group.names.abstraction.issues-->
     <localInspection groupPath="Java" language="JAVA" shortName="BooleanParameter" bundle="com.siyeh.InspectionGadgetsBundle" key="boolean.parameter.display.name"
                      bundle="com.siyeh.InspectionGadgetsBundle" key="mismatched.string.builder.query.update.display.name" runForWholeFile="true"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="true" level="WARNING"
                      implementationClass="com.siyeh.ig.bugs.MismatchedStringBuilderQueryUpdateInspection"/>
-    <localInspection groupPath="Java" language="JAVA" shortName="MisspelledCompareTo" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.compareto.display.name"
-                     groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.bugs.MisspelledCompareToInspection"/>
-    <localInspection groupPath="Java" language="JAVA" shortName="MisspelledHashcode" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.hashcode.display.name"
-                     groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.bugs.MisspelledHashcodeInspection"/>
     <localInspection groupPath="Java" language="JAVA" shortName="MisspelledEquals" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.equals.display.name"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
                      implementationClass="com.siyeh.ig.bugs.MisspelledEqualsInspection"/>
-    <localInspection groupPath="Java" language="JAVA" shortName="MisspelledToString" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.tostring.display.name"
-                     groupBundle="messages.InspectionsBundle" groupKey="group.names.probable.bugs" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.bugs.MisspelledToStringInspection"/>
     <localInspection groupPath="Java" language="JAVA" shortName="NewStringBufferWithCharArgument" bundle="com.siyeh.InspectionGadgetsBundle"
                      key="new.string.buffer.with.char.argument.display.name" groupBundle="messages.InspectionsBundle"
                      groupKey="group.names.probable.bugs" enabledByDefault="true" level="WARNING"
                      key="junit.test.class.naming.convention.display.name" groupBundle="messages.InspectionsBundle"
                      groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
                      implementationClass="com.siyeh.ig.junit.JUnitTestClassNamingConventionInspection"/>
-    <localInspection groupPath="Java" language="JAVA" shortName="MisspelledSetUp" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.set.up.display.name"
-                     groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.junit.MisspelledSetUpInspection"/>
-    <localInspection groupPath="Java" language="JAVA" shortName="MisspelledTearDown" bundle="com.siyeh.InspectionGadgetsBundle" key="misspelled.tear.down.display.name"
-                     groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.junit.MisspelledTearDownInspection"/>
     <localInspection groupPath="Java" language="JAVA" suppressId="MisorderedAssertEqualsArguments" alternativeId="MisorderedAssertEqualsArguments" shortName="MisorderedAssertEqualsParameters"
                      bundle="com.siyeh.InspectionGadgetsBundle" key="misordered.assert.equals.arguments.display.name"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.junit.issues" enabledByDefault="false" level="WARNING"
                      key="method.name.same.as.parent.name.display.name" groupBundle="messages.InspectionsBundle"
                      groupKey="group.names.naming.conventions" enabledByDefault="false" level="WARNING"
                      implementationClass="com.siyeh.ig.naming.MethodNameSameAsParentNameInspection"/>
-    <localInspection groupPath="Java" language="JAVA" suppressId="MethodNamesDifferingOnlyByCase" shortName="MethodNamesDifferOnlyByCase"
+    <localInspection groupPath="Java" language="JAVA" suppressId="MethodNamesDifferingOnlyByCase" shortName="MisspelledMethodName"
                      bundle="com.siyeh.InspectionGadgetsBundle" key="method.names.differ.only.by.case.display.name"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.naming.conventions" enabledByDefault="false"
-                     level="WARNING" implementationClass="com.siyeh.ig.naming.MethodNamesDifferOnlyByCaseInspection"/>
+                     level="WARNING" implementationClass="com.siyeh.ig.naming.MisspelledMethodNameInspection"/>
     <localInspection groupPath="Java" language="JAVA" shortName="NativeMethodNamingConvention"
                      bundle="com.siyeh.InspectionGadgetsBundle" key="native.method.naming.convention.display.name"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.naming.conventions" enabledByDefault="false"
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledCompareToInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledCompareToInspectionBase.java
deleted file mode 100644 (file)
index 75a6909..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2000-2013 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.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledCompareToInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "misspelled.compareto.display.name");
-  }
-
-  @Override
-  @NotNull
-  public String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "misspelled.compareto.problem.descriptor");
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new MisspelledCompareToVisitor();
-  }
-
-  private static class MisspelledCompareToVisitor
-    extends BaseInspectionVisitor {
-
-    @Override
-    public void visitMethod(@NotNull PsiMethod method) {
-      //note: no call to super
-      @NonNls final String methodName = method.getName();
-      if (!"compareto".equals(methodName)) {
-        return;
-      }
-      final PsiParameterList parameterList = method.getParameterList();
-      if (parameterList.getParametersCount() != 1) {
-        return;
-      }
-      registerMethodError(method);
-    }
-  }
-}
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledHashcodeInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledHashcodeInspectionBase.java
deleted file mode 100644 (file)
index 435cfed..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2000-2013 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.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledHashcodeInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "misspelled.hashcode.display.name");
-  }
-
-  @Override
-  @NotNull
-  public String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "misspelled.hashcode.problem.descriptor");
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new MisspelledHashcodeVisitor();
-  }
-
-  private static class MisspelledHashcodeVisitor
-    extends BaseInspectionVisitor {
-
-    @Override
-    public void visitMethod(@NotNull PsiMethod method) {
-      //note: no call to super
-      @NonNls final String methodName = method.getName();
-      if (!"hashcode".equals(methodName)) {
-        return;
-      }
-      final PsiParameterList parameterList = method.getParameterList();
-      if (parameterList.getParametersCount() != 0) {
-        return;
-      }
-      registerMethodError(method);
-    }
-  }
-}
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledToStringInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/MisspelledToStringInspectionBase.java
deleted file mode 100644 (file)
index 4fd6e42..0000000
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright 2000-2013 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.bugs;
-
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiParameterList;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledToStringInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "misspelled.tostring.display.name");
-  }
-
-  @Override
-  @NotNull
-  public String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "misspelled.tostring.problem.descriptor");
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new MisspelledToStringVisitor();
-  }
-
-  private static class MisspelledToStringVisitor
-    extends BaseInspectionVisitor {
-
-    @Override
-    public void visitMethod(@NotNull PsiMethod method) {
-      //note: no call to super
-      @NonNls final String methodName = method.getName();
-      if (!"tostring".equals(methodName)) {
-        return;
-      }
-      final PsiParameterList parameterList = method.getParameterList();
-      if (parameterList.getParametersCount() != 0) {
-        return;
-      }
-      registerMethodError(method);
-    }
-  }
-}
index dd151e83a2f531f46e931e84a4a886c0295829c8..4c5dfd559171de22bf51622c36f3d8efe593ba16 100644 (file)
@@ -23,12 +23,12 @@ import com.intellij.codeInspection.ex.InspectionElementsMerger;
 public class ThrowableNeverThrownInspectionMerger extends InspectionElementsMerger {
 
   @Override
-  protected String getMergedToolName() {
+  public String getMergedToolName() {
     return "ThrowableNeverThrown";
   }
 
   @Override
-  protected String[] getSourceToolNames() {
+  public String[] getSourceToolNames() {
     return new String[] {"ThrowableInstanceNeverThrown", "ThrowableResultOfMethodCallIgnored"};
   }
 }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledSetUpInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledSetUpInspectionBase.java
deleted file mode 100644 (file)
index af3f874..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2000-2013 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.junit;
-
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.util.InheritanceUtil;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledSetUpInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "misspelled.set.up.display.name");
-  }
-
-  @Override
-  @NotNull
-  protected String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "misspelled.set.up.problem.descriptor");
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new MisspelledSetUpVisitor();
-  }
-
-  @Override
-  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
-    return true;
-  }
-
-  private static class MisspelledSetUpVisitor extends BaseInspectionVisitor {
-
-    @Override
-    public void visitMethod(@NotNull PsiMethod method) {
-      //note: no call to super
-      final PsiClass aClass = method.getContainingClass();
-      @NonNls final String methodName = method.getName();
-      if (!"setup".equals(methodName)) {
-        return;
-      }
-      if (aClass == null) {
-        return;
-      }
-      if (!InheritanceUtil.isInheritor(aClass,
-                                       "junit.framework.TestCase")) {
-        return;
-      }
-      registerMethodError(method);
-    }
-  }
-}
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledTearDownInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/MisspelledTearDownInspectionBase.java
deleted file mode 100644 (file)
index d6858bf..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright 2000-2013 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.junit;
-
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.util.InheritanceUtil;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
-
-public class MisspelledTearDownInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "misspelled.tear.down.display.name");
-  }
-
-  @Override
-  @NotNull
-  protected String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "misspelled.tear.down.problem.descriptor");
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new MisspelledSetUpVisitor();
-  }
-
-  @Override
-  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
-    return true;
-  }
-
-  private static class MisspelledSetUpVisitor extends BaseInspectionVisitor {
-
-    @Override
-    public void visitMethod(@NotNull PsiMethod method) {
-      // note: no call to super
-      @NonNls final String methodName = method.getName();
-      if (!"teardown".equals(methodName)) {
-        return;
-      }
-      final PsiClass aClass = method.getContainingClass();
-      if (aClass == null) {
-        return;
-      }
-      if (!InheritanceUtil.isInheritor(aClass,
-                                       "junit.framework.TestCase")) {
-        return;
-      }
-      registerMethodError(method);
-    }
-  }
-}
@@ -29,16 +29,10 @@ import org.jetbrains.annotations.NotNull;
 
 import java.util.Map;
 
-public class MethodNamesDifferOnlyByCaseInspectionBase extends BaseInspection {
+public class MisspelledMethodNameInspectionBase extends BaseInspection {
   @SuppressWarnings("PublicField")
   public boolean ignoreIfMethodIsOverride = true;
 
-  @Override
-  @NotNull
-  public String getID() {
-    return "MethodNamesDifferingOnlyByCase";
-  }
-
   @Override
   @NotNull
   public String getDisplayName() {
similarity index 52%
rename from plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledToStringInspection.java
rename to plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/naming/MisspelledMethodNameInspectionMerger.java
index 35f90eb958b21b60311b3174c9e5a9d54b24f874..2e315faa9ac7df28d2e413feffbaa621af7831ab 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2007 Dave Griffith, Bas Leijdekkers
+ * 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.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.siyeh.ig.bugs;
+package com.siyeh.ig.naming;
 
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
+import com.intellij.codeInspection.ex.InspectionElementsMerger;
 
-public class MisspelledToStringInspection extends MisspelledToStringInspectionBase {
+public class MisspelledMethodNameInspectionMerger extends InspectionElementsMerger {
 
   @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix(HardcodedMethodConstants.TO_STRING);
+  public String getMergedToolName() {
+    return "MisspelledMethodName";
   }
-}
\ No newline at end of file
+
+  @Override
+  public String[] getSourceToolNames() {
+    return new String[]{"MethodNamesDifferOnlyByCase", "MisspelledSetUp", "MisspelledTearDown", "MisspelledHashcode", "MisspelledToString", "MisspelledCompareTo"};
+  }
+}
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledHashcodeInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/bugs/MisspelledHashcodeInspection.java
deleted file mode 100644 (file)
index d4269da..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright 2003-2007 Dave Griffith, 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.ig.bugs;
-
-import com.siyeh.HardcodedMethodConstants;
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledHashcodeInspection extends MisspelledHashcodeInspectionBase {
-
-  @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix(HardcodedMethodConstants.HASH_CODE);
-  }
-}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledSetUpInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledSetUpInspection.java
deleted file mode 100644 (file)
index d426f32..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2003-2011 Dave Griffith, 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.ig.junit;
-
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledSetUpInspection extends MisspelledSetUpInspectionBase {
-
-  @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix("setUp");
-  }
-}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledTearDownInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/junit/MisspelledTearDownInspection.java
deleted file mode 100644 (file)
index 4bc58b0..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2003-2011 Dave Griffith, 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.ig.junit;
-
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.RenameFix;
-
-public class MisspelledTearDownInspection extends MisspelledTearDownInspectionBase {
-
-  @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix("tearDown");
-  }
-}
\ No newline at end of file
similarity index 89%
rename from plugins/InspectionGadgets/src/com/siyeh/ig/naming/MethodNamesDifferOnlyByCaseInspection.java
rename to plugins/InspectionGadgets/src/com/siyeh/ig/naming/MisspelledMethodNameInspection.java
index 567a7c557b856792cf381d4b29390aaa61448c07..15a453b1fd228649ec39b87bea0fc2e92feb78a2 100644 (file)
@@ -22,7 +22,7 @@ import com.siyeh.ig.fixes.RenameFix;
 
 import javax.swing.*;
 
-public class MethodNamesDifferOnlyByCaseInspection extends MethodNamesDifferOnlyByCaseInspectionBase {
+public class MisspelledMethodNameInspection extends MisspelledMethodNameInspectionBase {
 
   @Override
   public JComponent createOptionsPanel() {
@@ -32,6 +32,6 @@ public class MethodNamesDifferOnlyByCaseInspection extends MethodNamesDifferOnly
 
   @Override
   protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new RenameFix();
+    return new RenameFix((String)infos[0]);
   }
 }
\ No newline at end of file
index ece054bfb8a7251662c9efde65f1683af4126d3a..7b6f47478751e6876f2f77202bb55f9c701e8522 100644 (file)
@@ -5,6 +5,6 @@ import com.siyeh.ig.IGInspectionTestCase;
 public class MethodNamesDifferOnlyByCaseInspectionTest extends IGInspectionTestCase {
 
   public void test() throws Exception {
-    doTest("com/siyeh/igtest/naming/method_names_differ_only_by_case", new MethodNamesDifferOnlyByCaseInspection());
+    doTest("com/siyeh/igtest/naming/method_names_differ_only_by_case", new MisspelledMethodNameInspection());
   }
 }
\ No newline at end of file
index f85177c1f96542e81372f16712a7768430233930..52ebd1788d398263acd75c86da275ee5128c380b 100644 (file)
@@ -18,19 +18,15 @@ package git4idea.branch;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.components.JBLabel;
 import com.intellij.util.ArrayUtil;
 import com.intellij.xml.util.XmlStringUtil;
 import git4idea.DialogManager;
-import git4idea.GitBranch;
 import git4idea.GitCommit;
-import git4idea.i18n.GitBundle;
 import git4idea.repo.GitRepository;
 import git4idea.ui.GitCommitListWithDiffPanel;
 import git4idea.ui.GitRepositoryComboboxListCellRenderer;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
@@ -53,56 +49,50 @@ public class GitBranchIsNotFullyMergedDialog extends DialogWrapper {
 
   private final Project myProject;
   private final Map<GitRepository, List<GitCommit>> myCommits;
-  private final String myBranchToDelete;
-  private final String myBaseBranch;
-  private final List<String> myMergedToBranches;
 
   private final GitCommitListWithDiffPanel myCommitListWithDiffPanel;
   private final Collection<GitRepository> myRepositories;
+  @NotNull private final String myRemovedBranch;
+  @NotNull private final Map<GitRepository, String> myBaseBranches;
   private final GitRepository myInitialRepository;
 
   /**
    * Show the dialog and get user's answer, whether he wants to force delete the branch.
    *
-   * @param commits          the list of commits, which are not merged from the branch being deleted to the current branch,
-   *                         grouped by repository.
-   * @param branchToDelete   the name of the branch which user chose to delete.
-   * @param mergedToBranches the list of branches which the branch is merged to (returned by {@code git branch --merged <branchToDelete>} command.
-   * @param baseBranch       branch which branchToDelete is not merged to. It is either current branch, or the upstream branch.
-   * @return true if user decided to delete the branch.
+   * @param commits      the list of commits, which are not merged from the branch being deleted to the current branch,
+   *                     grouped by repository.
+   * @param baseBranches base branches (which Git reported as not containing commits from the removed branch) per repository.
+   * @return true if user decided to restore the branch.
    */
   public static boolean showAndGetAnswer(@NotNull Project project,
                                          @NotNull Map<GitRepository, List<GitCommit>> commits,
-                                         @NotNull String branchToDelete,
-                                         @NotNull List<String> mergedToBranches,
-                                         @Nullable String baseBranch) {
-    GitBranchIsNotFullyMergedDialog dialog = new GitBranchIsNotFullyMergedDialog(project, commits, branchToDelete, baseBranch, mergedToBranches);
+                                         @NotNull Map<GitRepository, String> baseBranches,
+                                         @NotNull String removedBranch) {
+    GitBranchIsNotFullyMergedDialog dialog = new GitBranchIsNotFullyMergedDialog(project, commits, baseBranches, removedBranch);
     DialogManager.show(dialog);
     return dialog.isOK();
   }
 
   private GitBranchIsNotFullyMergedDialog(@NotNull Project project,
                                           @NotNull Map<GitRepository, List<GitCommit>> commits,
-                                          @NotNull String branchToDelete,
-                                          @Nullable String baseBranch,
-                                          @NotNull List<String> mergedToBranches) {
+                                          @NotNull Map<GitRepository, String> baseBranches,
+                                          @NotNull String removedBranch) {
     super(project, false);
     myProject = project;
     myCommits = commits;
-    myBranchToDelete = branchToDelete;
-    myBaseBranch = baseBranch;
-    myMergedToBranches = mergedToBranches;
     myRepositories = commits.keySet();
+    myBaseBranches = baseBranches;
+    myRemovedBranch = removedBranch;
 
     myInitialRepository = calcInitiallySelectedRepository();
     myCommitListWithDiffPanel = new GitCommitListWithDiffPanel(myProject, new ArrayList<GitCommit>(myCommits.get(myInitialRepository)));
 
     init();
 
-    setTitle("Branch Is Not Fully Merged");
-    setOKButtonText("Delete");
-    setOKButtonMnemonic('D');
-    setCancelButtonText("Cancel");
+    setTitle("Branch Was Not Fully Merged");
+    setOKButtonText("Restore");
+    setOKButtonMnemonic('R');
+    getCancelAction().putValue(DEFAULT_ACTION, Boolean.TRUE);
   }
 
   @NotNull
@@ -115,61 +105,33 @@ public class GitBranchIsNotFullyMergedDialog extends DialogWrapper {
     throw new AssertionError("The dialog shouldn't be shown. Unmerged commits: " + myCommits);
   }
 
-  private String makeDescription() {
-    String currentBranchOrRev;
-    boolean onBranch;
-    if (myRepositories.size() > 1) {
-      LOG.assertTrue(myBaseBranch != null, "Branches have unexpectedly diverged");
-      currentBranchOrRev = myBaseBranch;
-      onBranch = true;
+  @NotNull
+  private String makeDescription(@NotNull GitRepository repository) {
+    String baseBranch = myBaseBranches.get(repository);
+    String description;
+    if (baseBranch == null) {
+      description = String.format("All commits from branch %s were merged", myRemovedBranch);
     }
     else {
-      GitRepository repository = myInitialRepository;
-      if (repository.isOnBranch()) {
-        GitBranch currentBranch = repository.getCurrentBranch();
-        assert currentBranch != null;
-        currentBranchOrRev = currentBranch.getName();
-        onBranch = true;
-      }
-      else {
-        currentBranchOrRev = repository.getCurrentRevision();
-        onBranch = false;
-      }
-    }
-
-    StringBuilder description = new StringBuilder();
-    if (onBranch) {
-      description.append(GitBundle.message("branch.delete.not_fully_merged.description", myBranchToDelete, myBaseBranch));
-    } else {
-      description.append(GitBundle.message("branch.delete.not_fully_merged.description.not_on_branch", myBranchToDelete, currentBranchOrRev,
-                                           myBaseBranch));
-    }
-    if (!myMergedToBranches.isEmpty()) {
-      String listOfMergedBranches = StringUtil.join(StringUtil.surround(ArrayUtil.toStringArray(myMergedToBranches), "<b>", "</b>"), ", ");
-      description.append("<br>");
-      if (myMergedToBranches.size() == 1) {
-        description.append(GitBundle.message("branch.delete.merged_to.one", myBranchToDelete, listOfMergedBranches));
-      }
-      else {
-        description.append(GitBundle.message("branch.delete.merged_to.many", myBranchToDelete, listOfMergedBranches));
-      }
+      description = String.format("The branch %s was not fully merged to %s.<br/>Below is the list of unmerged commits.",
+                                  myRemovedBranch, baseBranch);
     }
-    description.append("<br>").append(GitBundle.message("branch.delete.warning", myBranchToDelete));
-    return description.toString();
+    return XmlStringUtil.wrapInHtml(description);
   }
 
   @Override
   protected JComponent createNorthPanel() {
-    JBLabel descriptionLabel = new JBLabel(XmlStringUtil.wrapInHtml(makeDescription()));
+    JBLabel descriptionLabel = new JBLabel(makeDescription(myInitialRepository));
 
-      final JComboBox repositorySelector = new JComboBox(ArrayUtil.toObjectArray(myRepositories, GitRepository.class));
+    JComboBox repositorySelector = new JComboBox(ArrayUtil.toObjectArray(myRepositories, GitRepository.class));
     repositorySelector.setRenderer(new GitRepositoryComboboxListCellRenderer(repositorySelector));
     repositorySelector.setSelectedItem(myInitialRepository);
     repositorySelector.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(ActionEvent e) {
-        List<GitCommit> commits = myCommits.get((GitRepository)repositorySelector.getSelectedItem());
-        myCommitListWithDiffPanel.setCommits(new ArrayList<GitCommit>(commits));
+        GitRepository selectedRepo = (GitRepository)repositorySelector.getSelectedItem();
+        descriptionLabel.setText(makeDescription(selectedRepo));
+        myCommitListWithDiffPanel.setCommits(myCommits.get(selectedRepo));
       }
     });
 
index f84845b7fe771ea71e91c8f025ebfcb01f3e655c..68b8ea88dca3bdd4adc7dc8901a887420e4c198b 100644 (file)
@@ -15,6 +15,7 @@
  */
 package git4idea.branch;
 
+import com.google.common.collect.Maps;
 import com.intellij.dvcs.DvcsUtil;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
@@ -29,9 +30,7 @@ import com.intellij.openapi.vcs.changes.Change;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.Function;
-import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.MultiMap;
-import git4idea.GitLocalBranch;
 import git4idea.GitUtil;
 import git4idea.commands.Git;
 import git4idea.commands.GitMessageWithFilesDetector;
@@ -44,6 +43,7 @@ import java.util.*;
 
 import static com.intellij.openapi.application.ModalityState.defaultModalityState;
 import static com.intellij.openapi.util.text.StringUtil.pluralize;
+import static com.intellij.util.ObjectUtils.chooseNotNull;
 
 /**
  * Common class for Git operations with branches aware of multi-root configuration,
@@ -58,6 +58,7 @@ abstract class GitBranchOperation {
   @NotNull protected final GitBranchUiHandler myUiHandler;
   @NotNull private final Collection<GitRepository> myRepositories;
   @NotNull protected final Map<GitRepository, String> myCurrentHeads;
+  @NotNull protected final Map<GitRepository, String> myInitialRevisions;
   @NotNull private final GitVcsSettings mySettings;
 
   @NotNull private final Collection<GitRepository> mySuccessfulRepositories;
@@ -70,13 +71,8 @@ abstract class GitBranchOperation {
     myGit = git;
     myUiHandler = uiHandler;
     myRepositories = repositories;
-    myCurrentHeads = ContainerUtil.map2Map(repositories, new Function<GitRepository, Pair<GitRepository, String>>() {
-      @Override
-      public Pair<GitRepository, String> fun(GitRepository repository) {
-        GitLocalBranch currentBranch = repository.getCurrentBranch();
-        return Pair.create(repository, currentBranch == null ? repository.getCurrentRevision() : currentBranch.getName());
-      }
-    });
+    myCurrentHeads = Maps.toMap(repositories, repo -> chooseNotNull(repo.getCurrentBranchName(), repo.getCurrentRevision()));
+    myInitialRevisions = Maps.toMap(repositories, GitRepository::getCurrentRevision);
     mySuccessfulRepositories = new ArrayList<GitRepository>();
     mySkippedRepositories = new ArrayList<GitRepository>();
     myRemainingRepositories = new ArrayList<GitRepository>(myRepositories);
@@ -183,7 +179,7 @@ abstract class GitBranchOperation {
     VcsNotifier.getInstance(myProject).notifySuccess(message);
   }
 
-  protected final void notifySuccess() {
+  protected void notifySuccess() {
     notifySuccess(getSuccessMessage());
   }
 
@@ -264,6 +260,14 @@ abstract class GitBranchOperation {
     }
   }
 
+  /**
+   * Returns the hash of the revision which was current before the start of this GitBranchOperation.
+   */
+  @NotNull
+  protected String getInitialRevision(@NotNull GitRepository repository) {
+    return myInitialRevisions.get(repository);
+  }
+
   @Nullable
   private String getRecentCommonBranch() {
     String recentCommonBranch = null;
index dd3e08305d43f58a91fa5a4fcf5803d76222bc1a..bba53c98bb3b52bbbe7ca86da11581552f8fc9d7 100644 (file)
@@ -81,8 +81,12 @@ public interface GitBranchUiHandler {
   int showSmartOperationDialog(@NotNull Project project, @NotNull List<Change> changes, @NotNull Collection<String> paths,
                                @NotNull String operation, @Nullable String forceButtonTitle);
 
-  boolean showBranchIsNotFullyMergedDialog(@NotNull Project project, @NotNull Map<GitRepository, List<GitCommit>> history,
-                                           @NotNull String unmergedBranch, @NotNull List<String> mergedToBranches,
-                                           @NotNull String baseBranch);
+  /**
+   * @return true if user decided to restore the branch.
+   */
+  boolean showBranchIsNotFullyMergedDialog(@NotNull Project project,
+                                           @NotNull Map<GitRepository, List<GitCommit>> history,
+                                           @NotNull Map<GitRepository, String> baseBranches,
+                                           @NotNull String removedBranch);
 
 }
index f39461d60290b7210249b435f4e3bd79bee657e8..826a78038b0fc1cfab289dc0877d94e029fa8e9f 100644 (file)
@@ -147,14 +147,15 @@ public class GitBranchUiHandlerImpl implements GitBranchUiHandler {
   }
 
   @Override
-  public boolean showBranchIsNotFullyMergedDialog(@NotNull Project project, @NotNull final Map<GitRepository, List<GitCommit>> history,
-                                                  @NotNull final String unmergedBranch, @NotNull final List<String> mergedToBranches,
-                                                  @NotNull final String baseBranch) {
-    final AtomicBoolean forceDelete = new AtomicBoolean();
-    ApplicationManager.getApplication().invokeAndWait(() -> forceDelete.set(
-      GitBranchIsNotFullyMergedDialog.showAndGetAnswer(myProject, history, unmergedBranch, mergedToBranches, baseBranch)),
+  public boolean showBranchIsNotFullyMergedDialog(@NotNull Project project,
+                                                  @NotNull Map<GitRepository, List<GitCommit>> history,
+                                                  @NotNull Map<GitRepository, String> baseBranches,
+                                                  @NotNull String removedBranch) {
+    AtomicBoolean restore = new AtomicBoolean();
+    ApplicationManager.getApplication().invokeAndWait(() -> restore.set(
+      GitBranchIsNotFullyMergedDialog.showAndGetAnswer(myProject, history, baseBranches, removedBranch)),
       ModalityState.defaultModalityState());
-    return forceDelete.get();
+    return restore.get();
   }
 
   @NotNull
index 735269ee68235bcb5878912f499698e0dfa740ec..86ae4326c1b73075f3bd7c851bec5148f9a6e60d 100644 (file)
@@ -83,6 +83,11 @@ public class GitBranchUtil {
     return null;
   }
 
+  @Nullable
+  public static GitBranchTrackInfo getTrackInfo(@NotNull GitRepository repository, @NotNull String localBranchName) {
+    return ContainerUtil.find(repository.getBranchTrackInfos(), it -> it.getLocalBranch().getName().equals(localBranchName));
+  }
+
   @NotNull
   static String