Merge remote-tracking branch 'origin/master'
authorDmitry Avdeev <dmitry.avdeev@jetbrains.com>
Wed, 4 May 2016 09:22:39 +0000 (12:22 +0300)
committerDmitry Avdeev <dmitry.avdeev@jetbrains.com>
Wed, 4 May 2016 09:22:39 +0000 (12:22 +0300)
395 files changed:
build/scripts/moduleLoader.gant
java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
java/execution/impl/src/com/intellij/execution/JavaTestFrameworkRunnableState.java
java/execution/impl/src/com/intellij/execution/testframework/JavaAwareTestConsoleProperties.java
java/idea-ui/src/com/intellij/facet/impl/ui/libraries/versions/VersionsComponent.java
java/idea-ui/src/com/intellij/ide/util/projectWizard/ExistingModuleLoader.java
java/idea-ui/src/com/intellij/ide/util/projectWizard/importSources/impl/ProjectFromSourcesBuilderImpl.java
java/idea-ui/src/com/intellij/platform/templates/SaveProjectAsTemplateAction.java
java/java-analysis-impl/src/com/intellij/codeInspection/testOnly/TestOnlyInspection.java
java/java-impl/src/com/intellij/codeInsight/completion/CatchTypeProvider.java
java/java-impl/src/com/intellij/codeInsight/completion/FunctionalExpressionCompletionProvider.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaClassNameInsertHandler.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSession.java [moved from java/java-impl/src/com/intellij/codeInsight/completion/InheritorsHolder.java with 82% similarity]
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaDocCompletionContributor.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaKeywordCompletion.java
java/java-impl/src/com/intellij/codeInsight/completion/JavaNoVariantsDelegator.java
java/java-impl/src/com/intellij/codeInsight/completion/TypeArgumentCompletionProvider.java
java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaColorProvider.java
java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableTypeFromCallFix.java
java/java-impl/src/com/intellij/codeInsight/editorActions/JavaCopyPasteReferenceProcessor.java
java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/JavaSmartEnterProcessor.java
java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/MissingIfBranchesFixer.java
java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/PlainEnterProcessor.java
java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SwitchLabelColonFixer.java [moved from java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/CaseColonFixer.java with 71% similarity]
java/java-impl/src/com/intellij/codeInsight/lookup/VariableLookupItem.java
java/java-impl/src/com/intellij/codeInsight/template/impl/CodeBlockReformattingProcessor.java
java/java-impl/src/com/intellij/codeInsight/template/impl/ShortenFQNamesProcessor.java
java/java-impl/src/com/intellij/codeInsight/template/impl/ShortenToStaticImportProcessor.java
java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java
java/java-impl/src/com/intellij/refactoring/memberPullUp/JavaPullUpHandler.java
java/java-impl/src/com/intellij/refactoring/memberPushDown/JavaPushDownHandler.java
java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java
java/java-impl/src/com/intellij/spi/psi/SPIClassProviderReferenceElement.java
java/java-indexing-impl/src/com/intellij/psi/impl/search/JavaClassInheritorsSearcher.java
java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java
java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java
java/java-psi-impl/src/com/intellij/psi/impl/source/JavaLightStubBuilder.java
java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java
java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completeStatement/DefaultColon.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completeStatement/DefaultColon_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/NoExpectedReturnTypeDuplication.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter_after.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/normalSorting/GenericityDoesNotMatterWhenNoTypeIsExpected.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef-out.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor-out.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnboxingFromTypeParameter.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/InheritorConstructorRef.java [new file with mode: 0644]
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/LambdaWithCapturedSuperWildcardInAmbiguousCall.java [deleted file]
java/java-tests/testData/inspection/testOnly/visibleForTesting/expected.xml
java/java-tests/testData/inspection/testOnly/visibleForTesting/src/A.java
java/java-tests/testData/inspection/testOnly/visibleForTesting/src/B.java
java/java-tests/testData/psi/resolve/class/QualifiedAnonymousClass.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java.after [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java.after [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java [new file with mode: 0644]
java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java.after [new file with mode: 0644]
java/java-tests/testSrc/com/intellij/codeInsight/CompleteStatementTest.java
java/java-tests/testSrc/com/intellij/codeInsight/completion/Normal8CompletionTest.groovy
java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy
java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy
java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartType18CompletionTest.java
java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
java/java-tests/testSrc/com/intellij/codeInsight/daemon/impl/DaemonRespondToChangesTest.java
java/java-tests/testSrc/com/intellij/codeInspection/InspectionProfilesConverterTest.java
java/java-tests/testSrc/com/intellij/execution/ConfigurationRefactoringsTest.java
java/java-tests/testSrc/com/intellij/lang/spi/SPICompletionTest.java [new file with mode: 0644]
java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy
java/java-tests/testSrc/com/intellij/psi/resolve/ResolveClassTest.java
java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java
java/java-tests/testSrc/com/intellij/refactoring/inline/InlineLocalTest.java
java/testFramework/src/com/intellij/testFramework/codeInsight/hierarchy/HierarchyViewTestBase.java
java/testFramework/src/com/intellij/testFramework/fixtures/JavaCodeInsightTestUtil.java
java/testFramework/src/com/intellij/testFramework/fixtures/impl/JavaCodeInsightTestFixtureImpl.java
jps/jps-builders/src/org/jetbrains/jps/javac/ExternalJavacManager.java
jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsGlobalElementSaver.java
jps/model-serialization/src/org/jetbrains/jps/model/serialization/JpsLoaderBase.java
jps/model-serialization/src/org/jetbrains/jps/model/serialization/library/JpsLibraryTableSerializer.java
jps/model-serialization/src/org/jetbrains/jps/model/serialization/library/JpsSdkTableSerializer.java
platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileLoadUtil.java
platform/configuration-store-impl/src/ComponentStoreImpl.kt
platform/configuration-store-impl/src/SchemeManagerImpl.kt
platform/configuration-store-impl/src/StorageBaseEx.kt
platform/core-api/src/com/intellij/psi/search/LocalSearchScope.java
platform/core-impl/src/com/intellij/openapi/application/TransactionGuardImpl.java
platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java
platform/core-impl/src/com/intellij/psi/impl/smartPointers/AnchorElementInfoFactory.java
platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPointerElementInfoFactory.java [deleted file]
platform/core-impl/src/com/intellij/psi/impl/smartPointers/SmartPsiElementPointerImpl.java
platform/dvcs-impl/src/com/intellij/dvcs/DvcsCommitAdditionalComponent.java
platform/dvcs-impl/src/com/intellij/dvcs/DvcsPlatformFacade.java [deleted file]
platform/dvcs-impl/src/com/intellij/dvcs/DvcsPlatformFacadeImpl.java [deleted file]
platform/editor-ui-api/src/com/intellij/openapi/editor/GutterMarkPreprocessor.java [moved from platform/usageView/src/com/intellij/usages/actions/IncludeUsageAction.java with 53% similarity]
platform/editor-ui-ex/src/com/intellij/psi/impl/cache/impl/id/PlatformIdTableBuilding.java
platform/indexing-impl/src/com/intellij/psi/impl/cache/impl/todo/TodoIndexers.java
platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java
platform/lang-impl/src/com/intellij/codeInsight/documentation/DocumentationManager.java
platform/lang-impl/src/com/intellij/codeInsight/editorActions/enter/EnterBetweenBracesHandler.java
platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupArranger.java
platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateSettingsEditor.java
platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateOptionalProcessor.java
platform/lang-impl/src/com/intellij/codeInspection/actions/ViewOfflineResultsAction.java
platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java
platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTreeState.java
platform/lang-impl/src/com/intellij/codeInspection/ui/QuickFixPreviewPanelFactory.java
platform/lang-impl/src/com/intellij/codeInspection/ui/SuppressableInspectionTreeNode.java
platform/lang-impl/src/com/intellij/diagnostic/logging/OutputFileUtil.java
platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java
platform/lang-impl/src/com/intellij/find/replaceInProject/ReplaceInProjectManager.java
platform/lang-impl/src/com/intellij/ide/actions/GotoActionAction.java
platform/lang-impl/src/com/intellij/ide/actions/GotoFileItemProvider.java
platform/lang-impl/src/com/intellij/ide/bookmarks/actions/MnemonicChooser.java
platform/lang-impl/src/com/intellij/ide/fileTemplates/ui/CreateFromTemplatePanel.java
platform/lang-impl/src/com/intellij/ide/fileTemplates/ui/SelectTemplateDialog.java
platform/lang-impl/src/com/intellij/ide/impl/convert/JDomConvertingUtil.java
platform/lang-impl/src/com/intellij/ide/todo/ScopeBasedTodosPanel.java
platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNamePopup.java
platform/lang-impl/src/com/intellij/profile/codeInspection/ui/header/InspectionToolsConfigurable.java
platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
platform/lang-impl/src/com/intellij/refactoring/util/RefactoringUIUtil.java
platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
platform/lang-impl/src/com/intellij/util/indexing/IndexingStamp.java
platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
platform/lang-impl/src/com/intellij/util/indexing/SharedIndicesData.java
platform/platform-api/src/com/intellij/ide/actions/exclusion/TreeNodeExclusionAction.java
platform/platform-api/src/com/intellij/openapi/ui/MessageType.java
platform/platform-api/src/com/intellij/openapi/ui/PanelWithActionsAndCloseButton.java
platform/platform-api/src/com/intellij/ui/DottedBorder.java
platform/platform-api/src/com/intellij/util/ContentsUtil.java
platform/platform-api/src/com/intellij/util/net/HttpConfigurable.java
platform/platform-impl/src/com/intellij/ide/IdeEventQueue.java
platform/platform-impl/src/com/intellij/ide/IdeTooltipManager.java
platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java
platform/platform-impl/src/com/intellij/openapi/application/impl/LaterInvocator.java
platform/platform-impl/src/com/intellij/openapi/diff/impl/ErrorDiffViewer.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorGutterComponentImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java
platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java
platform/platform-impl/src/com/intellij/openapi/keymap/impl/ui/KeymapPanel.java
platform/platform-impl/src/com/intellij/openapi/ui/WindowWrapperBuilder.java
platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/InternalDecorator.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/PaintersHelper.java
platform/platform-impl/src/com/intellij/openapi/wm/impl/content/ToolWindowContentUi.java
platform/platform-impl/src/com/intellij/ui/ColorPicker.java
platform/platform-impl/src/com/intellij/ui/SlideComponent.java
platform/platform-impl/src/com/intellij/ui/content/impl/TabbedContentImpl.java
platform/platform-impl/src/com/intellij/ui/plaf/beg/BegMenuBorder.java
platform/platform-impl/src/com/intellij/ui/plaf/beg/BegTabbedPaneUI.java
platform/platform-impl/src/com/intellij/ui/popup/BalloonPopupBuilderImpl.java
platform/platform-impl/src/com/intellij/util/ContentUtilEx.java
platform/platform-impl/src/com/intellij/util/jdom.kt
platform/platform-resources-en/src/messages/ApplicationBundle.properties
platform/platform-resources/src/META-INF/LangExtensionPoints.xml
platform/platform-resources/src/META-INF/PlatformExtensionPoints.xml
platform/platform-resources/src/META-INF/VcsExtensions.xml
platform/platform-resources/src/componentSets/VCS.xml
platform/platform-resources/src/idea/LangActions.xml
platform/platform-tests/testSrc/com/intellij/application/TransactionTest.groovy
platform/platform-tests/testSrc/com/intellij/openapi/vfs/local/JarRootsRefreshTest.java
platform/platform-tests/testSrc/com/intellij/ui/BalloonTest.java
platform/projectModel-impl/src/com/intellij/core/CoreProjectLoader.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralToSMTRunnerEventsConvertor.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/ImportedTestConsoleProperties.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/history/actions/AbstractImportTestsAction.java
platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/TestsPresentationUtil.java
platform/structuralsearch/source/com/intellij/structuralsearch/impl/matcher/handlers/SymbolHandler.java
platform/structuralsearch/testSource/com/intellij/structuralsearch/StructuralSearchTest.java
platform/testFramework/src/com/intellij/openapi/application/ex/PathManagerEx.java
platform/testFramework/src/com/intellij/testFramework/EdtTestUtil.kt
platform/testFramework/src/com/intellij/testFramework/InspectionTestUtil.java
platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
platform/testRunner/src/com/intellij/execution/testframework/TestConsoleProperties.java
platform/usageView/src/com/intellij/usages/actions/IncludeExcludeActionBase.java [deleted file]
platform/usageView/src/com/intellij/usages/actions/RemoveUsageAction.java
platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java
platform/util/resources/misc/registry.properties
platform/util/src/com/intellij/openapi/util/JDOMUtil.java
platform/util/src/com/intellij/ui/JBColor.java
platform/util/src/com/intellij/ui/PopupBorder.java
platform/util/src/com/intellij/util/ui/JBUI.java
platform/vcs-api/src/com/intellij/openapi/vcs/VcsConfiguration.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListManagerImpl.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/VcsDirtyScopeVfsListener.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/CommittedChangesBrowser.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/ApplyPatchDifferentiatedDialog.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesBrowserBase.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitChangeListDialog.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/MultipleChangeListBrowser.java
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/NewEditChangelistPanel.java
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.java
platform/vcs-impl/src/com/intellij/openapi/vcs/impl/projectlevelman/NewMappings.java
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/CloseLogTabAction.java
platform/vcs-tests/testSrc/com/intellij/vcs/VcsDirtyScopeManagerTest.kt
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/ThrowableResultOfMethodCallIgnoredInspection.java
plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/SharedThreadLocalRandomInspectionBase.java
plugins/ant/jps-plugin/src/com/intellij/lang/ant/config/impl/BuildFileProperty.java
plugins/ant/src/com/intellij/lang/ant/config/actions/RunAction.java
plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java
plugins/ant/src/com/intellij/lang/ant/config/execution/AntRunConfiguration.java
plugins/ant/src/com/intellij/lang/ant/config/execution/AntRunProfileState.java
plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
plugins/copyright/src/com/maddyhome/idea/copyright/options/ExternalOptionHelper.java
plugins/devkit/jps-plugin/src/org/jetbrains/jps/devkit/builder/JpsPluginSyntheticArtifactProvider.java
plugins/eclipse/common-eclipse-util/src/EclipseProjectFinder.java
plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathSerializer.java
plugins/eclipse/testSources/org/jetbrains/idea/eclipse/EclipseImlTest.java
plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/CloudGitDeploymentRuntime.java
plugins/git4idea/src/git4idea/GitPlatformFacade.java
plugins/git4idea/src/git4idea/GitPlatformFacadeImpl.java
plugins/git4idea/src/git4idea/actions/GitStash.java
plugins/git4idea/src/git4idea/branch/GitBranchIsNotFullyMergedDialog.java
plugins/git4idea/src/git4idea/branch/GitBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitBranchUiHandlerImpl.java
plugins/git4idea/src/git4idea/branch/GitBranchWorker.java
plugins/git4idea/src/git4idea/branch/GitBrancherImpl.java
plugins/git4idea/src/git4idea/branch/GitCheckoutNewBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitCheckoutOperation.java
plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitDeleteRemoteBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitMergeOperation.java
plugins/git4idea/src/git4idea/branch/GitRenameBranchOperation.java
plugins/git4idea/src/git4idea/branch/GitSmartOperationDialog.java
plugins/git4idea/src/git4idea/checkin/GitCheckinEnvironment.java
plugins/git4idea/src/git4idea/checkin/GitCheckinHandlerFactory.java
plugins/git4idea/src/git4idea/cherrypick/GitCherryPicker.java
plugins/git4idea/src/git4idea/commands/GitSSHGUIHandler.java
plugins/git4idea/src/git4idea/crlf/GitCrlfProblemsDetector.java
plugins/git4idea/src/git4idea/log/GitShowExternalLogAction.java
plugins/git4idea/src/git4idea/merge/GitConflictResolver.java
plugins/git4idea/src/git4idea/merge/GitMergeCommittingConflictResolver.java
plugins/git4idea/src/git4idea/push/GitPushOperation.java
plugins/git4idea/src/git4idea/rebase/GitAbortRebaseProcess.java
plugins/git4idea/src/git4idea/rebase/GitRebaseProcess.java
plugins/git4idea/src/git4idea/rebase/GitRebaseSpec.java
plugins/git4idea/src/git4idea/rebase/GitRebaser.java
plugins/git4idea/src/git4idea/repo/GitConfig.java
plugins/git4idea/src/git4idea/repo/GitRemote.java
plugins/git4idea/src/git4idea/repo/GitRepositoryCreator.java
plugins/git4idea/src/git4idea/repo/GitRepositoryImpl.java
plugins/git4idea/src/git4idea/repo/GitRepositoryManager.java
plugins/git4idea/src/git4idea/reset/GitResetOperation.java
plugins/git4idea/src/git4idea/stash/GitChangesSaver.java
plugins/git4idea/src/git4idea/stash/GitShelveChangesSaver.java
plugins/git4idea/src/git4idea/stash/GitStashChangesSaver.java
plugins/git4idea/src/git4idea/ui/GitUnstashDialog.java
plugins/git4idea/src/git4idea/ui/branch/GitLogBranchOperationsActionGroup.java
plugins/git4idea/src/git4idea/update/GitMergeUpdater.java
plugins/git4idea/src/git4idea/update/GitUpdateEnvironment.java
plugins/git4idea/src/git4idea/update/GitUpdateProcess.java
plugins/git4idea/src/git4idea/util/GitFreezingProcess.java
plugins/git4idea/src/git4idea/util/GitPreservingProcess.java
plugins/git4idea/test-stepdefs/git4idea/GitAddSteps.java
plugins/git4idea/test-stepdefs/git4idea/GitCherryPickStepdefs.java
plugins/git4idea/test-stepdefs/git4idea/GitCucumberWorld.java
plugins/git4idea/tests/git4idea/branch/GitBranchWorkerTest.java
plugins/git4idea/tests/git4idea/crlf/GitCrlfProblemsDetectorTest.java
plugins/git4idea/tests/git4idea/rebase/GitMultiRepoRebaseTest.kt
plugins/git4idea/tests/git4idea/rebase/GitSingleRepoRebaseTest.kt
plugins/git4idea/tests/git4idea/repo/GitConfigTest.java
plugins/git4idea/tests/git4idea/repo/GitRepositoryReaderNewTest.kt
plugins/git4idea/tests/git4idea/repo/GitRepositoryReaderTest.java
plugins/git4idea/tests/git4idea/test/GitPlatformTest.kt
plugins/github/src/org/jetbrains/plugins/github/GithubRebaseAction.java
plugins/gradle/jps-plugin/src/org/jetbrains/jps/gradle/model/impl/JpsGradleExtensionServiceImpl.java
plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleResourceCompilerConfigurationGenerator.java
plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleConsoleProperties.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/GroovyCoreEnvironment.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/api/statements/typedef/GrTypeDefinition.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrAnnotationUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/GrFieldImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrAnnotationTypeDefinitionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrAnonymousClassDefinitionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrEnumTypeDefinitionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrTypeDefinitionImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/GrTypeDefinitionMembersCache.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/members/GrMethodBaseImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrAccessorMethodImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightField.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrLightMethodBuilder.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/synthetic/GrReflectedMethodImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/types/GrTypeParameterImpl.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrClassImplUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/GrTraitUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CollectClassMembersUtil.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/NonCodeMembersContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/AstTransformContributor.java [deleted file]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/AutoCloneContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/AutoExternalizeContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/ConstructorAnnotationsProcessor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/DelegatedMethodsContributor.java [deleted file]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/InheritConstructorContributor.java [moved from plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/GrInheritConstructorContributor.java with 81% similarity]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/LoggingContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/bindable/BindableTransformContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/BuilderAnnotationContributor.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/strategy/DefaultBuilderStrategySupport.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/strategy/ExternalBuilderStrategySupport.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/strategy/InitializerBuilderStrategySupport.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ast/builder/strategy/SimpleBuilderStrategySupport.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/GroovyResolverProcessorBuilder.java
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/AstTransformationSupport.java [moved from platform/usageView/src/com/intellij/usages/actions/ExcludeUsageAction.java with 56% similarity]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationContext.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationContextImpl.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationUtil.kt [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/CategoryTransformationSupport.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/DefaultTransformationSupport.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/DelegateTransformationSupport.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/TraitTransformationSupport.java [new file with mode: 0644]
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/util/dynamicMembers/DynamicMemberUtils.java
plugins/groovy/src/META-INF/plugin.xml
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GrMainCompletionProvider.java
plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyNoVariantsDelegator.java
plugins/groovy/src/org/jetbrains/plugins/groovy/template/GroovyShortenFQNamesProcessor.java
plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/DelegateTest.groovy
plugins/hg4idea/src/org/zmlx/hg4idea/provider/commit/HgCheckinEnvironment.java
plugins/junit/test/com/intellij/execution/junit/JUnitTreeByDescriptionHierarchyTest.java
plugins/junit_rt/src/com/intellij/junit4/JUnit4TestListener.java
plugins/maven/jps-plugin/src/org/jetbrains/jps/maven/model/impl/JpsMavenExtensionServiceImpl.java
plugins/maven/src/main/java/org/jetbrains/idea/maven/indices/MavenIndicesManager.java
plugins/properties/src/com/intellij/codeInsight/editorActions/enter/EnterInPropertiesFileHandler.java
plugins/properties/testSrc/com/intellij/lang/properties/ResourceBundleTest.java
plugins/svn4idea/src/org/jetbrains/idea/svn/actions/AbstractShowPropertiesDiffAction.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ChangeFormatDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/LockDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSHCredentialsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SSLCredentialsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectCreateExternalTargetDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SelectLocationDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/ShareDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SimpleCredentialsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/UpgradeFormatDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/UserNameCredentialsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/DeleteOptionsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ExportOptionsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/browser/ImportOptionsDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/history/RootsAndBranches.java
plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnEditCommitMessageDialog.java
plugins/svn4idea/src/org/jetbrains/idea/svn/history/SvnMergeInfoRootPanelManual.java
plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/TreeConflictRefreshablePanel.java
plugins/svn4idea/testSource/org/jetbrains/idea/svn/SvnTestDirtyScopeStateTest.java
python/src/com/jetbrains/python/codeInsight/intentions/PyBaseConvertCollectionLiteralIntention.java
python/src/com/jetbrains/python/codeInsight/intentions/PyConvertLiteralToSetIntention.java
python/src/com/jetbrains/python/codeInsight/intentions/PyConvertLiteralToTupleIntention.java
python/src/com/jetbrains/python/debugger/array/ArrayTableCellRenderer.java
python/src/com/jetbrains/python/sdk/PythonSdkDetailsStep.java
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/cannotConvertEmptyListToSet.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/cannotConvertEmptyTupleToSet.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementIncompleteListToTuple.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementIncompleteListToTuple_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListToTuple.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListToTuple_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListWithCommaAfterCommentToTuple.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListWithCommaAfterCommentToTuple_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListWithCommentToTuple.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementListWithCommentToTuple_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleToList.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleToList_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleWithCommentToList.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleWithCommentToList_after.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleWithoutParenthesesToSet.py [new file with mode: 0644]
python/testData/intentions/PyConvertCollectionLiteralIntentionTest/convertOneElementTupleWithoutParenthesesToSet_after.py [new file with mode: 0644]
python/testSrc/com/jetbrains/python/intentions/PyConvertCollectionLiteralIntentionTest.java
xml/impl/src/com/intellij/application/options/editor/XmlCodeFoldingOptionsProvider.java
xml/impl/src/com/intellij/codeInsight/template/emmet/EmmetPreviewHint.java
xml/impl/src/com/intellij/xml/util/documentation/XmlDocumentationProvider.java
xml/relaxng/test/org/intellij/plugins/relaxNG/RncRenameTest.java
xml/tests/src/com/intellij/codeInsight/XmlDocumentationTest.java
xml/tests/src/com/intellij/xml/XmlFoldingTest.java
xml/tests/testData/folding/entities.html [new file with mode: 0644]
xml/xml-psi-api/src/com/intellij/lang/XmlCodeFoldingSettings.java
xml/xml-psi-impl/src/com/intellij/application/options/editor/XmlFoldingSettings.java
xml/xml-psi-impl/src/com/intellij/lang/XmlCodeFoldingBuilder.java

index 50dcda444624a9dd3e8161fff8112c99b75b41b3..d3c6597e296c96388b84e7889b29fa386ce6baef 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.
@@ -34,7 +34,7 @@ binding.setVariable("loadModule", {File moduleFile ->
   def moduleName = FileUtil.getNameWithoutExtension(moduleFile)
   def module = JpsElementFactory.instance.createModule(moduleName, JpsJavaModuleType.INSTANCE, JpsElementFactory.instance.createDummyElement())
   def expander = createModuleMacroExpander(new HashMap<String, String>(), moduleFile)
-  def rootElement = JDOMUtil.loadDocument(moduleFile).rootElement
+  def rootElement = JDOMUtil.load(moduleFile)
   expander.substitute(rootElement, SystemInfo.isFileSystemCaseSensitive)
   JpsModuleRootModelSerializer.loadRootModel(module, JDomSerializationUtil.findComponent(rootElement, "NewModuleRootManager"),
                                              JpsJavaSdkType.INSTANCE)
index 2d9742863629c584bcc2abb51d87bc3b622d012e..9059f6dadd86f649ff0c31a0539a67cd29e6acef 100644 (file)
@@ -387,14 +387,14 @@ public class BuildManager implements Disposable {
           return;
         }
         synchronized (myProjectDataMap) {
-          if (IS_UNIT_TEST_MODE) {
-            if (notifyDeletion) {
-              LOG.info("Registering deleted paths: " + filtered);
-            }
-            else {
-              LOG.info("Registering changed paths: " + filtered);
-            }
-          }
+          //if (IS_UNIT_TEST_MODE) {
+          //  if (notifyDeletion) {
+          //    LOG.info("Registering deleted paths: " + filtered);
+          //  }
+          //  else {
+          //    LOG.info("Registering changed paths: " + filtered);
+          //  }
+          //}
           for (Map.Entry<String, ProjectData> entry : myProjectDataMap.entrySet()) {
             final ProjectData data = entry.getValue();
             if (notifyDeletion) {
index f07cb5301613691e6cef6c9556126cd28aa96feb..dd5d7148e811fb56989ff8f15db16fd47c1d4d1b 100644 (file)
@@ -17,6 +17,7 @@ package com.intellij.execution;
 
 import com.intellij.ExtensionPoints;
 import com.intellij.debugger.impl.GenericDebuggerRunnerSettings;
+import com.intellij.diagnostic.logging.OutputFileUtil;
 import com.intellij.execution.configurations.*;
 import com.intellij.execution.process.OSProcessHandler;
 import com.intellij.execution.process.ProcessAdapter;
@@ -124,7 +125,8 @@ public abstract class JavaTestFrameworkRunnableState<T extends ModuleBasedConfig
       @Override
       public void startNotified(ProcessEvent event) {
         if (getConfiguration().isSaveOutputToFile()) {
-          root.setOutputFilePath(getConfiguration().getOutputFilePath());
+          final File file = OutputFileUtil.getOutputFile(getConfiguration());
+          root.setOutputFilePath(file != null ? file.getAbsolutePath() : null);
         }
       }
 
index d49624954ff0456b163d7f0c2bd4a246c37f15e7..9e779808534d395e32ddac5804a1380907f3f06d 100644 (file)
@@ -60,7 +60,7 @@ public abstract class JavaAwareTestConsoleProperties<T extends ModuleBasedConfig
   }
 
   @Override
-  protected int getSelectionMode() {
+  public int getSelectionMode() {
     return TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION;
   }
 
index 346b9cf718182d4cace5fea6815b24953aa03e1f..4c581d81f585f091ff2aba0138d4b22a42e8b1cb 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.
@@ -27,6 +27,7 @@ import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.CollectionComboBoxModel;
 import com.intellij.util.containers.HashSet;
 import com.intellij.util.containers.hash.HashMap;
+import com.intellij.util.ui.JBUI;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -165,10 +166,10 @@ public abstract class VersionsComponent {
 
   private void addToPanel(@NotNull JComponent first, @NotNull JComponent second) {
     myMainPanel.add(first, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.LINE_START,
-                                                  GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0));
+                                                  GridBagConstraints.BOTH, JBUI.insets(2), 0, 0));
     myMainPanel.add(second,
                     new GridBagConstraints(1, GridBagConstraints.RELATIVE, 1, 1, 1, 0, GridBagConstraints.LINE_END, GridBagConstraints.BOTH,
-                                           new Insets(2, 2, 2, 2), 0, 0));
+                                           JBUI.insets(2), 0, 0));
   }
 
   private JRadioButton createRadioButton(final String ri) {
index c545cca19bf14a26013ade3a5ebf27e01fc392ae..cb458b2493fb401c3965ebd891bc96b458a47799 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 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.
@@ -34,7 +34,6 @@ import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.JDOMUtil;
-import org.jdom.Document;
 import org.jdom.Element;
 import org.jdom.JDOMException;
 import org.jetbrains.annotations.NotNull;
@@ -62,6 +61,7 @@ public class ExistingModuleLoader extends ModuleBuilder {
     return moduleLoader;
   }
 
+  @Override
   @NotNull
   public Module createModule(@NotNull ModifiableModuleModel moduleModel)
     throws InvalidDataException, IOException, ModuleWithNameAlreadyExists, JDOMException, ConfigurationException {
@@ -75,14 +75,17 @@ public class ExistingModuleLoader extends ModuleBuilder {
     return moduleModel.loadModule(moduleFilePath);
   }
 
+  @Override
   public void setupRootModel(ModifiableRootModel modifiableRootModel) throws ConfigurationException {
     // empty
   }
 
+  @Override
   public ModuleType getModuleType() {
     return null; // no matter
   }
 
+  @Override
   public boolean validate(final Project current, final Project dest) {
     if (getName() == null) return false;
     String moduleFilePath = getModuleFilePath();
@@ -94,8 +97,7 @@ public class ExistingModuleLoader extends ModuleBuilder {
         if (result.openingIsCanceled()) {
           return false;
         }
-        final Document document = JDOMUtil.loadDocument(file);
-        final Element root = document.getRootElement();
+        final Element root = JDOMUtil.load(file);
         final Set<String> usedMacros = PathMacrosCollector.getMacroNames(root);
         final Set<String> definedMacros = PathMacros.getInstance().getAllMacroNames();
         usedMacros.remove("$" + PathMacrosImpl.MODULE_DIR_MACRO_NAME + "$");
index 26e133464ebdf481b57d50a7fde72d4f661f6317..5e84612e1b343bd039d99a49b367dfe62c803684 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 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.
@@ -166,10 +166,12 @@ public class ProjectFromSourcesBuilderImpl extends ProjectImportBuilder implemen
   public void setOpenProjectSettingsAfter(boolean on) {
   }
 
+  @Override
   public void setFileToImport(String path) {
     setBaseProjectPath(path);
   }
 
+  @Override
   public List<Module> commit(@NotNull final Project project, final ModifiableModuleModel model, final ModulesProvider modulesProvider) {
     final boolean fromProjectStructure = model != null;
     ModifiableModelsProvider modelsProvider = new IdeaModifiableModelsProvider();
@@ -306,6 +308,7 @@ public class ProjectFromSourcesBuilderImpl extends ProjectImportBuilder implemen
     myUpdaters.add(updater);
   }
 
+  @Override
   public boolean hasRootsFromOtherDetectors(ProjectStructureDetector thisDetector) {
     for (ProjectStructureDetector projectStructureDetector : Extensions.getExtensions(ProjectStructureDetector.EP_NAME)) {
       if (projectStructureDetector != thisDetector && !getProjectRoots(projectStructureDetector).isEmpty()) {
@@ -321,7 +324,7 @@ public class ProjectFromSourcesBuilderImpl extends ProjectImportBuilder implemen
       List<ModuleDescriptor> modules = new ArrayList<ModuleDescriptor>();
       for (DetectedProjectRoot root : roots) {
         if (root instanceof DetectedContentRoot) {
-          modules.add(new ModuleDescriptor(root.getDirectory(), ((DetectedContentRoot)root).getModuleType(), Collections.<DetectedSourceRoot>emptyList()));
+          modules.add(new ModuleDescriptor(root.getDirectory(), ((DetectedContentRoot)root).getModuleType(), Collections.emptyList()));
         }
       }
       projectDescriptor.setModules(modules);
@@ -405,10 +408,10 @@ public class ProjectFromSourcesBuilderImpl extends ProjectImportBuilder implemen
   }
 
   private static boolean isTestRootName(final String name) {
-    return "test".equalsIgnoreCase(name) || 
-           "tests".equalsIgnoreCase(name) || 
-           "testSource".equalsIgnoreCase(name) || 
-           "testSources".equalsIgnoreCase(name) || 
+    return "test".equalsIgnoreCase(name) ||
+           "tests".equalsIgnoreCase(name) ||
+           "testSource".equalsIgnoreCase(name) ||
+           "testSources".equalsIgnoreCase(name) ||
            "testSrc".equalsIgnoreCase(name) ||
            "tst".equalsIgnoreCase(name);
   }
@@ -437,7 +440,7 @@ public class ProjectFromSourcesBuilderImpl extends ProjectImportBuilder implemen
     if (moduleDescriptor.isReuseExistingElement()) {
       final File file = new File(moduleDescriptor.computeModuleFilePath());
       if (file.exists()) {
-        final Element rootElement = JDOMUtil.loadDocument(file).getRootElement();
+        final Element rootElement = JDOMUtil.load(file);
         final String type = rootElement.getAttributeValue("type");
         if (type != null) {
           return ModuleTypeManager.getInstance().findByID(type);
index e1374f446c7e68dd55b7478088df533eb7add679..21131e5882e9f0dbad0c422d758c4c8696e49bc8 100644 (file)
@@ -25,6 +25,7 @@ import com.intellij.ide.util.projectWizard.ProjectTemplateParameterFactory;
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.module.Module;
@@ -122,16 +123,8 @@ public class SaveProjectAsTemplateAction extends AnAction {
 
     final Map<String, String> parameters = computeParameters(project, replaceParameters);
     indicator.setText("Saving project...");
-    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
-      @Override
-      public void run() {
-        ApplicationManager.getApplication().runWriteAction(new Runnable() {
-          public void run() {
-            project.save();
-          }
-        });
-      }
-    });
+    ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(project::save),
+                                                      indicator.getModalityState());
     indicator.setText("Processing project files...");
     ZipOutputStream stream = null;
     try {
@@ -139,10 +132,10 @@ public class SaveProjectAsTemplateAction extends AnAction {
       stream = new ZipOutputStream(new FileOutputStream(zipFile));
 
       final VirtualFile dir = getDirectoryToSave(project, moduleToSave);
-      writeFile(LocalArchivedTemplate.DESCRIPTION_PATH, description, project, dir, stream, true);
+      writeFile(LocalArchivedTemplate.DESCRIPTION_PATH, description, project, dir, stream, true, indicator);
       if (replaceParameters) {
         String text = getInputFieldsText(parameters);
-        writeFile(LocalArchivedTemplate.TEMPLATE_DESCRIPTOR, text, project, dir, stream, false);
+        writeFile(LocalArchivedTemplate.TEMPLATE_DESCRIPTOR, text, project, dir, stream, false, indicator);
       }
 
       FileIndex index = moduleToSave == null
@@ -205,7 +198,7 @@ public class SaveProjectAsTemplateAction extends AnAction {
 
   private static void writeFile(String path,
                                 final String text,
-                                Project project, VirtualFile dir, ZipOutputStream stream, boolean overwrite) throws IOException {
+                                Project project, VirtualFile dir, ZipOutputStream stream, boolean overwrite, ProgressIndicator indicator) throws IOException {
     final VirtualFile descriptionFile = getDescriptionFile(project, path);
     if (descriptionFile == null) {
       stream.putNextEntry(new ZipEntry(dir.getName() + "/" + path));
@@ -213,21 +206,14 @@ public class SaveProjectAsTemplateAction extends AnAction {
       stream.closeEntry();
     }
     else if (overwrite) {
-      UIUtil.invokeAndWaitIfNeeded(new Runnable() {
-        public void run() {
-          ApplicationManager.getApplication().runWriteAction(new Runnable() {
-            @Override
-            public void run() {
-              try {
-                VfsUtil.saveText(descriptionFile, text);
-              }
-              catch (IOException e) {
-                LOG.error(e);
-              }
-            }
-          });
+      ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(() -> {
+        try {
+          VfsUtil.saveText(descriptionFile, text);
         }
-      });
+        catch (IOException e) {
+          LOG.error(e);
+        }
+      }), indicator.getModalityState());
     }
   }
 
index d6c4c80abfd4bfca6b38550cd7bedb36d392a2d3..c7862042e06156f71708dfd172f37b842688aa8c 100644 (file)
@@ -121,7 +121,13 @@ public class TestOnlyInspection extends BaseJavaBatchLocalInspectionTool {
   @Nullable
   private static PsiAnnotation findVisibleForTestingAnnotation(@NotNull PsiMember member) {
     PsiAnnotation anno = AnnotationUtil.findAnnotation(member, "com.google.common.annotations.VisibleForTesting");
-    return anno != null ? anno : AnnotationUtil.findAnnotation(member, "com.android.annotations.VisibleForTesting");
+    if (anno == null) {
+      anno = AnnotationUtil.findAnnotation(member, "com.android.annotations.VisibleForTesting");
+    }
+    if (anno != null) return anno;
+
+    PsiClass containingClass = member.getContainingClass();
+    return containingClass != null ? findVisibleForTestingAnnotation(containingClass) : null;
   }
 
   private static boolean isInsideTestOnlyMethod(PsiElement e) {
index f760a08f95aed9a0d13f2903d6f7bfa46b44b48b..290d2a15a761a8a90031b1e074783314e338540a 100644 (file)
@@ -23,7 +23,6 @@ import com.intellij.codeInsight.lookup.TailTypeDecorator;
 import com.intellij.patterns.ElementPattern;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.util.Consumer;
 import com.intellij.util.ProcessingContext;
 import org.jetbrains.annotations.NotNull;
 
@@ -48,27 +47,24 @@ class CatchTypeProvider extends CompletionProvider<CompletionParameters> {
     final PsiCodeBlock tryBlock = tryStatement == null ? null : tryStatement.getTryBlock();
     if (tryBlock == null) return;
 
-    final InheritorsHolder holder = new InheritorsHolder(result);
+    final JavaCompletionSession session = new JavaCompletionSession(result);
 
     for (final PsiClassType type : ExceptionUtil.getThrownExceptions(tryBlock.getStatements())) {
       PsiClass typeClass = type.resolve();
       if (typeClass != null) {
         result.addElement(createCatchTypeVariant(tryBlock, type));
-        holder.registerClass(typeClass);
+        session.registerClass(typeClass);
       }
     }
 
     final Collection<PsiClassType> expectedClassTypes = Collections.singletonList(JavaPsiFacade.getElementFactory(
       tryBlock.getProject()).createTypeByFQClassName(CommonClassNames.JAVA_LANG_THROWABLE));
-    JavaInheritorsGetter.processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), new Consumer<PsiType>() {
-      @Override
-      public void consume(PsiType type) {
-        final PsiClass psiClass = type instanceof PsiClassType ? ((PsiClassType)type).resolve() : null;
-        if (psiClass == null || psiClass instanceof PsiTypeParameter) return;
+    JavaInheritorsGetter.processInheritors(parameters, expectedClassTypes, result.getPrefixMatcher(), type -> {
+      final PsiClass psiClass = type instanceof PsiClassType ? ((PsiClassType)type).resolve() : null;
+      if (psiClass == null || psiClass instanceof PsiTypeParameter) return;
 
-        if (!holder.alreadyProcessed(psiClass)) {
-          result.addElement(createCatchTypeVariant(tryBlock, (PsiClassType)type));
-        }
+      if (!session.alreadyProcessed(psiClass)) {
+        result.addElement(createCatchTypeVariant(tryBlock, (PsiClassType)type));
       }
     });
   }
index 5ad4543848c3cbb65a06ce0da37ffdaf97a5c3b9..6400dfc9e12a4f8fefbe587b13711f07744f06c2 100644 (file)
@@ -21,43 +21,39 @@ import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.LookupElementBuilder;
 import com.intellij.icons.AllIcons;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.EditorModificationUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.patterns.ElementPattern;
-import com.intellij.patterns.PatternCondition;
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
 import com.intellij.psi.impl.source.resolve.graphInference.FunctionalInterfaceParameterizationUtil;
+import com.intellij.psi.impl.source.tree.java.MethodReferenceResolver;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.psi.util.TypeConversionUtil;
-import com.intellij.util.Function;
+import com.intellij.util.Consumer;
+import com.intellij.util.ObjectUtils;
 import com.intellij.util.ProcessingContext;
-import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import static com.intellij.patterns.PlatformPatterns.psiElement;
+import java.util.*;
 
 /**
  * User: anna
  */
 public class FunctionalExpressionCompletionProvider extends CompletionProvider<CompletionParameters> {
-  static final ElementPattern<PsiElement> LAMBDA = psiElement().with(new PatternCondition<PsiElement>("LAMBDA_CONTEXT") {
-    @Override
-    public boolean accepts(@NotNull PsiElement element, ProcessingContext context) {
-      return isLambdaContext(element);
-    }});
+
+  private static final InsertHandler<LookupElement> CONSTRUCTOR_REF_INSERT_HANDLER = (context, item) -> {
+    int start = context.getStartOffset();
+    PsiClass psiClass = PsiUtil.resolveClassInType((PsiType)item.getObject());
+    if (psiClass != null) {
+      JavaCompletionUtil.insertClassReference(psiClass, context.getFile(), start,
+                                              start + StringUtil.trimEnd(item.getLookupString(), "::new").length());
+    }
+  };
 
   private static boolean isLambdaContext(@NotNull PsiElement element) {
     final PsiElement rulezzRef = element.getParent();
@@ -71,20 +67,19 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
   protected void addCompletions(@NotNull CompletionParameters parameters,
                                 ProcessingContext context,
                                 @NotNull CompletionResultSet result) {
-    result.addAllElements(getLambdaVariants(parameters, false));
+    addFunctionalVariants(parameters, true, true, result);
   }
 
-  static List<LookupElement> getLambdaVariants(@NotNull CompletionParameters parameters, boolean prioritize) {
-    if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile()) || !isLambdaContext(parameters.getPosition())) return Collections.emptyList();
+  static void addFunctionalVariants(@NotNull CompletionParameters parameters, boolean smart, boolean addInheritors, CompletionResultSet result) {
+    if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile()) || !isLambdaContext(parameters.getPosition())) return;
 
-    List<LookupElement> result = ContainerUtil.newArrayList();
-    for (ExpectedTypeInfo expectedType : JavaSmartCompletionContributor.getExpectedTypes(parameters)) {
+    ExpectedTypeInfo[] expectedTypes = JavaSmartCompletionContributor.getExpectedTypes(parameters);
+    for (ExpectedTypeInfo expectedType : expectedTypes) {
       final PsiType defaultType = expectedType.getDefaultType();
       if (LambdaUtil.isFunctionalType(defaultType)) {
         final PsiType functionalInterfaceType = FunctionalInterfaceParameterizationUtil.getGroundTargetType(defaultType);
         final PsiMethod functionalInterfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
         if (functionalInterfaceMethod != null) {
-          assert functionalInterfaceType != null;
           PsiParameter[] params = new PsiParameter[0];
           final PsiElement originalPosition = parameters.getPosition();
           final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(functionalInterfaceMethod, PsiUtil.resolveGenericsClassInType(functionalInterfaceType));
@@ -98,12 +93,8 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
             }
 
             String paramsString =
-              params.length == 1 ? getParamName(params[0], javaCodeStyleManager, originalPosition) : "(" + StringUtil.join(params, new Function<PsiParameter, String>() {
-              @Override
-              public String fun(PsiParameter parameter) {
-                return getParamName(parameter, javaCodeStyleManager, originalPosition);
-              }
-              }, ",") + ")";
+              params.length == 1 ? getParamName(params[0], originalPosition)
+                                 : "(" + StringUtil.join(params, parameter -> getParamName(parameter, originalPosition), ",") + ")";
 
             final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project);
             PsiLambdaExpression lambdaExpression = (PsiLambdaExpression)JavaPsiFacade.getElementFactory(project)
@@ -112,64 +103,86 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
             paramsString = lambdaExpression.getParameterList().getText();
             final LookupElementBuilder builder =
               LookupElementBuilder.create(functionalInterfaceMethod, paramsString)
-                .withPresentableText(paramsString + " -> {}").withInsertHandler(new InsertHandler<LookupElement>() {
-                @Override
-                public void handleInsert(InsertionContext context, LookupElement item) {
-                  final Editor editor = context.getEditor();
-                  EditorModificationUtil.insertStringAtCaret(editor, " -> ");
-                }
-              })
+                .withPresentableText(paramsString + " -> {}")
+                .withInsertHandler((context, item) -> EditorModificationUtil.insertStringAtCaret(context.getEditor(), " -> "))
                 .withTypeText(functionalInterfaceType.getPresentableText())
                 .withIcon(AllIcons.Nodes.Function);
             LookupElement lambdaElement = builder.withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
-            if (prioritize) {
-              lambdaElement = PrioritizedLookupElement.withPriority(lambdaElement, 1);
-            }
-            result.add(lambdaElement);
+            result.addElement(smart ? lambdaElement : PrioritizedLookupElement.withPriority(lambdaElement, 1));
           }
 
-          final PsiType expectedReturnType = substitutor.substitute(functionalInterfaceMethod.getReturnType());
-          if (expectedReturnType != null) {
-            if (params.length > 0) {
-              collectVariantsByReceiver(prioritize, functionalInterfaceType, params, originalPosition, substitutor, expectedReturnType, result);
-            }
-            collectThisVariants(functionalInterfaceType, params, originalPosition, substitutor, expectedReturnType, result);
-            final PsiClass psiClass = PsiUtil.resolveClassInType(expectedReturnType);
-            if (psiClass != null && !(psiClass instanceof PsiTypeParameter)) {
-              if (expectedReturnType.getArrayDimensions() == 0) {
-                final PsiMethod[] constructors = psiClass.getConstructors();
-                for (PsiMethod psiMethod : constructors) {
-                  if (areParameterTypesAppropriate(psiMethod, params, substitutor, 0)) {
-                    result.add(createConstructorReferenceLookup(functionalInterfaceType, expectedReturnType));
-                  }
-                }
-                if (constructors.length == 0 && params.length == 0) {
-                  result.add(createConstructorReferenceLookup(functionalInterfaceType, expectedReturnType));
-                }
-              }
-              else if (params.length == 1 && PsiType.INT.equals(params[0].getType())){
-                result.add(createConstructorReferenceLookup(functionalInterfaceType, expectedReturnType));
-              }
-            }
+          addMethodReferenceVariants(
+            smart, addInheritors, parameters, result.getPrefixMatcher(), functionalInterfaceType, functionalInterfaceMethod, params, originalPosition, substitutor,
+            element -> result.addElement(smart ? JavaSmartCompletionContributor.decorate(element, Arrays.asList(expectedTypes)) : element));
+        }
+      }
+    }
+  }
+
+  private static void addMethodReferenceVariants(boolean smart,
+                                                 boolean addInheritors,
+                                                 CompletionParameters parameters,
+                                                 PrefixMatcher matcher,
+                                                 PsiType functionalInterfaceType,
+                                                 PsiMethod functionalInterfaceMethod,
+                                                 PsiParameter[] params,
+                                                 PsiElement originalPosition,
+                                                 PsiSubstitutor substitutor,
+                                                 Consumer<LookupElement> result) {
+    final PsiType expectedReturnType = substitutor.substitute(functionalInterfaceMethod.getReturnType());
+    if (expectedReturnType == null) return;
+
+    if (params.length > 0) {
+      for (LookupElement element : collectVariantsByReceiver(!smart, functionalInterfaceType, params, originalPosition, substitutor, expectedReturnType)) {
+        result.consume(element);
+      }
+    }
+    for (LookupElement element : collectThisVariants(functionalInterfaceType, params, originalPosition, substitutor, expectedReturnType)) {
+      result.consume(element);
+    }
+
+    Consumer<PsiType> consumer = eachReturnType -> {
+      PsiClass psiClass = PsiUtil.resolveClassInType(eachReturnType);
+      if (psiClass == null || psiClass instanceof PsiTypeParameter) return;
+
+      if (eachReturnType.getArrayDimensions() == 0) {
+        PsiMethod[] constructors = psiClass.getConstructors();
+        for (PsiMethod psiMethod : constructors) {
+          if (areParameterTypesAppropriate(psiMethod, params, substitutor, 0)) {
+            result.consume(createConstructorReferenceLookup(functionalInterfaceType, eachReturnType));
           }
         }
+        if (constructors.length == 0 && params.length == 0 && MethodReferenceResolver.canBeConstructed(psiClass)) {
+          result.consume(createConstructorReferenceLookup(functionalInterfaceType, eachReturnType));
+        }
+      }
+      else if (params.length == 1 && PsiType.INT.equals(params[0].getType())) {
+        result.consume(createConstructorReferenceLookup(functionalInterfaceType, eachReturnType));
       }
+    };
+    if (addInheritors && expectedReturnType instanceof PsiClassType) {
+      JavaInheritorsGetter.processInheritors(parameters, Collections.singletonList((PsiClassType)expectedReturnType), matcher, consumer);
+    } else {
+      consumer.consume(expectedReturnType);
     }
-    return result;
   }
 
-  private static LookupElement createConstructorReferenceLookup(PsiType functionalInterfaceType, PsiType expectedReturnType) {
+  private static LookupElement createConstructorReferenceLookup(@NotNull PsiType functionalInterfaceType, 
+                                                                @NotNull PsiType constructedType) {
+    constructedType = TypeConversionUtil.erasure(constructedType);
     return LookupElementBuilder
-                      .create(expectedReturnType.getPresentableText() + "::new")
+                      .create(constructedType, constructedType.getPresentableText() + "::new")
                       .withTypeText(functionalInterfaceType.getPresentableText())
                       .withIcon(AllIcons.Nodes.MethodReference)
+                      .withInsertHandler(CONSTRUCTOR_REF_INSERT_HANDLER)
                       .withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
   }
 
-  private static void collectThisVariants(PsiType functionalInterfaceType,
-                                          PsiParameter[] params,
-                                          PsiElement originalPosition,
-                                          PsiSubstitutor substitutor, PsiType expectedReturnType, List<LookupElement> result) {
+  private static List<LookupElement> collectThisVariants(PsiType functionalInterfaceType,
+                                                         PsiParameter[] params,
+                                                         PsiElement originalPosition,
+                                                         PsiSubstitutor substitutor, PsiType expectedReturnType) {
+    List<LookupElement> result = new ArrayList<>();
     final PsiClass psiClass = PsiTreeUtil.getParentOfType(originalPosition, PsiClass.class);
     if (psiClass != null) {
       for (PsiMethod psiMethod : psiClass.getMethods()) {
@@ -179,14 +192,7 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
           LookupElement methodRefLookupElement = LookupElementBuilder
             .create(psiMethod)
             .withPresentableText("this::" + psiMethod.getName())
-            .withInsertHandler(new InsertHandler<LookupElement>() {
-              @Override
-              public void handleInsert(InsertionContext context, LookupElement item) {
-                final int startOffset = context.getStartOffset();
-                final Document document = context.getDocument();
-                document.insertString(startOffset, "this::");
-              }
-            })
+            .withInsertHandler((context, item) -> context.getDocument().insertString(context.getStartOffset(), "this::"))
             .withTypeText(functionalInterfaceType.getPresentableText())
             .withIcon(AllIcons.Nodes.MethodReference)
             .withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
@@ -194,48 +200,47 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
         }
       }
     }
+    return result;
   }
 
-  private static void collectVariantsByReceiver(boolean prioritize,
-                                                PsiType functionalInterfaceType,
-                                                PsiParameter[] params,
-                                                PsiElement originalPosition,
-                                                PsiSubstitutor substitutor, 
-                                                PsiType expectedReturnType,
-                                                List<LookupElement> result) {
+  private static List<LookupElement> collectVariantsByReceiver(boolean prioritize,
+                                                               PsiType functionalInterfaceType,
+                                                               PsiParameter[] params,
+                                                               PsiElement originalPosition,
+                                                               PsiSubstitutor substitutor,
+                                                               PsiType expectedReturnType) {
+    List<LookupElement> result = new ArrayList<>();
     final PsiType functionalInterfaceParamType = substitutor.substitute(params[0].getType());
     final PsiClass paramClass = PsiUtil.resolveClassInClassTypeOnly(functionalInterfaceParamType);
     if (paramClass != null && !paramClass.hasTypeParameters()) {
       final Set<String> visited = new HashSet<String>();
       for (PsiMethod psiMethod : paramClass.getAllMethods()) {
         final PsiType returnType = psiMethod.getReturnType();
+        PsiClass containingClass = psiMethod.getContainingClass();
+        PsiClass qualifierClass = containingClass != null ? containingClass : paramClass;
         if (visited.add(psiMethod.getName()) &&
             isInstanceMethodWithAppropriateReturnType(expectedReturnType, psiMethod, returnType) &&
             areParameterTypesAppropriate(psiMethod, params, substitutor, 1) &&
             JavaResolveUtil.isAccessible(psiMethod, null, psiMethod.getModifierList(), originalPosition, null, null)) {
           LookupElement methodRefLookupElement = LookupElementBuilder
             .create(psiMethod)
-            .withPresentableText(paramClass.getName() + "::" + psiMethod.getName())
-            .withInsertHandler(new InsertHandler<LookupElement>() {
-              @Override
-              public void handleInsert(InsertionContext context, LookupElement item) {
-                final int startOffset = context.getStartOffset();
-                final Document document = context.getDocument();
-                final PsiFile file = context.getFile();
-                document.insertString(startOffset, "::");
-                JavaCompletionUtil.insertClassReference(paramClass, file, startOffset);
-              }
+            .withPresentableText(qualifierClass.getName() + "::" + psiMethod.getName())
+            .withInsertHandler((context, item) -> {
+              int startOffset = context.getStartOffset();
+              context.getDocument().insertString(startOffset, "::");
+              JavaCompletionUtil.insertClassReference(qualifierClass, context.getFile(), startOffset);
             })
             .withTypeText(functionalInterfaceType.getPresentableText())
             .withIcon(AllIcons.Nodes.MethodReference)
             .withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
-          if (prioritize && psiMethod.getContainingClass() == paramClass) {
+          if (prioritize && containingClass == paramClass) {
             methodRefLookupElement = PrioritizedLookupElement.withPriority(methodRefLookupElement, 1);
           }
           result.add(methodRefLookupElement);
         }
       }
     }
+    return result;
   }
 
   private static boolean isInstanceMethodWithAppropriateReturnType(PsiType expectedReturnType, PsiMethod psiMethod, PsiType returnType) {
@@ -258,7 +263,8 @@ public class FunctionalExpressionCompletionProvider extends CompletionProvider<C
     return false;
   }
 
-  private static String getParamName(PsiParameter param, JavaCodeStyleManager javaCodeStyleManager, PsiElement originalPosition) {
-    return javaCodeStyleManager.suggestUniqueVariableName(param.getName(), originalPosition, false);
+  private static String getParamName(PsiParameter param, PsiElement originalPosition) {
+    return JavaCodeStyleManager.getInstance(originalPosition.getProject()).suggestUniqueVariableName(
+      ObjectUtils.assertNotNull(param.getName()), originalPosition, false);
   }
 }
index 1a674347b59201962a4e23247f85da6ec6a61a04..c7650c5da451a0ed792900fb592e9b6702e8e213 100644 (file)
@@ -36,7 +36,6 @@ import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import org.jetbrains.annotations.NotNull;
 
-import static com.intellij.patterns.PsiJavaPatterns.psiElement;
 import static com.intellij.psi.codeStyle.JavaCodeStyleSettings.*;
 
 /**
@@ -175,7 +174,8 @@ class JavaClassNameInsertHandler implements InsertHandler<JavaPsiClassReferenceE
     if (!(obj instanceof PsiClass) || !((PsiClass)obj).isAnnotationType()) return false;
 
     PsiElement leaf = context.getFile().findElementAt(context.getStartOffset());
-    return psiElement(PsiIdentifier.class).withParents(PsiJavaCodeReferenceElement.class, PsiAnnotation.class).accepts(leaf);
+    PsiAnnotation anno = PsiTreeUtil.getParentOfType(leaf, PsiAnnotation.class);
+    return anno != null && PsiTreeUtil.isAncestor(anno.getNameReferenceElement(), leaf, false);
   }
 
   static boolean shouldHaveAnnotationParameters(PsiClass annoClass) {
index 8c23fc2712bc2cd089325f7a7431c62a11232541..fbac2bb0e9bc719fd600ab41bc50f4602c854a0d 100644 (file)
@@ -53,7 +53,6 @@ import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.psi.util.TypeConversionUtil;
-import com.intellij.util.Consumer;
 import com.intellij.util.DocumentUtil;
 import com.intellij.util.PairConsumer;
 import com.intellij.util.ProcessingContext;
@@ -215,10 +214,11 @@ public class JavaCompletionContributor extends CompletionContributor {
     }
 
     final CompletionResultSet result = JavaCompletionSorting.addJavaSorting(parameters, _result);
+    JavaCompletionSession session = new JavaCompletionSession(result);
 
     if (ANNOTATION_ATTRIBUTE_NAME.accepts(position) && !JavaKeywordCompletion.isAfterPrimitiveOrArrayType(position)) {
       JavaKeywordCompletion.addExpectedTypeMembers(parameters, result);
-      JavaKeywordCompletion.addPrimitiveTypes(result, position);
+      JavaKeywordCompletion.addPrimitiveTypes(result, position, session);
       completeAnnotationAttributeName(result, position, parameters);
       result.stopHere();
       return;
@@ -227,12 +227,11 @@ public class JavaCompletionContributor extends CompletionContributor {
     PrefixMatcher matcher = result.getPrefixMatcher();
     PsiElement parent = position.getParent();
 
-    final InheritorsHolder inheritors = new InheritorsHolder(result);
     if (position instanceof PsiIdentifier) {
-      addIdentifierVariants(parameters, position, result, matcher, parent, inheritors);
+      addIdentifierVariants(parameters, position, result, matcher, parent, session);
     }
 
-    Set<String> usedWords = addReferenceVariants(parameters, result, inheritors);
+    Set<String> usedWords = addReferenceVariants(parameters, result, session);
 
     if (psiElement().inside(PsiLiteralExpression.class).accepts(position)) {
       PsiReference reference = position.getContainingFile().findReferenceAt(parameters.getOffset());
@@ -245,7 +244,11 @@ public class JavaCompletionContributor extends CompletionContributor {
       JavaGenerateMemberCompletionContributor.fillCompletionVariants(parameters, result);
     }
 
-    addAllClasses(parameters, result, inheritors);
+    addAllClasses(parameters, result, session);
+
+    if (position instanceof PsiIdentifier) {
+      FunctionalExpressionCompletionProvider.addFunctionalVariants(parameters, false, true, result);
+    }
 
     if (position instanceof PsiIdentifier &&
         parent instanceof PsiReferenceExpression &&
@@ -260,34 +263,28 @@ public class JavaCompletionContributor extends CompletionContributor {
   private static void addIdentifierVariants(@NotNull CompletionParameters parameters,
                                             PsiElement position,
                                             final CompletionResultSet result,
-                                            PrefixMatcher matcher, PsiElement parent, final InheritorsHolder inheritors) {
+                                            PrefixMatcher matcher, PsiElement parent, @NotNull JavaCompletionSession session) {
     if (TypeArgumentCompletionProvider.IN_TYPE_ARGS.accepts(position)) {
-      new TypeArgumentCompletionProvider(false, inheritors).addCompletions(parameters, new ProcessingContext(), result);
+      new TypeArgumentCompletionProvider(false, session).addCompletions(parameters, new ProcessingContext(), result);
     }
 
-    result.addAllElements(FunctionalExpressionCompletionProvider.getLambdaVariants(parameters, true));
+    FunctionalExpressionCompletionProvider.addFunctionalVariants(parameters, false, false, result);
 
     if (JavaSmartCompletionContributor.AFTER_NEW.accepts(position)) {
-      new JavaInheritorsGetter(ConstructorInsertHandler.BASIC_INSTANCE).generateVariants(parameters, matcher, inheritors);
+      new JavaInheritorsGetter(ConstructorInsertHandler.BASIC_INSTANCE).generateVariants(parameters, matcher, session);
     }
 
     if (MethodReturnTypeProvider.IN_METHOD_RETURN_TYPE.accepts(position)) {
-      MethodReturnTypeProvider.addProbableReturnTypes(parameters, new Consumer<LookupElement>() {
-        @Override
-        public void consume(LookupElement element) {
-          registerClassFromTypeElement(element, inheritors);
-          result.addElement(element);
-        }
+      MethodReturnTypeProvider.addProbableReturnTypes(parameters, element -> {
+        registerClassFromTypeElement(element, session);
+        result.addElement(element);
       });
     }
 
     if (SmartCastProvider.shouldSuggestCast(parameters)) {
-      SmartCastProvider.addCastVariants(parameters, new Consumer<LookupElement>() {
-        @Override
-        public void consume(LookupElement element) {
-          registerClassFromTypeElement(element, inheritors);
-          result.addElement(PrioritizedLookupElement.withPriority(element, 1));
-        }
+      SmartCastProvider.addCastVariants(parameters, element -> {
+        registerClassFromTypeElement(element, session);
+        result.addElement(PrioritizedLookupElement.withPriority(element, 1));
       });
     }
 
@@ -301,17 +298,22 @@ public class JavaCompletionContributor extends CompletionContributor {
       result.addElement(LookupElementBuilder.create("*"));
     }
 
-    addKeywords(parameters, result);
+    addKeywords(parameters, result, session);
 
     addExpressionVariants(parameters, position, result);
   }
 
-  private static void registerClassFromTypeElement(LookupElement element, InheritorsHolder inheritors) {
+  private static void registerClassFromTypeElement(LookupElement element, JavaCompletionSession session) {
     PsiType type = assertNotNull(element.as(PsiTypeLookupItem.CLASS_CONDITION_KEY)).getType();
+    if (type instanceof PsiPrimitiveType) {
+      session.registerKeyword(type.getCanonicalText(false));
+      return;
+    }
+
     PsiClass aClass =
       type instanceof PsiClassType && ((PsiClassType)type).getParameterCount() == 0 ? ((PsiClassType)type).resolve() : null;
     if (aClass != null) {
-      inheritors.registerClass(aClass);
+      session.registerClass(aClass);
     }
   }
 
@@ -331,18 +333,15 @@ public class JavaCompletionContributor extends CompletionContributor {
 
   public static void addAllClasses(final CompletionParameters parameters,
                                    final CompletionResultSet result,
-                                   final InheritorsHolder inheritors) {
+                                   final JavaCompletionSession session) {
     if (!isClassNamePossible(parameters) || !mayStartClassName(result)) {
       return;
     }
 
     if (parameters.getInvocationCount() >= 2) {
-      JavaClassNameCompletionContributor.addAllClasses(parameters, parameters.getInvocationCount() <= 2, result.getPrefixMatcher(), new Consumer<LookupElement>() {
-        @Override
-        public void consume(LookupElement element) {
-          if (!inheritors.alreadyProcessed(element)) {
-            result.addElement(JavaClassNameCompletionContributor.highlightIfNeeded((JavaPsiClassReferenceElement)element, parameters));
-          }
+      JavaClassNameCompletionContributor.addAllClasses(parameters, parameters.getInvocationCount() <= 2, result.getPrefixMatcher(), element -> {
+        if (!session.alreadyProcessed(element)) {
+          result.addElement(JavaClassNameCompletionContributor.highlightIfNeeded((JavaPsiClassReferenceElement)element, parameters));
         }
       });
     } else {
@@ -356,7 +355,7 @@ public class JavaCompletionContributor extends CompletionContributor {
     }
   }
 
-  private static Set<String> addReferenceVariants(final CompletionParameters parameters, CompletionResultSet result, final InheritorsHolder inheritors) {
+  private static Set<String> addReferenceVariants(final CompletionParameters parameters, CompletionResultSet result, JavaCompletionSession session) {
     final Set<String> usedWords = new HashSet<String>();
     final PsiElement position = parameters.getPosition();
     final boolean first = parameters.getInvocationCount() <= 1;
@@ -385,7 +384,7 @@ public class JavaCompletionContributor extends CompletionContributor {
                                                                                   new ElementExtractorFilter(filter),
                                                                                   options,
                                                                                   result.getPrefixMatcher(), parameters)) {
-              if (inheritors.alreadyProcessed(element)) {
+              if (session.alreadyProcessed(element)) {
                 continue;
               }
 
@@ -403,12 +402,9 @@ public class JavaCompletionContributor extends CompletionContributor {
                   final PsiMethod method = call.getObject();
                   if (method.getTypeParameters().length > 0) {
                     final PsiType returned = TypeConversionUtil.erasure(method.getReturnType());
-                    PsiType matchingExpectation = returned == null ? null : ContainerUtil.find(expectedTypes, new Condition<PsiType>() {
-                      @Override
-                      public boolean value(PsiType type) {
-                        return type.isAssignableFrom(returned);
-                      }
-                    });
+                    PsiType matchingExpectation = returned == null
+                                                  ? null
+                                                  : ContainerUtil.find(expectedTypes, type -> type.isAssignableFrom(returned));
                     if (matchingExpectation != null) {
                       call.setInferenceSubstitutor(SmartCompletionDecorator.calculateMethodReturnTypeSubstitutor(method, matchingExpectation), position);
                     }
@@ -435,18 +431,17 @@ public class JavaCompletionContributor extends CompletionContributor {
           if (completion == null) {
             LOG.error("Position=" + position + "\n;Reference=" + reference + "\n;variants=" + Arrays.toString(variants));
           }
-          if (completion instanceof LookupElement && !inheritors.alreadyProcessed((LookupElement)completion)) {
+          if (completion instanceof LookupElement && !session.alreadyProcessed((LookupElement)completion)) {
             usedWords.add(((LookupElement)completion).getLookupString());
             result.addElement((LookupElement)completion);
           }
           else if (completion instanceof PsiClass) {
-            for (JavaPsiClassReferenceElement item : JavaClassNameCompletionContributor.createClassLookupItems((PsiClass)completion, isAfterNew,
-                                                                                                               JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER, new Condition<PsiClass>() {
-              @Override
-              public boolean value(PsiClass psiClass) {
-                return !inheritors.alreadyProcessed(psiClass) && JavaCompletionUtil.isSourceLevelAccessible(position, psiClass, pkgContext);
-              }
-            })) {
+            Condition<PsiClass> condition = psiClass -> !session.alreadyProcessed(psiClass) &&
+                                                        JavaCompletionUtil.isSourceLevelAccessible(position, psiClass, pkgContext);
+            for (JavaPsiClassReferenceElement item : JavaClassNameCompletionContributor.createClassLookupItems((PsiClass)completion,
+                                                                                                               isAfterNew,
+                                                                                                               JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER,
+                                                                                                               condition)) {
               usedWords.add(item.getLookupString());
               result.addElement(item);
             }
@@ -464,17 +459,12 @@ public class JavaCompletionContributor extends CompletionContributor {
     return usedWords;
   }
 
-  private static void addKeywords(CompletionParameters parameters, final CompletionResultSet result) {
-    Consumer<LookupElement> noMiddleMatches = new Consumer<LookupElement>() {
-      @Override
-      public void consume(LookupElement element) {
-        if (element.getLookupString().startsWith(result.getPrefixMatcher().getPrefix())) {
-          result.addElement(element);
-        }
+  private static void addKeywords(CompletionParameters parameters, CompletionResultSet result, JavaCompletionSession session) {
+    JavaKeywordCompletion.addKeywords(parameters, session, element -> {
+      if (element.getLookupString().startsWith(result.getPrefixMatcher().getPrefix())) {
+        result.addElement(element);
       }
-    };
-
-    JavaKeywordCompletion.addKeywords(parameters, noMiddleMatches);
+    });
   }
 
   static boolean isClassNamePossible(CompletionParameters parameters) {
@@ -543,7 +533,7 @@ public class JavaCompletionContributor extends CompletionContributor {
       for (final LookupElement element : set) {
         result.addElement(element);
       }
-      addAllClasses(parameters, result, new InheritorsHolder(result));
+      addAllClasses(parameters, result, new JavaCompletionSession(result));
     }
 
     if (annoClass != null) {
similarity index 82%
rename from java/java-impl/src/com/intellij/codeInsight/completion/InheritorsHolder.java
rename to java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSession.java
index c9cc650a1cedad12c3291fdbcdece9af82af16ba..eeb8ed26a13b543013ac427694bdf5deb0cb1ffc 100644 (file)
@@ -29,11 +29,12 @@ import java.util.Set;
 /**
 * @author peter
 */
-public class InheritorsHolder implements Consumer<LookupElement> {
-  private final Set<String> myAddedClasses = new HashSet<String>();
+public class JavaCompletionSession implements Consumer<LookupElement> {
+  private final Set<String> myAddedClasses = new HashSet<>();
+  private Set<String> myKeywords = new HashSet<>();
   private final CompletionResultSet myResult;
 
-  public InheritorsHolder(CompletionResultSet result) {
+  public JavaCompletionSession(CompletionResultSet result) {
     myResult = result;
   }
 
@@ -65,4 +66,12 @@ public class InheritorsHolder implements Consumer<LookupElement> {
     final String name = getClassName(object);
     return name == null || myAddedClasses.contains(name);
   }
+
+  public boolean isKeywordAlreadyProcessed(@NotNull String keyword) {
+    return myKeywords.contains(keyword);
+  }
+
+  public void registerKeyword(@NotNull String keyword) {
+    myKeywords.add(keyword);
+  }
 }
index 13a66d12e9de1aa0911894f1b0d70ff8123f1157..78f869ff31febac016e9078b96a7443b9dc61d2b 100644 (file)
@@ -81,8 +81,11 @@ public class JavaCompletionSorting {
       }
     }
     ContainerUtil.addIfNotNull(afterPrefix, recursion(parameters, expectedTypes));
-    Collections.addAll(afterPrefix, new PreferSimilarlyEnding(expectedTypes),
-                       new PreferNonGeneric(), new PreferAccessible(position), new PreferSimple());
+    afterPrefix.add(new PreferSimilarlyEnding(expectedTypes));
+    if (ContainerUtil.or(expectedTypes, info -> !info.getType().equals(PsiType.VOID))) {
+      afterPrefix.add(new PreferNonGeneric());
+    }
+    Collections.addAll(afterPrefix, new PreferAccessible(position), new PreferSimple());
 
     sorter = sorter.weighAfter("prefix", afterPrefix.toArray(new LookupElementWeigher[afterPrefix.size()]));
     sorter = sorter.weighAfter("proximity", afterProximity.toArray(new LookupElementWeigher[afterProximity.size()]));
index 998e8bec4d2cd1758067299c184a157cdd488945..fe139162f1bcebbce7ca983add6da7d93811c4ec 100644 (file)
@@ -270,7 +270,10 @@ public class JavaCompletionUtil {
               final int parameterIndex = lambdaExpression.getParameterList().getParameterIndex((PsiParameter)resolve);
               final Set<LookupElement> set = new LinkedHashSet<LookupElement>();
               final boolean overloadsFound = LambdaUtil.processParentOverloads(lambdaExpression, functionalInterfaceType -> {
-                PsiType qualifierType = removeTopLevelWildcards(LambdaUtil.getLambdaParameterFromType(functionalInterfaceType, parameterIndex));
+                PsiType qualifierType = LambdaUtil.getLambdaParameterFromType(functionalInterfaceType, parameterIndex);
+                if (qualifierType instanceof PsiWildcardType) {
+                  qualifierType = ((PsiWildcardType)qualifierType).getBound();
+                }
                 if (qualifierType == null) return;
 
                 PsiReferenceExpression fakeRef = createReference("xxx.xxx", createContextWithXxxVariable(element, qualifierType));
@@ -285,17 +288,6 @@ public class JavaCompletionUtil {
     return processJavaQualifiedReference(element, javaReference, elementFilter, options, matcher, parameters);
   }
 
-  @Nullable
-  private static PsiType removeTopLevelWildcards(@Nullable PsiType qualifierType) {
-    if (qualifierType instanceof PsiCapturedWildcardType) {
-      return removeTopLevelWildcards(((PsiCapturedWildcardType)qualifierType).getWildcard());
-    }
-    if (qualifierType instanceof PsiWildcardType) {
-      return removeTopLevelWildcards(((PsiWildcardType)qualifierType).getBound());
-    }
-    return qualifierType;
-  }
-
   private static Set<LookupElement> processJavaQualifiedReference(PsiElement element, PsiJavaReference javaReference, ElementFilter elementFilter,
                                                         JavaCompletionProcessor.Options options,
                                                         final PrefixMatcher matcher, CompletionParameters parameters) {
index 22649fa14c5f75d4c4da5ae2b8b7afa8e5a74d7f..ec1a3956c3b7351367de3e3647b45d8f1d1d37bb 100644 (file)
@@ -114,7 +114,7 @@ public class JavaDocCompletionContributor extends CompletionContributor {
             result.addElement(item);
           }
 
-          JavaCompletionContributor.addAllClasses(parameters, result, new InheritorsHolder(result));
+          JavaCompletionContributor.addAllClasses(parameters, result, new JavaCompletionSession(result));
         }
 
         if (tag != null && "author".equals(tag.getName())) {
index fad3b66150e3e319fb36e3bb37558513efe00e5a..dea04fead30e1e6c0a12544f8aa764017477ccba 100644 (file)
@@ -242,7 +242,7 @@ public class JavaKeywordCompletion {
 
   }
 
-  static void addKeywords(CompletionParameters parameters, final Consumer<LookupElement> result) {
+  static void addKeywords(CompletionParameters parameters, JavaCompletionSession session, Consumer<LookupElement> result) {
     final PsiElement position = parameters.getPosition();
     if (PsiTreeUtil.getNonStrictParentOfType(position, PsiLiteralExpression.class, PsiComment.class) != null) {
       return;
@@ -274,7 +274,7 @@ public class JavaKeywordCompletion {
 
     addMethodHeaderKeywords(result, position, prevLeaf);
 
-    addPrimitiveTypes(result, position);
+    addPrimitiveTypes(result, position, session);
 
     addClassLiteral(result, position);
 
@@ -586,7 +586,7 @@ public class JavaKeywordCompletion {
            isAfterPrimitiveOrArrayType(position);
   }
 
-  static void addPrimitiveTypes(final Consumer<LookupElement> result, PsiElement position) {
+  static void addPrimitiveTypes(Consumer<LookupElement> result, PsiElement position, JavaCompletionSession session) {
     if (AFTER_DOT.accepts(position) ||
         psiElement().inside(psiAnnotation()).accepts(position) && !expectsClassLiteral(position)) {
       return;
@@ -621,7 +621,9 @@ public class JavaKeywordCompletion {
         expressionPosition ||
         isStatementPosition(position)) {
       for (String primitiveType : PRIMITIVE_TYPES) {
-        result.consume(createKeyword(position, primitiveType));
+        if (!session.isKeywordAlreadyProcessed(primitiveType)) {
+          result.consume(createKeyword(position, primitiveType));
+        }
       }
     }
     if (declaration) {
index 11e0c3d3cf9aa3ef2e037e19f92a36173822c26d..362e4d96a3667508113b1e22033ab46356ebd0d4 100644 (file)
@@ -42,7 +42,7 @@ import static com.intellij.patterns.PsiJavaPatterns.psiElement;
 public class JavaNoVariantsDelegator extends CompletionContributor {
   @Override
   public void fillCompletionVariants(@NotNull final CompletionParameters parameters, @NotNull final CompletionResultSet result) {
-    final InheritorsHolder holder = new InheritorsHolder(result);
+    final JavaCompletionSession session = new JavaCompletionSession(result);
     ResultTracker tracker = new ResultTracker(result) {
       @Override
       public void consume(CompletionResult plainResult) {
@@ -51,10 +51,10 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
         LookupElement element = plainResult.getLookupElement();
         Object o = element.getObject();
         if (o instanceof PsiClass) {
-          holder.registerClass((PsiClass)o);
+          session.registerClass((PsiClass)o);
         }
         if (element instanceof TypeArgumentCompletionProvider.TypeArgsLookupElement) {
-          ((TypeArgumentCompletionProvider.TypeArgsLookupElement)element).registerSingleClass(holder);
+          ((TypeArgumentCompletionProvider.TypeArgsLookupElement)element).registerSingleClass(session);
         }
       }
     };
@@ -66,14 +66,14 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
     }
 
     if (empty) {
-      delegate(parameters, JavaCompletionSorting.addJavaSorting(parameters, result), holder);
+      delegate(parameters, JavaCompletionSorting.addJavaSorting(parameters, result), session);
     } else if (Registry.is("ide.completion.show.better.matching.classes")) {
       if (parameters.getCompletionType() == CompletionType.BASIC &&
           parameters.getInvocationCount() <= 1 &&
           JavaCompletionContributor.mayStartClassName(result) &&
           JavaCompletionContributor.isClassNamePossible(parameters) &&
           !JavaSmartCompletionContributor.AFTER_NEW.accepts(parameters.getPosition())) {
-        suggestNonImportedClasses(parameters, JavaCompletionSorting.addJavaSorting(parameters, result.withPrefixMatcher(tracker.betterMatcher)), holder);
+        suggestNonImportedClasses(parameters, JavaCompletionSorting.addJavaSorting(parameters, result.withPrefixMatcher(tracker.betterMatcher)), session);
       }
     }
   }
@@ -82,7 +82,7 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
     return psiElement().withParents(PsiJavaCodeReferenceElement.class, PsiAnnotation.class).accepts(parameters.getPosition());
   }
 
-  private static void delegate(CompletionParameters parameters, final CompletionResultSet result, final InheritorsHolder inheritorsHolder) {
+  private static void delegate(CompletionParameters parameters, CompletionResultSet result, JavaCompletionSession session) {
     if (parameters.getCompletionType() == CompletionType.BASIC) {
       PsiElement position = parameters.getPosition();
       suggestCollectionUtilities(parameters, result, position);
@@ -90,7 +90,7 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
       if (parameters.getInvocationCount() <= 1 &&
           (JavaCompletionContributor.mayStartClassName(result) || suggestAllAnnotations(parameters)) &&
           JavaCompletionContributor.isClassNamePossible(parameters)) {
-        suggestNonImportedClasses(parameters, result, inheritorsHolder);
+        suggestNonImportedClasses(parameters, result, session);
         return;
       }
 
@@ -176,22 +176,18 @@ public class JavaNoVariantsDelegator extends CompletionContributor {
     return allClasses;
   }
 
-  private static void suggestNonImportedClasses(final CompletionParameters parameters, final CompletionResultSet result, @Nullable final InheritorsHolder inheritorsHolder) {
-    JavaClassNameCompletionContributor.addAllClasses(parameters,
-                                                     true, result.getPrefixMatcher(), new Consumer<LookupElement>() {
-      @Override
-      public void consume(LookupElement element) {
-        if (inheritorsHolder != null && inheritorsHolder.alreadyProcessed(element)) {
-          return;
-        }
-        JavaPsiClassReferenceElement classElement = element.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
-        if (classElement != null) {
-          classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
-          element = JavaClassNameCompletionContributor.highlightIfNeeded(classElement, parameters);
-        }
-
-        result.addElement(element);
+  private static void suggestNonImportedClasses(CompletionParameters parameters, CompletionResultSet result, @Nullable JavaCompletionSession session) {
+    JavaClassNameCompletionContributor.addAllClasses(parameters, true, result.getPrefixMatcher(), element -> {
+      if (session != null && session.alreadyProcessed(element)) {
+        return;
+      }
+      JavaPsiClassReferenceElement classElement = element.as(JavaPsiClassReferenceElement.CLASS_CONDITION_KEY);
+      if (classElement != null) {
+        classElement.setAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE);
+        element = JavaClassNameCompletionContributor.highlightIfNeeded(classElement, parameters);
       }
+
+      result.addElement(element);
     });
   }
 
index 48b58d54f5901b38141cc5090c60542b097051e1..53bc078de0c2c9676c11f257be2c4bca5a9b56a1 100644 (file)
@@ -52,11 +52,11 @@ class TypeArgumentCompletionProvider extends CompletionProvider<CompletionParame
   static final ElementPattern<PsiElement> IN_TYPE_ARGS = psiElement().inside(PsiReferenceParameterList.class);
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.completion.TypeArgumentCompletionProvider");
   private final boolean mySmart;
-  @Nullable private final InheritorsHolder myInheritors;
+  @Nullable private final JavaCompletionSession mySession;
 
-  TypeArgumentCompletionProvider(boolean smart, @Nullable InheritorsHolder inheritors) {
+  TypeArgumentCompletionProvider(boolean smart, @Nullable JavaCompletionSession session) {
     mySmart = smart;
-    myInheritors = inheritors;
+    mySession = session;
   }
 
   @Override
@@ -114,7 +114,7 @@ class TypeArgumentCompletionProvider extends CompletionProvider<CompletionParame
 
     boolean hasParameters = ConstructorInsertHandler.hasConstructorParameters(actualClass, context);
     TypeArgsLookupElement element = new TypeArgsLookupElement(typeItems, globalTail, hasParameters);
-    element.registerSingleClass(myInheritors);
+    element.registerSingleClass(mySession);
     resultSet.addElement(element);
   }
 
@@ -216,7 +216,7 @@ class TypeArgumentCompletionProvider extends CompletionProvider<CompletionParame
       return myTypeItems.get(0).getObject();
     }
 
-    public void registerSingleClass(@Nullable InheritorsHolder inheritors) {
+    public void registerSingleClass(@Nullable JavaCompletionSession inheritors) {
       if (inheritors != null && myTypeItems.size() == 1) {
         PsiType type = myTypeItems.get(0).getType();
         PsiClass aClass = PsiUtil.resolveClassInClassTypeOnly(type);
index 7582b3fae019e12513908b5486814e0181558c57..5e5109971fb95e18c8eee3a16079b8e1c74d6073 100644 (file)
@@ -19,10 +19,12 @@ import com.intellij.ide.IdeBundle;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.ElementColorProvider;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
 import com.intellij.psi.util.PsiTypesUtil;
 import com.intellij.ui.ColorUtil;
+import com.intellij.ui.JBColor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -31,6 +33,7 @@ import java.awt.*;
 /**
  * @author Konstantin Bulenkov
  */
+@SuppressWarnings("UseJBColor")
 public class JavaColorProvider implements ElementColorProvider {
   @Override
   public Color getColorFrom(@NotNull PsiElement element) {
@@ -57,10 +60,34 @@ public class JavaColorProvider implements ElementColorProvider {
       if (isColorType(expr.getType())) {
         return getColor(expr.getArgumentList());
       }
+    } else if (isIntLiteralInsideNewJBColorExpression(element)) {
+      final String text = element.getText();
+      boolean hasAlpha = text != null && StringUtil.startsWithIgnoreCase(text, "0x") && text.length() > 8;
+      return new Color(getInt((PsiExpression)element), hasAlpha);
     }
     return null;
   }
 
+  private static boolean isIntLiteralInsideNewJBColorExpression(PsiElement element) {
+    if (element instanceof PsiLiteralExpression && PsiType.INT.equals(((PsiLiteralExpression)element).getType())) {
+      PsiElement parent = element.getParent();
+      if (parent != null) {
+        return isNewJBColorExpression(parent.getParent());
+      }
+    }
+    return false;
+  }
+
+  private static boolean isNewJBColorExpression(PsiElement element) {
+    if (element instanceof PsiNewExpression) {
+      final PsiClass psiClass = PsiTypesUtil.getPsiClass(((PsiNewExpression)element).getType());
+      if (psiClass != null && JBColor.class.getName().equals(psiClass.getQualifiedName())) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   @Nullable
   private static Color getColor(PsiExpressionList list) {
     try {
@@ -116,49 +143,63 @@ public class JavaColorProvider implements ElementColorProvider {
 
   @Override
   public void setColorTo(@NotNull PsiElement element, @NotNull Color color) {
-    PsiExpressionList argumentList = ((PsiNewExpression)element).getArgumentList();
-    assert argumentList != null;
-    
-    PsiExpression[] expr = argumentList.getExpressions();
-    ColorConstructors type = getConstructorType(argumentList.getExpressionTypes());
+    Runnable command;
     final Document document = PsiDocumentManager.getInstance(element.getProject()).getDocument(element.getContainingFile());
-    assert type != null;
-    CommandProcessor.getInstance().executeCommand(element.getProject(), new Runnable() {
-      @Override
-      public void run() {
 
-
-        switch (type) {
-          case INT:
-          case INT_BOOL:
-            replaceInt(expr[0], color.getRGB(), true);
-            return;
-          case INT_x3:
-          case INT_x4:
-            replaceInt(expr[0], color.getRed());
-            replaceInt(expr[1], color.getGreen());
-            replaceInt(expr[2], color.getBlue());
-            if (type == ColorConstructors.INT_x4) {
-              replaceInt(expr[3], color.getAlpha());
-            }
-            else if (color.getAlpha() != 255) {
-              //todo add alpha
-            }
-            return;
-          case FLOAT_x3:
-          case FLOAT_x4:
-            float[] rgba = color.getColorComponents(null);
-            replaceFloat(expr[0], rgba[0]);
-            replaceFloat(expr[1], rgba[1]);
-            replaceFloat(expr[2], rgba[2]);
-            if (type == ColorConstructors.FLOAT_x4) {
-              replaceFloat(expr[3], rgba.length == 4 ? rgba[3] : 0f);
-            }
-            else if (color.getAlpha() != 255) {
-              //todo add alpha
-            }
+    if (isIntLiteralInsideNewJBColorExpression(element)) {
+      command = new Runnable() {
+        @Override
+        public void run() {
+          replaceInt((PsiExpression)element, color.getRGB(), true, color.getAlpha() != 255);
+        }
+      };
+    } else {
+      PsiExpressionList argumentList = ((PsiNewExpression)element).getArgumentList();
+      assert argumentList != null;
+
+      PsiExpression[] expr = argumentList.getExpressions();
+      ColorConstructors type = getConstructorType(argumentList.getExpressionTypes());
+
+      assert type != null;
+      command = new Runnable() {
+        @Override
+        public void run() {
+          switch (type) {
+            case INT:
+            case INT_BOOL:
+              replaceInt(expr[0], color.getRGB(), true);
+              return;
+            case INT_x3:
+            case INT_x4:
+              replaceInt(expr[0], color.getRed());
+              replaceInt(expr[1], color.getGreen());
+              replaceInt(expr[2], color.getBlue());
+              if (type == ColorConstructors.INT_x4) {
+                replaceInt(expr[3], color.getAlpha());
+              }
+              else if (color.getAlpha() != 255) {
+                //todo add alpha
+              }
+              return;
+            case FLOAT_x3:
+            case FLOAT_x4:
+              float[] rgba = color.getColorComponents(null);
+              replaceFloat(expr[0], rgba[0]);
+              replaceFloat(expr[1], rgba[1]);
+              replaceFloat(expr[2], rgba[2]);
+              if (type == ColorConstructors.FLOAT_x4) {
+                replaceFloat(expr[3], rgba.length == 4 ? rgba[3] : 0f);
+              }
+              else if (color.getAlpha() != 255) {
+                //todo add alpha
+              }
+          }
         }
-      }}, IdeBundle.message("change.color.command.text"), null, document);
+      };
+    }
+    if (command != null) {
+      CommandProcessor.getInstance().executeCommand(element.getProject(), command, IdeBundle.message("change.color.command.text"), null, document);
+    }
   }
 
   private static void replaceInt(PsiExpression expr, int newValue) {
@@ -166,9 +207,24 @@ public class JavaColorProvider implements ElementColorProvider {
   }
 
   private static void replaceInt(PsiExpression expr, int newValue, boolean hex) {
+    replaceInt(expr, newValue, hex, false);
+  }
+
+  private static void replaceInt(PsiExpression expr, int newValue, boolean hex, boolean hasAlpha) {
     PsiElementFactory factory = JavaPsiFacade.getElementFactory(expr.getProject());
     if (getInt(expr) != newValue) {
-      String text = hex ? "0x" + ColorUtil.toHex(new Color(newValue)).toUpperCase() : Integer.toString(newValue);
+      final Color c = new Color(newValue, hasAlpha);
+      String text;
+      if (hex) {
+        text = "0x";
+        if (hasAlpha) {
+          text += Integer.toHexString(c.getAlpha());
+        }
+        text += ColorUtil.toHex(c).toUpperCase();
+      } else {
+        text = Integer.toString(newValue);
+      }
+
       expr.replace(factory.createExpressionFromText(text, null));
     }
   }
index e1190d999bd995e570bfc547c1376640e146a6f8..0f5b6541d91920b4e2983e425367548604eadb3b 100644 (file)
@@ -29,7 +29,6 @@ import com.intellij.psi.*;
 import com.intellij.psi.impl.source.resolve.DefaultParameterTypeInferencePolicy;
 import com.intellij.psi.search.PsiSearchHelper;
 import com.intellij.psi.util.PsiUtil;
-import com.intellij.refactoring.typeMigration.TypeMigrationLabeler;
 import com.intellij.refactoring.typeMigration.TypeMigrationProcessor;
 import com.intellij.refactoring.typeMigration.TypeMigrationRules;
 import com.intellij.usageView.UsageViewUtil;
@@ -79,7 +78,7 @@ public class VariableTypeFromCallFix implements IntentionAction {
 
   @Override
   public boolean startInWriteAction() {
-    return true;
+    return false;
   }
 
 
index 1686eab868916c5e204a243ffbd6af3108d76bbe..70460bfca8ea6ed284e190542311d9b6ea02b7a4 100644 (file)
@@ -15,6 +15,8 @@
  */
 package com.intellij.codeInsight.editorActions;
 
+import com.intellij.codeInsight.CodeInsightSettings;
+import com.intellij.codeInsight.daemon.impl.quickfix.ImportClassFix;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.RangeMarker;
 import com.intellij.openapi.util.TextRange;
@@ -100,6 +102,16 @@ public class JavaCopyPasteReferenceProcessor extends CopyPasteReferenceProcessor
         }
       }
     }
+
+    if (CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY) {
+      for (int i = 0; i < refs.length; i++) {
+        PsiJavaCodeReferenceElement ref = refs[i];
+        if (ref != null && new ImportClassFix(ref).getClassesToImport().size() <= 1) {
+          refs[i] = null;
+        }
+      }
+    }
+
     return refs;
   }
 
index 9fd7ed8c5222408a76316e5b8b910954e0f1369f..42e45c19bda259e3205b01e9f1a5d9ea65dda822 100644 (file)
@@ -74,7 +74,7 @@ public class JavaSmartEnterProcessor extends SmartEnterProcessor {
     fixers.add(new WhileConditionFixer());
     fixers.add(new CatchDeclarationFixer());
     fixers.add(new SwitchExpressionFixer());
-    fixers.add(new CaseColonFixer());
+    fixers.add(new SwitchLabelColonFixer());
     fixers.add(new DoWhileConditionFixer());
     fixers.add(new BlockBraceFixer());
     fixers.add(new MissingIfBranchesFixer());
index 5def648b137fbe2a67f0aca00699abac84c391de..96172132642abf758b9666c8ac6b369cd0c6ade8 100644 (file)
@@ -19,6 +19,8 @@ import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.psi.*;
 import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 /**
  * @author max
@@ -30,37 +32,37 @@ public class MissingIfBranchesFixer implements Fixer {
 
     PsiIfStatement ifStatement = (PsiIfStatement) psiElement;
     final Document doc = editor.getDocument();
-    final PsiStatement elseBranch = ifStatement.getElseBranch();
     final PsiKeyword elseElement = ifStatement.getElseElement();
-    if (elseElement != null && (elseBranch == null || !(elseBranch instanceof PsiBlockStatement) &&
-                                                      startLine(doc, elseBranch) > startLine(doc, elseElement))) {
-      doc.insertString(elseElement.getTextRange().getEndOffset(), "{}");
+    if (elseElement != null) {
+      handleBranch(doc, ifStatement, elseElement, ifStatement.getElseBranch());
     }
 
-    PsiElement thenBranch = ifStatement.getThenBranch();
-    if (thenBranch instanceof PsiBlockStatement) return;
-
-    boolean transformingOneLiner = false;
-    if (thenBranch != null && startLine(doc, thenBranch) == startLine(doc, ifStatement)) {
-      if (ifStatement.getCondition() != null) {
-        return;
-      }
-      transformingOneLiner = true;
-    }
-
-    final PsiJavaToken rParenth = ifStatement.getRParenth();
+    PsiJavaToken rParenth = ifStatement.getRParenth();
     assert rParenth != null;
+    handleBranch(doc, ifStatement, rParenth, ifStatement.getThenBranch());
+  }
 
-    if (elseBranch == null && !transformingOneLiner || thenBranch == null) {
-      doc.insertString(rParenth.getTextRange().getEndOffset(), "{}");
+  private static void handleBranch(@NotNull Document doc, @NotNull PsiIfStatement ifStatement, @NotNull PsiElement beforeBranch, @Nullable PsiStatement branch) {
+    if (branch instanceof PsiBlockStatement) return;
+    boolean transformingOneLiner = branch != null && (startLine(doc, beforeBranch) == startLine(doc, branch) ||
+                                                      startCol(doc, ifStatement) < startCol(doc, branch));
+
+    if (!transformingOneLiner) {
+      doc.insertString(beforeBranch.getTextRange().getEndOffset(), "{}");
     }
     else {
-      doc.insertString(rParenth.getTextRange().getEndOffset(), "{");
-      doc.insertString(thenBranch.getTextRange().getEndOffset() + 1, "}");
+      doc.insertString(beforeBranch.getTextRange().getEndOffset(), "{");
+      doc.insertString(branch.getTextRange().getEndOffset() + 1, "}");
     }
+
   }
 
-  private static int startLine(Document doc, PsiElement psiElement) {
+  private static int startLine(Document doc, @NotNull PsiElement psiElement) {
     return doc.getLineNumber(psiElement.getTextRange().getStartOffset());
   }
+
+  private static int startCol(Document doc, @NotNull PsiElement psiElement) {
+    int offset = psiElement.getTextRange().getStartOffset();
+    return offset - doc.getLineStartOffset(doc.getLineNumber(offset));
+  }
 }
index bf5db4cfa64ac240933345c7860a5187ddaea3f0..c32cbf32875f522f93cd7ff6cfb3a2cd69251735 100644 (file)
@@ -94,6 +94,10 @@ public class PlainEnterProcessor implements EnterProcessor {
       return ((PsiTryStatement)element).getFinallyBlock();
     }
 
+    if (element instanceof PsiSynchronizedStatement) {
+      return ((PsiSynchronizedStatement)element).getBody();
+    }
+
     if (element instanceof PsiMethod) {
       PsiCodeBlock methodBody = ((PsiMethod)element).getBody();
       if (methodBody != null) return methodBody;
similarity index 71%
rename from java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/CaseColonFixer.java
rename to java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/SwitchLabelColonFixer.java
index de32027c4616aac047d107bb5e815397e456d928..939a7c051222dc15039c9f0182138b79b7a29171 100644 (file)
@@ -23,13 +23,14 @@ import com.intellij.util.IncorrectOperationException;
 /**
  * @author peter
  */
-public class CaseColonFixer implements Fixer {
+public class SwitchLabelColonFixer implements Fixer {
   @Override
   public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException {
-    if (psiElement instanceof PsiSwitchLabelStatement &&
-        ((PsiSwitchLabelStatement)psiElement).getCaseValue() != null &&
-        !psiElement.getText().endsWith(":")) {
-      editor.getDocument().insertString(psiElement.getTextRange().getEndOffset(), ":");
+    if (psiElement instanceof PsiSwitchLabelStatement && !psiElement.getText().endsWith(":")) {
+      PsiSwitchLabelStatement statement = (PsiSwitchLabelStatement)psiElement;
+      if (statement.getCaseValue() != null || statement.isDefaultCase()) {
+        editor.getDocument().insertString(psiElement.getTextRange().getEndOffset(), ":");
+      }
     }
   }
 }
index 3141112d4488b463b5f1bcf46edcd9f0d19cad33..f76f30b8000a071aaa3f4f38f98a571743e1e8e4 100644 (file)
@@ -203,7 +203,7 @@ public class VariableLookupItem extends LookupItem<PsiVariable> implements Typed
       TailType.COMMA.processTail(context.getEditor(), context.getTailOffset());
       AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), null);
     }
-    else if (completionChar == ':') {
+    else if (completionChar == ':' && getAttribute(LookupItem.TAIL_TYPE_ATTR) != TailType.UNKNOWN) {
       context.setAddCompletionChar(false);
       TailType.COND_EXPR_COLON.processTail(context.getEditor(), context.getTailOffset());
     }
index eb43ea47049310dfb550c009a3be75f80fb8f486..95947598d2cf6a28fe25aaddccd5673d0b659a68 100644 (file)
@@ -26,6 +26,7 @@ import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtilBase;
 import com.intellij.util.text.CharArrayUtil;
 import org.jetbrains.annotations.Nls;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author peter
@@ -74,7 +75,7 @@ public class CodeBlockReformattingProcessor implements TemplateOptionalProcessor
   }
 
   @Override
-  public boolean isVisible(Template template) {
+  public boolean isVisible(@NotNull Template template, @NotNull TemplateContext context) {
     return false;
   }
 }
index 3304e84cfe113e563a5a9a8c08c845ef6c3df018..0f0cc27aad2c0deacd36229da7cf921e379282f0 100644 (file)
@@ -64,8 +64,4 @@ public class ShortenFQNamesProcessor implements TemplateOptionalProcessor {
     template.setToShortenLongNames(value);
   }
 
-  @Override
-  public boolean isVisible(Template template) {
-    return true;
-  }
 }
index fbb6786c49722a570f7ea084b60bb7537d4ca676..3187bb18a2e248fa9266de4a08a357df0a08b057 100644 (file)
@@ -18,7 +18,10 @@ package com.intellij.codeInsight.template.impl;
 import com.intellij.codeInsight.CodeInsightBundle;
 import com.intellij.codeInsight.intention.impl.AddOnDemandStaticImportAction;
 import com.intellij.codeInsight.intention.impl.AddSingleMemberStaticImportAction;
+import com.intellij.codeInsight.template.JavaCodeContextType;
+import com.intellij.codeInsight.template.JavaCommentContextType;
 import com.intellij.codeInsight.template.Template;
+import com.intellij.codeInsight.template.TemplateContextType;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.RangeMarker;
@@ -98,8 +101,14 @@ public class ShortenToStaticImportProcessor implements TemplateOptionalProcessor
   }
 
   @Override
-  public boolean isVisible(Template template) {
-    return true;
+  public boolean isVisible(@NotNull Template template, @NotNull TemplateContext context) {
+    for (TemplateContextType contextType : TemplateContextType.EP_NAME.getExtensions()) {
+      if (!context.isEnabled(contextType)) continue;
+      if (contextType instanceof JavaCodeContextType || contextType instanceof JavaCommentContextType) {
+        return true;
+      }
+    }
+    return false;
   }
   
   private interface StaticImporter {
index f1b352733fe473d7c23132aa69aba59a63c48bba..cf7adbeb80fc252e0eb7f62b9f8852a0bf093d22 100644 (file)
@@ -989,9 +989,12 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
                                                           final PsiType expectedType) {
 
     if (initializer instanceof PsiTypeCastExpression) {
-      PsiTypeElement castType = ((PsiTypeCastExpression)initializer).getCastType();
-      if (castType != null && TypeConversionUtil.isAssignable(expectedType, castType.getType())) {
-        return ((PsiTypeCastExpression)initializer).getOperand();
+      PsiExpression operand = ((PsiTypeCastExpression)initializer).getOperand();
+      if (operand != null) {
+        PsiType operandType = operand.getType();
+        if (operandType != null && TypeConversionUtil.isAssignable(expectedType, operandType)) {
+          return operand;
+        }
       }
     }
     else if (initializer instanceof PsiNewExpression) {
index 5a21d945fd790df03cb563f7091f9af3d213e914..d24ffeeaf2aca4e1a8bd6c8005a7f5091cc87d19 100644 (file)
@@ -28,12 +28,14 @@ import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Caret;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ScrollType;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.psi.*;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.HelpID;
 import com.intellij.refactoring.RefactoringActionHandler;
 import com.intellij.refactoring.RefactoringBundle;
@@ -58,56 +60,41 @@ public class JavaPullUpHandler implements RefactoringActionHandler, PullUpDialog
 
   @Override
   public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
-    int offset = editor.getCaretModel().getOffset();
     editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
-    PsiElement element = file.findElementAt(offset);
-
-    while (true) {
-      if (element == null || element instanceof PsiFile) {
-        String message = RefactoringBundle
-          .getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from"));
-        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PULL_UP);
-        return;
-      }
-
-      if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return;
-
-      if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) {
-        invoke(project, new PsiElement[]{element}, dataContext);
-        return;
+    List<PsiElement> elements = new ArrayList<>();
+    for (Caret caret : editor.getCaretModel().getAllCarets()) {
+      int offset = caret.getOffset();
+      PsiElement element = file.findElementAt(offset);
+
+      while (element != null && !(element instanceof PsiFile)) {
+        if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) {
+          elements.add(element);
+          break;
+        }
+        element = element.getParent();
       }
-      element = element.getParent();
+    }
+    if (elements.isEmpty()) {
+      String message = RefactoringBundle
+        .getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.pull.members.from"));
+      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PULL_UP);
+    }
+    else {
+      invoke(project, elements.toArray(PsiElement.EMPTY_ARRAY),dataContext);
     }
   }
 
   @Override
   public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
-    if (elements.length != 1) return;
-    myProject = project;
 
-    PsiElement element = elements[0];
-    PsiClass aClass;
-    PsiElement aMember = null;
+    myProject = project;
 
-    if (element instanceof PsiClass) {
-      aClass = (PsiClass)element;
-    }
-    else if (element instanceof PsiMethod) {
-      aClass = ((PsiMethod)element).getContainingClass();
-      aMember = element;
-    }
-    else if (element instanceof PsiField) {
-      aClass = ((PsiField)element).getContainingClass();
-      aMember = element;
-    }
-    else {
-      return;
-    }
+    PsiClass aClass = PsiTreeUtil.getParentOfType(PsiTreeUtil.findCommonParent(elements), PsiClass.class, false);
 
-    invoke(project, dataContext, aClass, aMember);
+    invoke(project, dataContext, aClass, elements);
   }
 
-  private void invoke(Project project, DataContext dataContext, PsiClass aClass, PsiElement aMember) {
+  private void invoke(Project project, DataContext dataContext, PsiClass aClass, PsiElement... selectedMembers) {
     final Editor editor = dataContext != null ? CommonDataKeys.EDITOR.getData(dataContext) : null;
     if (aClass == null) {
       String message =
@@ -130,21 +117,17 @@ public class JavaPullUpHandler implements RefactoringActionHandler, PullUpDialog
       return;
     }
 
-
+    if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;
     mySubclass = aClass;
-    MemberInfoStorage memberInfoStorage = new MemberInfoStorage(mySubclass, new MemberInfo.Filter<PsiMember>() {
-      @Override
-      public boolean includeMember(PsiMember element) {
-        return true;
-      }
-    });
+    MemberInfoStorage memberInfoStorage = new MemberInfoStorage(mySubclass, element -> true);
     List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(mySubclass);
-    PsiManager manager = mySubclass.getManager();
 
     for (MemberInfoBase<PsiMember> member : members) {
-      if (manager.areElementsEquivalent(member.getMember(), aMember)) {
-        member.setChecked(true);
-        break;
+      for (PsiElement aMember : selectedMembers) {
+        if (PsiTreeUtil.isAncestor(member.getMember(), aMember, false)) {
+          member.setChecked(true);
+          break;
+        }
       }
     }
 
index 1997191a9feec1c378209ec240cb210ad8310824..a4de216f7a4ba2485cbc5571a55a420b0ba92c4b 100644 (file)
  */
 package com.intellij.refactoring.memberPushDown;
 
+import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.editor.Caret;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ScrollType;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.HelpID;
 import com.intellij.refactoring.RefactoringActionHandler;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.classMembers.MemberInfoBase;
 import com.intellij.refactoring.lang.ElementsHandler;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
-import com.intellij.refactoring.util.RefactoringMessageUtil;
 import com.intellij.refactoring.util.classMembers.MemberInfo;
 import com.intellij.refactoring.util.classMembers.MemberInfoStorage;
 import org.jetbrains.annotations.NotNull;
 
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -41,67 +44,73 @@ public class JavaPushDownHandler implements RefactoringActionHandler, ElementsHa
   public static final String REFACTORING_NAME = RefactoringBundle.message("push.members.down.title");
 
   public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
-    int offset = editor.getCaretModel().getOffset();
     editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
-    PsiElement element = file.findElementAt(offset);
+    ArrayList<PsiElement> elements = new ArrayList<>();
+    String errorMessage = null;
+    for (Caret caret : editor.getCaretModel().getAllCarets()) {
+      int offset = caret.getOffset();
+      PsiElement element = file.findElementAt(offset);
+      String errorFromElement = collectElementsUnderCaret(element, elements);
+      if (errorFromElement != null) {
+        errorMessage = errorFromElement;
+      }
+    }
+
+    if (elements.isEmpty()) {
+      String message = errorMessage != null ? errorMessage
+                                            : RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
+      CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
+      return;
+    }
 
+    invoke(project, elements.toArray(PsiElement.EMPTY_ARRAY), dataContext);
+  }
+
+  private static String collectElementsUnderCaret(PsiElement element, List<PsiElement> elements) {
     while (true) {
       if (element == null || element instanceof PsiFile) {
-        String message = RefactoringBundle.getCannotRefactorMessage(
-          RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
-        CommonRefactoringUtil.showErrorHint(project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
-        return;
+        return RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
       }
 
-      if (element instanceof PsiClass || element instanceof PsiField || element instanceof PsiMethod) {
+      if (element instanceof PsiClass && ((PsiClass)element).getQualifiedName() != null || element instanceof PsiField || element instanceof PsiMethod) {
         if (element instanceof JspClass) {
-          RefactoringMessageUtil.showNotSupportedForJspClassesError(project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
-          return;
+          return RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("refactoring.is.not.supported.for.jsp.classes"));
         }
-        invoke(project, new PsiElement[]{element}, dataContext);
-        return;
+        elements.add(element);
+        return null;
       }
       element = element.getParent();
     }
   }
 
   public void invoke(@NotNull final Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
-    if (elements.length != 1) return;
+    PsiClass aClass = PsiTreeUtil.getParentOfType(PsiTreeUtil.findCommonParent(elements), PsiClass.class, false);
+    if (aClass == null) return;
 
-    PsiElement element = elements[0];
-    PsiClass aClass;
-    PsiElement aMember = null;
+    String qualifiedName = aClass.getQualifiedName();
+    if (qualifiedName == null) return;
 
-    if (element instanceof PsiClass) {
-      aClass = (PsiClass) element;
-    } else if (element instanceof PsiMethod) {
-      aClass = ((PsiMethod) element).getContainingClass();
-      aMember = element;
-    } else if (element instanceof PsiField) {
-      aClass = ((PsiField) element).getContainingClass();
-      aMember = element;
-    } else
+    final Editor editor = dataContext != null ? CommonDataKeys.EDITOR.getData(dataContext) : null;
+    if (aClass.hasModifierProperty(PsiModifier.FINAL)) {
+      CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.message("refactoring.cannot.be.performed") +
+                                                           ": Class " + aClass.getName() + " is final", REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
       return;
+    }
 
     if (!CommonRefactoringUtil.checkReadOnlyStatus(project, aClass)) return;
-    MemberInfoStorage memberInfoStorage = new MemberInfoStorage(aClass, new MemberInfo.Filter<PsiMember>() {
-      public boolean includeMember(PsiMember element) {
-        return !(element instanceof PsiEnumConstant);
-      }
-    });
+    MemberInfoStorage memberInfoStorage = new MemberInfoStorage(aClass, element -> !(element instanceof PsiEnumConstant));
+
     List<MemberInfo> members = memberInfoStorage.getClassMemberInfos(aClass);
-    PsiManager manager = aClass.getManager();
 
     for (MemberInfoBase<PsiMember> member : members) {
-      if (manager.areElementsEquivalent(member.getMember(), aMember)) {
-        member.setChecked(true);
-        break;
+      for (PsiElement element : elements) {
+        if (PsiTreeUtil.isAncestor(member.getMember(), element, false)) {
+          member.setChecked(true);
+          break;
+        }
       }
     }
-    PushDownDialog dialog = new PushDownDialog(
-            project,
-            members.toArray(new MemberInfo[members.size()]),
-            aClass);
+    PushDownDialog dialog = new PushDownDialog(project, members.toArray(new MemberInfo[members.size()]), aClass);
     dialog.show();
   }
 
index 925ab0b7bd43cd94ac61fd5f270339166b9556fa..6fad6197cf5d61b04927cd88a17c982354c06203 100644 (file)
 package com.intellij.refactoring.util;
 
 import com.intellij.codeInsight.ChangeContextUtil;
-import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
+import com.intellij.psi.impl.source.resolve.graphInference.PsiPolyExpressionUtil;
 import com.intellij.psi.search.LocalSearchScope;
 import com.intellij.psi.search.searches.ReferencesSearch;
 import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.RedundantCastUtil;
-import com.intellij.psi.util.TypeConversionUtil;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.util.Function;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.Processor;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.*;
@@ -53,7 +51,6 @@ public class InlineUtil {
     PsiClass thisClass = RefactoringChangeUtil.getThisClass(initializer);
     PsiClass refParent = RefactoringChangeUtil.getThisClass(ref);
     final PsiElement parent = ref.getParent();
-    boolean insertCastWhenUnchecked = parent instanceof PsiForeachStatement;
     final PsiType varType = variable.getType();
     initializer = RefactoringUtil.convertInitializerToNormalExpression(initializer, varType);
     if (initializer instanceof PsiPolyadicExpression) {
@@ -75,94 +72,39 @@ public class InlineUtil {
     PsiThisExpression thisAccessExpr = createThisExpression(manager, thisClass, refParent);
 
     expr = (PsiExpression)ChangeContextUtil.decodeContextInfo(expr, thisClass, thisAccessExpr);
-    PsiType exprType = expr.getType();
-    if (exprType != null && (!varType.equals(exprType) && (varType instanceof PsiPrimitiveType || exprType instanceof PsiPrimitiveType)
-                             || !TypeConversionUtil.isAssignable(varType, exprType)
-                             || insertCastWhenUnchecked && JavaGenericsUtil.isRawToGeneric(varType, exprType))) {
-      boolean matchedTypes = false;
-      //try explicit type arguments
-      final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
-      if (expr instanceof PsiCallExpression && ((PsiCallExpression)expr).getTypeArguments().length == 0) {
-        final JavaResolveResult resolveResult = ((PsiCallExpression)initializer).resolveMethodGenerics();
-        final PsiElement resolved = resolveResult.getElement();
-        if (resolved instanceof PsiMethod) {
-          final PsiTypeParameter[] typeParameters = ((PsiMethod)resolved).getTypeParameters();
-          if (typeParameters.length > 0) {
-            final PsiCallExpression copy = (PsiCallExpression)expr.copy();
-            for (final PsiTypeParameter typeParameter : typeParameters) {
-              final PsiType substituted = resolveResult.getSubstitutor().substitute(typeParameter);
-              if (substituted == null) break;
-              copy.getTypeArgumentList().add(elementFactory.createTypeElement(substituted));
-            }
-            if (varType.equals(copy.getType())) {
-              ((PsiCallExpression)expr).getTypeArgumentList().replace(copy.getTypeArgumentList());
-              if (expr instanceof PsiMethodCallExpression) {
-                final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)expr).getMethodExpression();
-                final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
-                if (qualifierExpression == null) {
-                  final PsiMethod method = (PsiMethod)resolved;
-                  final PsiClass containingClass = method.getContainingClass();
-                  LOG.assertTrue(containingClass != null);
-                  if (method.getModifierList().hasModifierProperty(PsiModifier.STATIC)) {
-                    methodExpression.setQualifierExpression(elementFactory.createReferenceExpression(containingClass));
-                  } else {
-                    methodExpression.setQualifierExpression(createThisExpression(manager, thisClass, refParent));
-                  }
-                }
-              }
-              matchedTypes = true;
+    PsiType exprType = RefactoringUtil.getTypeByExpression(expr);
+    if (exprType != null && !exprType.equals(varType)) {
+      PsiElementFactory elementFactory = JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
+      PsiMethod method = qualifyWithExplicitTypeArguments(initializer, expr, varType);
+      if (method != null) {
+        if (expr instanceof PsiMethodCallExpression) {
+          final PsiReferenceExpression methodExpression = ((PsiMethodCallExpression)expr).getMethodExpression();
+          final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
+          if (qualifierExpression == null) {
+            final PsiClass containingClass = method.getContainingClass();
+            LOG.assertTrue(containingClass != null);
+            if (method.getModifierList().hasModifierProperty(PsiModifier.STATIC)) {
+              methodExpression.setQualifierExpression(elementFactory.createReferenceExpression(containingClass));
+            } else {
+              methodExpression.setQualifierExpression(createThisExpression(method.getManager(), thisClass, refParent));
             }
           }
         }
       }
-
-      if (!matchedTypes) {
-        if (varType instanceof PsiEllipsisType && ((PsiEllipsisType)varType).getComponentType().equals(exprType)) { //convert vararg to array
-
-          final PsiExpressionList argumentList = PsiTreeUtil.getParentOfType(expr, PsiExpressionList.class);
-          LOG.assertTrue(argumentList != null);
-          final PsiExpression[] arguments = argumentList.getExpressions();
-
-          @NonNls final StringBuilder builder = new StringBuilder("new ");
-          builder.append(exprType.getCanonicalText());
-          builder.append("[]{");
-          builder.append(StringUtil.join(Arrays.asList(arguments), new Function<PsiExpression, String>() {
-            @Override
-            public String fun(final PsiExpression expr) {
-              return expr.getText();
-            }
-          }, ","));
-          builder.append('}');
-
-          expr.replace(JavaPsiFacade.getInstance(manager.getProject()).getElementFactory().createExpressionFromText(builder.toString(), argumentList));
-
-        } else {
-          //try cast
-          PsiTypeCastExpression cast = (PsiTypeCastExpression)elementFactory.createExpressionFromText("(t)a", null);
-          PsiTypeElement castTypeElement = cast.getCastType();
-          assert castTypeElement != null;
-          castTypeElement.replace(variable.getTypeElement());
-          final PsiExpression operand = cast.getOperand();
-          assert operand != null;
-          operand.replace(expr);
-          PsiExpression exprCopy = (PsiExpression)expr.copy();
-          cast = (PsiTypeCastExpression)expr.replace(cast);
-          if (!RedundantCastUtil.isCastRedundant(cast)) {
-            expr = cast;
-          }
-          else {
-            PsiElement toReplace = cast;
-            while (toReplace.getParent() instanceof PsiParenthesizedExpression) {
-              toReplace = toReplace.getParent();
-            }
-            expr = (PsiExpression)toReplace.replace(exprCopy);
-          }
+      else if (varType instanceof PsiEllipsisType &&
+               ((PsiEllipsisType)varType).getComponentType().equals(exprType)) { //convert vararg to array
+        final PsiExpressionList argumentList = PsiTreeUtil.getParentOfType(expr, PsiExpressionList.class);
+        LOG.assertTrue(argumentList != null);
+        final PsiExpression[] arguments = argumentList.getExpressions();
+        String varargsWrapper = "new " + exprType.getCanonicalText() + "[]{" + StringUtil.join(Arrays.asList(arguments), PsiElement::getText, ",") + '}';
+        expr.replace(elementFactory.createExpressionFromText(varargsWrapper, argumentList));
+      }
+      else {
+        boolean insertCastWhenUnchecked = !(exprType instanceof PsiClassType && ((PsiClassType)exprType).isRaw() && parent instanceof PsiExpressionList);
+        if (expr instanceof PsiFunctionalExpression || !PsiPolyExpressionUtil.isPolyExpression(expr) && insertCastWhenUnchecked) {
+          expr = surroundWithCast(variable, expr);
         }
       }
-    } else if (exprType instanceof PsiLambdaExpressionType) {
-      expr = surroundWithCast(variable, expr, ((PsiLambdaExpressionType)exprType).getExpression());
-    } else if (exprType instanceof PsiMethodReferenceType) {
-      expr = surroundWithCast(variable, expr, ((PsiMethodReferenceType)exprType).getExpression());
     }
 
     ChangeContextUtil.clearContextInfo(initializer);
@@ -170,21 +112,45 @@ public class InlineUtil {
     return expr;
   }
 
-  private static PsiExpression surroundWithCast(PsiVariable variable, PsiExpression expr, PsiExpression expression) {
-    final PsiElement parent = expression.getParent();
-    if (parent instanceof PsiReferenceExpression || parent instanceof PsiExpressionList) {
-      PsiTypeCastExpression cast = (PsiTypeCastExpression)JavaPsiFacade.getElementFactory(expr.getProject()).createExpressionFromText("(t)a", null);
-      PsiTypeElement castTypeElement = cast.getCastType();
-      assert castTypeElement != null;
-      castTypeElement.replace(variable.getTypeElement());
-      final PsiExpression operand = cast.getOperand();
-      assert operand != null;
-      operand.replace(expr);
-      expr = (PsiTypeCastExpression)expr.replace(cast);
-      if (RedundantCastUtil.isCastRedundant((PsiTypeCastExpression)expr)) {
-        expr = (PsiExpression)expr.replace(((PsiTypeCastExpression)expr).getOperand());
+  private static PsiMethod qualifyWithExplicitTypeArguments(PsiExpression initializer,
+                                                            PsiExpression expr,
+                                                            PsiType varType) {
+    final PsiElementFactory elementFactory = JavaPsiFacade.getInstance(initializer.getProject()).getElementFactory();
+    if (expr instanceof PsiCallExpression && ((PsiCallExpression)expr).getTypeArguments().length == 0) {
+      final JavaResolveResult resolveResult = ((PsiCallExpression)initializer).resolveMethodGenerics();
+      final PsiElement resolved = resolveResult.getElement();
+      if (resolved instanceof PsiMethod) {
+        final PsiTypeParameter[] typeParameters = ((PsiMethod)resolved).getTypeParameters();
+        if (typeParameters.length > 0) {
+          final PsiCallExpression copy = (PsiCallExpression)expr.copy();
+          for (final PsiTypeParameter typeParameter : typeParameters) {
+            final PsiType substituted = resolveResult.getSubstitutor().substitute(typeParameter);
+            if (substituted == null) break;
+            copy.getTypeArgumentList().add(elementFactory.createTypeElement(substituted));
+          }
+          if (varType.equals(copy.getType())) {
+            ((PsiCallExpression)expr).getTypeArgumentList().replace(copy.getTypeArgumentList());
+            return (PsiMethod)resolved;
+          }
+        }
       }
     }
+    return null;
+  }
+
+  private static PsiExpression surroundWithCast(PsiVariable variable, PsiExpression expr) {
+    PsiTypeCastExpression cast = (PsiTypeCastExpression)JavaPsiFacade.getElementFactory(expr.getProject()).createExpressionFromText("(t)a", null);
+    PsiTypeElement castTypeElement = cast.getCastType();
+    assert castTypeElement != null;
+    castTypeElement.replace(variable.getTypeElement());
+    final PsiExpression operand = cast.getOperand();
+    assert operand != null;
+    operand.replace(expr);
+    expr = (PsiTypeCastExpression)expr.replace(cast);
+    if (RedundantCastUtil.isCastRedundant((PsiTypeCastExpression)expr)) {
+      return RedundantCastUtil.removeCast((PsiTypeCastExpression)expr);
+    }
+
     return expr;
   }
 
index 1563adae7bc5c897d2ff872253b16ae9c50be1a5..a4b8f3a8d250e523092387d8abed7273ff55d5d4 100644 (file)
@@ -17,6 +17,7 @@ package com.intellij.spi.psi;
 
 import com.intellij.codeInsight.lookup.LookupElementBuilder;
 import com.intellij.lang.ASTNode;
+import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
 import com.intellij.psi.search.searches.ClassInheritorsSearch;
 import com.intellij.psi.util.ClassUtil;
@@ -35,6 +36,11 @@ public class SPIClassProviderReferenceElement extends SPIPackageOrClassReference
     super(node);
   }
 
+  @Override
+  public TextRange getRangeInElement() {
+    return TextRange.from(0, getTextLength());
+  }
+
   @NotNull
   @Override
   public Object[] getVariants() {
index 41b84266a684a5ad47a43ae1624d8d4203fec8de..eba2d0254247de47b9955adb3255365e4a5f5499 100644 (file)
@@ -260,7 +260,7 @@ public class JavaClassInheritorsSearcher extends QueryExecutorBase<PsiClass, Cla
           }
           currentlyProcessingClasses.down(); // tell other threads we are going to process this candidate
         }
-        PsiClass candidate = next == null ? myBaseClass : (PsiClass)next.retrieve();
+        PsiClass candidate = next == null ? myBaseClass : ApplicationManager.getApplication().runReadAction((Computable<PsiClass>)() -> (PsiClass)next.retrieve());
 
         boolean added;
         try {
index 124fcea2ce628bb10633c717d7ef0cdd95c3b30b..57c6d99f73c7fcbf01af1eec649c1740d1f6ca3c 100644 (file)
@@ -71,29 +71,30 @@ public class RedundantCastUtil {
     return arg;
   }
 
-  public static void removeCast(PsiTypeCastExpression castExpression) {
-    if (castExpression == null) return;
+  public static PsiExpression removeCast(PsiTypeCastExpression castExpression) {
+    if (castExpression == null) return null;
     PsiExpression operand = castExpression.getOperand();
     if (operand instanceof PsiParenthesizedExpression) {
       final PsiParenthesizedExpression parExpr = (PsiParenthesizedExpression)operand;
       operand = parExpr.getExpression();
     }
-    if (operand == null) return;
+    if (operand == null) return null;
 
-    PsiElement toBeReplaced = castExpression;
+    PsiExpression toBeReplaced = castExpression;
 
     PsiElement parent = castExpression.getParent();
     while (parent instanceof PsiParenthesizedExpression) {
-      toBeReplaced = parent;
+      toBeReplaced = (PsiExpression)parent;
       parent = parent.getParent();
     }
 
     try {
-      toBeReplaced.replace(operand);
+      return (PsiExpression)toBeReplaced.replace(operand);
     }
     catch (IncorrectOperationException e) {
       LOG.error(e);
     }
+    return toBeReplaced;
   }
 
   private static class MyCollectingVisitor extends MyIsRedundantVisitor {
index 8ccab9517a7b9ec7543778cc8d64a7eaa844f405..99e2a24aa5fc3d51dbe8214d85588cd3350d0057 100644 (file)
@@ -33,10 +33,7 @@ import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 
 import static com.intellij.psi.CommonClassNames.JAVA_LANG_STRING;
 
@@ -839,7 +836,7 @@ public class TypeConversionUtil {
       return false; // must be TypeCook's PsiTypeVariable
     }
     if (left instanceof PsiPrimitiveType) {
-      return isUnboxable((PsiPrimitiveType)left, (PsiClassType)right);
+      return isUnboxable((PsiPrimitiveType)left, (PsiClassType)right, new HashSet<PsiClassType>());
     }
     final PsiClassType.ClassResolveResult leftResult = PsiUtil.resolveGenericsClassInType(left);
     final PsiClassType.ClassResolveResult rightResult = PsiUtil.resolveGenericsClassInType(right);
@@ -880,7 +877,20 @@ public class TypeConversionUtil {
     return isAssignable(wildcardType.getExtendsBound(), right);
   }
 
-  private static boolean isUnboxable(@NotNull PsiPrimitiveType left, @NotNull PsiClassType right) {
+  private static boolean isUnboxable(@NotNull PsiPrimitiveType left, @NotNull PsiClassType right, @NotNull Set<PsiClassType> types) {
+    if (!right.getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5)) return false;
+    final PsiClass psiClass = right.resolve();
+    if (psiClass == null) return false;
+
+    if (psiClass instanceof PsiTypeParameter) {
+      for (PsiClassType bound : psiClass.getExtendsListTypes()) {
+        if (types.add(bound) && isUnboxable(left, bound, types)) {
+          return true;
+        }
+      }
+      return false;
+    }
+
     final PsiPrimitiveType rightUnboxedType = PsiPrimitiveType.getUnboxedType(right);
     return rightUnboxedType != null && isAssignable(left, rightUnboxedType);
   }
index da93b54be6a86cfae08cbc94a5686cdacaa443f5..cd9e053468cd5d2543a81962c279fda097319a0b 100644 (file)
@@ -95,6 +95,9 @@ public class JavaLightStubBuilder extends LightStubBuilder {
     if (nodeType == JavaElementType.PARAMETER_LIST && parentType == JavaElementType.LAMBDA_EXPRESSION) {
       return true;
     }
+    if (nodeType == JavaDocElementType.DOC_COMMENT) {
+      return true;
+    }
 
     return false;
   }
index e3298e65cf017d349598728ce2af5a66ee3b51a8..fba9855a722930f1399968c40368dac647f3c52d 100644 (file)
@@ -28,15 +28,20 @@ import com.intellij.psi.infos.CandidateInfo;
 import com.intellij.psi.javadoc.PsiDocComment;
 import com.intellij.psi.scope.PsiScopeProcessor;
 import com.intellij.psi.util.InheritanceUtil;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 public class JavaResolveUtil {
-  public static PsiClass getContextClass(PsiElement element) {
+  public static PsiClass getContextClass(@NotNull PsiElement element) {
+    PsiElement prev = element;
     PsiElement scope = element.getContext();
     while (scope != null) {
-      if (scope instanceof PsiClass) return (PsiClass)scope;
+      if (scope instanceof PsiClass && (prev instanceof PsiMember || prev instanceof PsiDocComment)) {
+        return (PsiClass)scope;
+      }
+      prev = scope;
       scope = scope.getContext();
     }
     return null;
@@ -110,15 +115,19 @@ public class JavaResolveUtil {
       if (memberClass == null) {
         return false;
       }
-      for (PsiElement placeParent = place; placeParent != null; placeParent = placeParent.getContext()) {
-        if (placeParent instanceof PsiClass && InheritanceUtil.isInheritorOrSelf((PsiClass)placeParent, memberClass, true)) {
+      PsiClass contextClass = member instanceof PsiClass ? getContextClass(place)
+                                                         : PsiTreeUtil.getContextOfType(place, PsiClass.class, false);
+      while (contextClass != null) {
+        if (InheritanceUtil.isInheritorOrSelf(contextClass, memberClass, true)) {
           if (member instanceof PsiClass ||
               modifierList.hasModifierProperty(PsiModifier.STATIC) ||
               accessObjectClass == null ||
-              InheritanceUtil.isInheritorOrSelf(accessObjectClass, (PsiClass)placeParent, true)) {
+              InheritanceUtil.isInheritorOrSelf(accessObjectClass, contextClass, true)) {
             return true;
           }
         }
+
+        contextClass = getContextClass(contextClass);
       }
       return false;
     }
index 8d40e2914d9c61c2625e63a072623aa5398298a2..b993727a30edea4a25d5ab556af5f09c306ba62f 100644 (file)
@@ -54,9 +54,7 @@ public class MethodReferenceResolver implements ResolveCache.PolyVariantContextR
       final PsiElement element = reference.getReferenceNameElement();
       final boolean isConstructor = reference.isConstructor();
       if (element instanceof PsiIdentifier || isConstructor) {
-        if (isConstructor && (containingClass.isEnum() ||
-                              containingClass.hasModifierProperty(PsiModifier.ABSTRACT) ||
-                              containingClass instanceof PsiTypeParameter)) {
+        if (isConstructor && !canBeConstructed(containingClass)) {
           return JavaResolveResult.EMPTY_ARRAY;
         }
         final PsiType functionalInterfaceType = getInterfaceType(reference);
@@ -166,6 +164,10 @@ public class MethodReferenceResolver implements ResolveCache.PolyVariantContextR
     return JavaResolveResult.EMPTY_ARRAY;
   }
 
+  public static boolean canBeConstructed(@NotNull PsiClass psiClass) {
+    return !psiClass.isEnum() && !psiClass.hasModifierProperty(PsiModifier.ABSTRACT) && !(psiClass instanceof PsiTypeParameter);
+  }
+
   private static boolean isLocatedInStaticContext(PsiClass containingClass, PsiMethodReferenceExpression reference) {
     final PsiClass gContainingClass = containingClass.getContainingClass();
     if (gContainingClass == null || !containingClass.hasModifierProperty(PsiModifier.STATIC)) {
diff --git a/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse.java b/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse.java
new file mode 100644 (file)
index 0000000..90e83a4
--- /dev/null
@@ -0,0 +1,9 @@
+
+class Foo {
+    {
+        if (t != true<caret>)
+            logger.error("SimulationClient.run error: strategy () still running. please stop it before restart.");
+        else
+            proxy.startStopStrategy("strategyName", true);
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse_after.java b/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfAndElse_after.java
new file mode 100644 (file)
index 0000000..dd1c533
--- /dev/null
@@ -0,0 +1,11 @@
+
+class Foo {
+    {
+        if (t != true) {
+            <caret>
+            logger.error("SimulationClient.run error: strategy () still running. please stop it before restart.");
+        } else {
+            proxy.startStopStrategy("strategyName", true);
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner.java b/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner.java
new file mode 100644 (file)
index 0000000..b2621a1
--- /dev/null
@@ -0,0 +1,7 @@
+
+class Foo {
+    {
+        if (t != true<caret>)
+            logger.error("SimulationClient.run error: strategy () still running. please stop it before restart.");
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner_after.java b/java/java-tests/testData/codeInsight/completeStatement/AddBracesToIfThenOneLiner_after.java
new file mode 100644 (file)
index 0000000..1453fb9
--- /dev/null
@@ -0,0 +1,9 @@
+
+class Foo {
+    {
+        if (t != true) {
+            <caret>
+            logger.error("SimulationClient.run error: strategy () still running. please stop it before restart.");
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/DefaultColon.java b/java/java-tests/testData/codeInsight/completeStatement/DefaultColon.java
new file mode 100644 (file)
index 0000000..c1e4e58
--- /dev/null
@@ -0,0 +1,8 @@
+
+class Foo {
+    void foo(String a) {
+        switch (a) {
+            default<caret>
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/DefaultColon_after.java b/java/java-tests/testData/codeInsight/completeStatement/DefaultColon_after.java
new file mode 100644 (file)
index 0000000..3e898b1
--- /dev/null
@@ -0,0 +1,9 @@
+
+class Foo {
+    void foo(String a) {
+        switch (a) {
+            default:
+                <caret>
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference.java b/java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference.java
new file mode 100644 (file)
index 0000000..1811c37
--- /dev/null
@@ -0,0 +1,6 @@
+@interface AbcdAnno {}
+
+class Foo {
+  void foo(@Abc<caret>Foo.Bar f) {}
+  static class Bar{}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference_after.java b/java/java-tests/testData/codeInsight/completion/normal/AnnotationBeforeQualifiedReference_after.java
new file mode 100644 (file)
index 0000000..d7c1ef1
--- /dev/null
@@ -0,0 +1,6 @@
+@interface AbcdAnno {}
+
+class Foo {
+  void foo(@AbcdAnno<caret> Foo.Bar f) {}
+  static class Bar{}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/NoExpectedReturnTypeDuplication.java b/java/java-tests/testData/codeInsight/completion/normal/NoExpectedReturnTypeDuplication.java
new file mode 100644 (file)
index 0000000..6a8b5d5
--- /dev/null
@@ -0,0 +1,5 @@
+class Foo {
+    b<caret> foo() {
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon.java b/java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon.java
new file mode 100644 (file)
index 0000000..108e2e2
--- /dev/null
@@ -0,0 +1,11 @@
+class Foo {
+  void foo(Constants c) {
+    switch (c) {
+        case B<caret>
+    }
+  }
+}
+
+enum Constants {
+  BAR0, BAR1;
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon_after.java b/java/java-tests/testData/codeInsight/completion/normal/SwitchValueFinishWithColon_after.java
new file mode 100644 (file)
index 0000000..8047388
--- /dev/null
@@ -0,0 +1,11 @@
+class Foo {
+  void foo(Constants c) {
+    switch (c) {
+        case BAR0:<caret>
+    }
+  }
+}
+
+enum Constants {
+  BAR0, BAR1;
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter.java b/java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter.java
new file mode 100644 (file)
index 0000000..9a1b95d
--- /dev/null
@@ -0,0 +1,7 @@
+public class Bar {
+    {
+        String foo1 = "";
+        String foo2 = "";
+        synchronized (foo<caret>)
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter_after.java b/java/java-tests/testData/codeInsight/completion/normal/SynchronizedArgumentSmartEnter_after.java
new file mode 100644 (file)
index 0000000..c632786
--- /dev/null
@@ -0,0 +1,9 @@
+public class Bar {
+    {
+        String foo1 = "";
+        String foo2 = "";
+        synchronized (foo1) {
+            <caret>
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normalSorting/GenericityDoesNotMatterWhenNoTypeIsExpected.java b/java/java-tests/testData/codeInsight/completion/normalSorting/GenericityDoesNotMatterWhenNoTypeIsExpected.java
new file mode 100644 (file)
index 0000000..2180271
--- /dev/null
@@ -0,0 +1,9 @@
+class Test {
+
+    void nonGeneric() {}
+    <T> T generic() {}
+
+    {
+        this.<caret>
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef-out.java b/java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef-out.java
new file mode 100644 (file)
index 0000000..f53cf9c
--- /dev/null
@@ -0,0 +1,7 @@
+import foo.ImplBar;
+
+class Test {
+  void foo() {
+    java.util.function.Supplier<intf.Intf<String>> s = ImplBar::new;<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef.java b/java/java-tests/testData/codeInsight/completion/smartType/InheritorConstructorRef.java
new file mode 100644 (file)
index 0000000..2556c5c
--- /dev/null
@@ -0,0 +1,5 @@
+class Test {
+  void foo() {
+    java.util.function.Supplier<intf.Intf<String>> s = <caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor-out.java b/java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor-out.java
new file mode 100644 (file)
index 0000000..df8ad20
--- /dev/null
@@ -0,0 +1,16 @@
+import java.util.*;
+
+class MyTest {
+
+  public interface Parent {
+    boolean hasFlag();
+  }
+
+  public interface Child extends Parent {}
+
+  public static void main(String[] args) {
+    List<Child> children = new ArrayList<>();
+    children.stream().filter(Parent::hasFlag)<caret>
+  }
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor.java b/java/java-tests/testData/codeInsight/completion/smartType/MethodReferenceOnAncestor.java
new file mode 100644 (file)
index 0000000..780cad9
--- /dev/null
@@ -0,0 +1,16 @@
+import java.util.*;
+
+class MyTest {
+
+  public interface Parent {
+    boolean hasFlag();
+  }
+
+  public interface Child extends Parent {}
+
+  public static void main(String[] args) {
+    List<Child> children = new ArrayList<>();
+    children.stream().filter(hasF<caret>)
+  }
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnboxingFromTypeParameter.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnboxingFromTypeParameter.java
new file mode 100644 (file)
index 0000000..b757661
--- /dev/null
@@ -0,0 +1,7 @@
+class Test {
+  <T extends S, S extends Long, K extends Long & Runnable> void method1(T param, S param1, K param2) {
+    long l = param;
+    long l1 = param1;
+    long l2 = param2;
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/InheritorConstructorRef.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/InheritorConstructorRef.java
new file mode 100644 (file)
index 0000000..ce873b9
--- /dev/null
@@ -0,0 +1,5 @@
+class Foo {
+  {
+    java.util.function.Supplier<java.util.List<String>> s = ArrayL<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/LambdaWithCapturedSuperWildcardInAmbiguousCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/completion/normal/LambdaWithCapturedSuperWildcardInAmbiguousCall.java
deleted file mode 100644 (file)
index 523e3e0..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-import java.util.stream.*;
-import java.util.*;
-
-class Foo {
-  void main(Stream<? super String> stream) {
-    stream.collect(Collectors.toMap(o -> o.sub<caret>))
-  }
-}
\ No newline at end of file
index bf49e4aca6a23a6207b01d147710fce3041d77fd..bb5e5062608008f444bab86452386919f3b79651 100644 (file)
     <line>5</line>
     <description>Test-only method is called in production code</description>
   </problem>
+  <problem>
+    <file>B.java</file>
+    <line>6</line>
+    <description>Test-only class is referenced in production code</description>
+  </problem>
+  <problem>
+    <file>B.java</file>
+    <line>7</line>
+    <description>Test-only method is called in production code</description>
+  </problem>
+
 </problems>
index f65ba879eaf106121741784cbe81d947888b5f5a..4f56a174a80d908093b6e90b629083016c307696 100644 (file)
@@ -18,4 +18,16 @@ public class A {
   void relaxedToPackageLevel(int a) {
 
   }
+
+  @com.google.common.annotations.VisibleForTesting
+  static class FooException extends RuntimeException {
+    FooException(String message) {
+      super(message);
+    }
+  }
+
+  public static void usingExceptionPrivately(String[] args) {
+    A.FooException exception =
+      new A.FooException("");
+  }
 }
\ No newline at end of file
index 429a154ec49fc973250e176ffe7bb3e96cff5f6c..ec8595d6f41e93314f08341d114048386aae7222 100644 (file)
@@ -3,5 +3,7 @@ public class B {
     new A().invisibleMethod(2);
     new A().visibleMethod(2);
     new A().relaxedToPackageLevel(2);
+    A.FooException exception =
+      new A.FooException("");
   }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/psi/resolve/class/QualifiedAnonymousClass.java b/java/java-tests/testData/psi/resolve/class/QualifiedAnonymousClass.java
new file mode 100644 (file)
index 0000000..83bb366
--- /dev/null
@@ -0,0 +1,8 @@
+import foo.Outer;
+
+class Foo {
+  {
+    new Outer.<ref>Inner() { };
+  }
+}
+
diff --git a/java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java b/java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java
new file mode 100644 (file)
index 0000000..560d619
--- /dev/null
@@ -0,0 +1,12 @@
+
+interface Vector<M> {
+  M get(int i);
+}
+class Test {
+
+  private static void call(Vector args_) {
+    Vector<String> ar<caret>gs = args_;
+
+    String s = args.get(0);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java.after b/java/java-tests/testData/refactoring/inlineLocal/InsertCastToGenericTypeToProvideValidReturnType.java.after
new file mode 100644 (file)
index 0000000..929fedc
--- /dev/null
@@ -0,0 +1,11 @@
+
+interface Vector<M> {
+  M get(int i);
+}
+class Test {
+
+  private static void call(Vector args_) {
+
+      String s = ((Vector<String>) args_).get(0);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java b/java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java
new file mode 100644 (file)
index 0000000..4d29fad
--- /dev/null
@@ -0,0 +1,18 @@
+
+class Cat {}
+class DomesticCat extends Cat {}
+
+class Test {
+  public static void main(String[] args) {
+    Cat c<caret>at = new DomesticCat();
+    petCat(cat);
+  }
+
+  static void petCat(Cat cat) {
+    System.out.println("A Cat");
+  }
+
+  static void petCat(DomesticCat domesticCat) {
+    System.out.println("A DomesticCat");
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java.after b/java/java-tests/testData/refactoring/inlineLocal/InsertNarrowingCastToAvoidSemanticsChange.java.after
new file mode 100644 (file)
index 0000000..521a626
--- /dev/null
@@ -0,0 +1,17 @@
+
+class Cat {}
+class DomesticCat extends Cat {}
+
+class Test {
+  public static void main(String[] args) {
+      petCat((Cat) new DomesticCat());
+  }
+
+  static void petCat(Cat cat) {
+    System.out.println("A Cat");
+  }
+
+  static void petCat(DomesticCat domesticCat) {
+    System.out.println("A DomesticCat");
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java b/java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java
new file mode 100644 (file)
index 0000000..896d939
--- /dev/null
@@ -0,0 +1,6 @@
+class Test {
+  public static void main(String[] args) {
+    int <caret>i = 7 - 6;
+    System.out.println("3 + 2 = " + i);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java.after b/java/java-tests/testData/refactoring/inlineLocal/OperationPrecedenceWhenInlineToStringConcatenation.java.after
new file mode 100644 (file)
index 0000000..d260041
--- /dev/null
@@ -0,0 +1,5 @@
+class Test {
+  public static void main(String[] args) {
+      System.out.println("3 + 2 = " + (7 - 6));
+  }
+}
\ No newline at end of file
index ac42193d7c880a86ca4860e34c48cb339b05c4c1..576e3e00a1a4b027e47282477b2dcd3db8ff17bb 100644 (file)
@@ -43,6 +43,10 @@ public class CompleteStatementTest extends EditorActionTestCase {
 
   public void testCompleteIfStatementGoesToThen() throws Exception { doTest(); }
 
+  public void testAddBracesToIfAndElse() { doTest(); }
+
+  public void testAddBracesToIfThenOneLiner() { doTest(); }
+
   public void testCompleteIfKeywordStatementGoesToThen() throws Exception { doTest(); }
 
   public void testIndentation() throws Exception { doTest(); }
@@ -222,6 +226,7 @@ public class CompleteStatementTest extends EditorActionTestCase {
   public void testSwitchKeywordWithCondition() throws Exception { doTest(); }
   public void testSwitchBraces() { doTest(); }
   public void testCaseColon() { doTest(); }
+  public void testDefaultColon() { doTest(); }
 
   public void testNewInParentheses() throws Exception { doTest(); }
   
index 29a40fe7071c5ed3fb44f43bfee4f2314799cb5e..b671bc48369525988aa80c7044ee012741d5c3c2 100644 (file)
@@ -174,7 +174,12 @@ class Test88 {
 }
 """
   }
-  
+
+  public void testInheritorConstructorRef() {
+    configureByTestName()
+    myFixture.assertPreferredCompletionItems 0, 'ArrayList::new', 'ArrayList'
+  }
+
   public void "test constructor ref without start"() {
     myFixture.configureByText "a.java", """
 interface Foo9 {
@@ -219,7 +224,7 @@ class Test88 {
 
   public void testAllCollectors() {
     configureByTestName()
-    myFixture.assertPreferredCompletionItems 0, 'collect(Collectors.toCollection())', 'collect', 'collect', 'collect(Collectors.toList())', 'collect(Collectors.toSet())'
+    myFixture.assertPreferredCompletionItems 0, 'collect', 'collect', 'collect(Collectors.toCollection())', 'collect(Collectors.toList())', 'collect(Collectors.toSet())'
     selectItem(myItems.find { it.lookupString.contains('toCollection') })
     checkResultByFile(getTestName(false) + "_after.java")
   }
@@ -244,10 +249,6 @@ class Test88 {
     configureByTestName()
     myFixture.assertPreferredCompletionItems(0, 'substring', 'substring', 'subSequence')
   }
-  public void testLambdaWithCapturedSuperWildcardInAmbiguousCall() {
-    configureByTestName()
-    myFixture.assertPreferredCompletionItems(0, 'substring', 'substring', 'subSequence')
-  }
   public void testUnexpectedLambdaInAmbiguousCall() { doAntiTest() }
 
   public void testNoCollectorsInComment() { doAntiTest() }
index 2aeb10b51b01ad9816cf25c73c992775f5ff21c0..00fc2da57eb7ac12a5f87d9224db79303a942fae 100644 (file)
@@ -99,6 +99,10 @@ public class NormalCompletionOrderingTest extends CompletionSortingTestCase {
     checkPreferredItems(0, "getService", "getService", "class");
   }
 
+  public void testGenericityDoesNotMatterWhenNoTypeIsExpected() {
+    checkPreferredItems 0, "generic", "nonGeneric", "clone", "equals"
+  }
+
   public void testClassStaticMembersInVoidContext() throws Throwable {
     checkPreferredItems(0, "booleanMethod", "voidMethod", "AN_OBJECT", "BOOLEAN", "class");
   }
index cac0f231934745d0f4e12049c411cfe1f622e180..c250bb43d3147932fb50ba16b6a5d866b937e824 100644 (file)
@@ -30,6 +30,7 @@ import com.intellij.psi.PsiMethod
 import com.intellij.psi.codeStyle.CodeStyleSettingsManager
 import com.intellij.psi.codeStyle.CommonCodeStyleSettings
 import com.intellij.psi.impl.PsiDocumentManagerBase
+import com.intellij.util.ui.UIUtil
 import com.siyeh.ig.style.UnqualifiedFieldAccessInspection
 
 public class NormalCompletionTest extends LightFixtureCompletionTestCase {
@@ -660,6 +661,11 @@ public class ListUtils {
 
   public void testInnerEnumConstant() throws Throwable { doTest('\n'); }
 
+  public void testNoExpectedReturnTypeDuplication() {
+    configure()
+    assert myFixture.lookupElementStrings == ['boolean', 'byte']
+  }
+
   public void testMethodReturnType() throws Throwable {
     doTest();
   }
@@ -950,7 +956,7 @@ public class ListUtils {
   public void testTabReplacesMethodNameWithLocalVariableName() throws Throwable { doTest('\t'); }
   public void testMethodParameterAnnotationClass() throws Throwable { doTest(); }
   public void testInnerAnnotation() { doTest('\n'); }
-  public void testPrimitiveCastOverwrite() throws Throwable { doTest '\t' }
+  public void testPrimitiveCastOverwrite() throws Throwable { doTest() }
   public void testClassReferenceInFor() throws Throwable { doTest ' ' }
   public void testClassReferenceInFor2() throws Throwable { doTest ' ' }
   public void testClassReferenceInFor3() throws Throwable {
@@ -1016,6 +1022,7 @@ public class ListUtils {
   public void testOnlyAnnotationsAfterAt() throws Throwable { doTest() }
   public void testOnlyAnnotationsAfterAt2() throws Throwable { doTest('\n') }
   public void testAnnotationBeforeIdentifier() { doTest('\n') }
+  public void testAnnotationBeforeQualifiedReference() { doTest('\n') }
   public void testAnnotationBeforeIdentifierFinishWithSpace() { doTest(' ') }
 
   public void testOnlyExceptionsInCatch1() throws Exception { doTest('\n') }
@@ -1040,6 +1047,7 @@ public class ListUtils {
   public void testNoFieldsInImplements() throws Throwable { doTest() }
 
   public void testSwitchConstantsFromReferencedClass() throws Throwable { doTest('\n') }
+  public void testSwitchValueFinishWithColon() throws Throwable { doTest(':') }
 
   public void testUnfinishedMethodTypeParameter() throws Throwable {
     configure()
@@ -1101,6 +1109,7 @@ public class ListUtils {
     myFixture.performEditorAction(IdeActions.ACTION_CHOOSE_LOOKUP_ITEM_COMPLETE_STATEMENT)
     checkResult()
   }
+  void testSynchronizedArgumentSmartEnter() { doTest(Lookup.COMPLETE_STATEMENT_SELECT_CHAR as String) }
 
   public void testImportStringValue() throws Throwable {
     myFixture.addClass("package foo; public class StringValue {}")
@@ -1536,6 +1545,7 @@ class Bar {
     myFixture.configureByText "a.java", "class Foo {int i; ge<caret>}"
     myFixture.enableInspections(new UnqualifiedFieldAccessInspection())
     myFixture.complete(CompletionType.BASIC)
+    UIUtil.dispatchAllInvocationEvents()
     myFixture.checkResult '''class Foo {int i;
 
     public int getI() {
index 6ff7aa17c75d69d59a456fe402b81b2f1a98c2b4..1e1e4eca0a0fc168198f07b571c95f940196da1a 100644 (file)
@@ -85,6 +85,19 @@ public class SmartType18CompletionTest extends LightFixtureCompletionTestCase {
     doTest(false);
   }
 
+  public void testInheritorConstructorRef() {
+    myFixture.addClass("package intf; public interface Intf<T> {}");
+    myFixture.addClass("package foo; public class ImplBar implements intf.Intf<String> {}");
+    myFixture.addClass("package foo; public class ImplFoo<T> implements intf.Intf<T> {}");
+    myFixture.addClass("package foo; public class ImplIncompatible implements intf.Intf<Integer> {}");
+    myFixture.addClass("package foo; class ImplInaccessible implements intf.Intf<String> {}");
+
+    configureByTestName();
+    myFixture.assertPreferredCompletionItems(0, "ImplBar::new", "ImplFoo::new", "()");
+    myFixture.type('\n');
+    checkResultByFile("/" + getTestName(false) + "-out.java");
+  }
+
   public void testFilteredMethodReference() throws Exception {
     doTest(false);
   }
@@ -127,6 +140,8 @@ public class SmartType18CompletionTest extends LightFixtureCompletionTestCase {
     doTest(true);
   }
 
+  public void testMethodReferenceOnAncestor() { doTest(true); }
+
   public void testNoLambdaSuggestionForGenericsFunctionalInterfaceMethod() throws Exception {
     configureByFile("/" + getTestName(false) + ".java");
     assertEmpty(myItems);
index 90a76764c9c0234f1065733b4b40d58b87524569..2b10c698a0c45345bd0ff16a20a1f5a07865829d 100644 (file)
@@ -575,6 +575,10 @@ public class GenericsHighlightingTest extends LightDaemonAnalyzerTestCase {
     doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
   }
 
+  public void testUnboxingFromTypeParameter() throws Exception {
+    doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
+  }
+
   public void testLeastUpperBoundWithRecursiveTypes() throws Exception {
     final PsiManager manager = getPsiManager();
     final GlobalSearchScope scope = GlobalSearchScope.allScope(getProject());
index 70d76c6a1691004add21177691e7a9b463f48ae6..349d50bfff367ae6f291dad4f444a41203d851d0 100644 (file)
@@ -234,10 +234,7 @@ public class DaemonRespondToChangesTest extends DaemonAnalyzerTestCase {
     Collection<HighlightInfo> infos = highlightErrors();
     assertEquals(0, infos.size());
     final PsiClass psiClass = ((PsiJavaFile)getFile()).getClasses()[0];
-    WriteCommandAction.runWriteCommandAction(null, () -> {
-      new RenameProcessor(myProject, psiClass, "Class2", false, false).run();
-      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
-    });
+    new RenameProcessor(myProject, psiClass, "Class2", false, false).run();
 
     TextRange dirty = myDaemonCodeAnalyzer.getFileStatusMap().getFileDirtyScope(document, Pass.UPDATE_ALL);
     assertEquals(getFile().getTextRange(), dirty);
index d74923370e6e15f1a59776880928462ccdaaf32b..c8710e6e290c13f54a94cd858fe4d713757de8f3 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.
@@ -44,14 +44,14 @@ public class InspectionProfilesConverterTest extends LightIdeaTestCase {
     try {
       final String relativePath = "/inspection/converter/";
       final File projectFile = new File(JavaTestUtil.getJavaTestDataPath() + relativePath + dirName + "/options.ipr");
-      for (Element element : JDOMUtil.loadDocument(projectFile).getRootElement().getChildren("component")) {
+      for (Element element : JDOMUtil.load(projectFile).getChildren("component")) {
         if (Comparing.strEqual(element.getAttributeValue("name"), "InspectionProjectProfileManager")) {
           final InspectionProjectProfileManager profileManager = InspectionProjectProfileManager.getInstance(getProject());
           profileManager.loadState(element);
 
           Element configElement = profileManager.getState();
           final File file = new File(JavaTestUtil.getJavaTestDataPath() + relativePath + dirName + "/options.after.xml");
-          PlatformTestUtil.assertElementsEqual(JDOMUtil.loadDocument(file).getRootElement(), configElement);
+          PlatformTestUtil.assertElementsEqual(JDOMUtil.load(file), configElement);
           break;
         }
       }
index 174b9af3507a7c034438ffbb9a98f491114b91d6..95a72e6060de7bc672db47fc0e047d2ebec03034 100644 (file)
@@ -23,8 +23,6 @@ import com.intellij.execution.junit.AllInPackageConfigurationProducer;
 import com.intellij.execution.junit.JUnitConfiguration;
 import com.intellij.execution.junit.JUnitConfigurationProducer;
 import com.intellij.execution.junit.JUnitConfigurationType;
-import com.intellij.openapi.application.Result;
-import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.refactoring.PackageWrapper;
@@ -198,13 +196,8 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
   }
 
   private void moveMembers(final PsiClass otherTest, final HashSet<PsiMember> members) {
-    new WriteCommandAction(myProject) {
-      @Override
-      protected void run(@NotNull Result result) throws Throwable {
-        MockMoveMembersOptions options = new MockMoveMembersOptions(otherTest.getQualifiedName(), members);
-        new MoveMembersProcessor(myProject, null, options).run();
-      }
-    }.executeSilently();
+    MockMoveMembersOptions options = new MockMoveMembersOptions(otherTest.getQualifiedName(), members);
+    new MoveMembersProcessor(myProject, null, options).run();
   }
 
   private void initModule() throws IOException {
@@ -217,24 +210,14 @@ public class ConfigurationRefactoringsTest extends BaseConfigurationTestCase {
     VirtualFile pkgFile = mySource.createPackageDir(packageName);
     final PsiDirectory toDir = PsiManager.getInstance(myProject).findDirectory(pkgFile);
     assertNotNull(toDir);
-    new WriteCommandAction(myProject, psiElement.getContainingFile()) {
-      @Override
-      protected void run(@NotNull Result result) throws Throwable {
-        PackageWrapper wrapper = PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(toDir));
-        new MoveClassesOrPackagesProcessor(myProject, new PsiElement[]{psiElement},
-                                           new SingleSourceRootMoveDestination(wrapper, toDir),
-                                           false, false, null).run();
-      }
-    }.executeSilently();
+    PackageWrapper wrapper = PackageWrapper.create(JavaDirectoryService.getInstance().getPackage(toDir));
+    new MoveClassesOrPackagesProcessor(myProject, new PsiElement[]{psiElement},
+                                       new SingleSourceRootMoveDestination(wrapper, toDir),
+                                       false, false, null).run();
   }
 
   private void rename(final PsiElement psiElement, final String newName) {
-    new WriteCommandAction(myProject, psiElement.getContainingFile()) {
-      @Override
-      protected void run(@NotNull Result result) throws Throwable {
-        new RenameProcessor(myProject, psiElement, newName, false, false).run();
-      }
-    }.executeSilently();
+    new RenameProcessor(myProject, psiElement, newName, false, false).run();
   }
 
   @Override
diff --git a/java/java-tests/testSrc/com/intellij/lang/spi/SPICompletionTest.java b/java/java-tests/testSrc/com/intellij/lang/spi/SPICompletionTest.java
new file mode 100644 (file)
index 0000000..ab2bc38
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * 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.lang.spi;
+
+import com.intellij.codeInsight.lookup.LookupManager;
+import com.intellij.openapi.command.WriteCommandAction;
+import com.intellij.openapi.util.ThrowableComputable;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
+
+import java.io.IOException;
+
+/**
+ * @author peter
+ */
+public class SPICompletionTest extends LightCodeInsightFixtureTestCase {
+
+  public void testQualifiedReference() {
+    myFixture.addClass("package com.foo; public class Interface {}");
+    myFixture.addClass("package com.foo; public class Implementation extends Interface {}");
+    myFixture.configureFromExistingVirtualFile(
+      myFixture.addFileToProject("META-INF/services/com.foo.Interface", "com.f<caret>").getVirtualFile());
+    myFixture.completeBasic();
+    myFixture.checkResult("com.foo.Implementation");
+  }
+
+  public void testCompletionAfterRenaming() throws IOException {
+    VirtualFile file = myFixture.addFileToProject("META-INF/services/aaa", "<caret>").getVirtualFile();
+    myFixture.configureFromExistingVirtualFile(file);
+    assertEmpty(myFixture.completeBasic());
+    LookupManager.getInstance(getProject()).hideActiveLookup();
+
+    WriteCommandAction.runWriteCommandAction(getProject(), (ThrowableComputable<Void, IOException>)() -> {
+      file.rename(this, "java.lang.Runnable");
+      return null;
+    });
+
+    myFixture.completeBasic();
+    myFixture.assertPreferredCompletionItems(0, "java.lang.Thread");
+  }
+
+}
index 40e002e5badb96e612a1a8e792cf21f14d7f7708..fe9acaa3b7fe342ea341b49c126cddc00ea7212e 100644 (file)
@@ -15,6 +15,7 @@
  */
 package com.intellij.navigation
 
+import com.intellij.ide.actions.GotoFileItemProvider
 import com.intellij.ide.util.gotoByName.*
 import com.intellij.lang.java.JavaLanguage
 import com.intellij.openapi.Disposable
@@ -30,6 +31,8 @@ import com.intellij.util.concurrency.Semaphore
 import org.jetbrains.annotations.NotNull
 import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
 
+import javax.swing.SwingUtilities
+
 /**
  * @author peter
  */
@@ -166,6 +169,13 @@ class Intf {
 
   }
 
+  public void "test accept file paths starting with a dot"() {
+    def file = myFixture.addFileToProject("foo/index.html", "foo")
+    def model = new GotoFileModel(project)
+    def popup = ChooseByNamePopup.createPopup(project, model, new GotoFileItemProvider(project, null, model))
+    assert calcPopupElements(popup, "./foo/in") == [file]
+  }
+
   public void "test goto file can go to dir"() {
     PsiFile fooIndex = myFixture.addFileToProject("foo/index.html", "foo")
     PsiFile barIndex = myFixture.addFileToProject("bar.txt/bar.txt", "foo")
@@ -315,7 +325,7 @@ class Intf {
     List<Object> elements = ['empty']
     def semaphore = new Semaphore()
     semaphore.down()
-    edt {
+    SwingUtilities.invokeLater {
       popup.scheduleCalcElements(text, checkboxState, ModalityState.NON_MODAL, { set ->
         elements = set as List
         semaphore.up()
index 62cc6930434cec74bdd14b3ffd52620661cba476..8a7bcb1d0e298e1ca1eae6ebcc6166fb192f28fb 100644 (file)
 package com.intellij.psi.resolve;
 
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.module.ModifiableModuleModel;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.module.StdModuleTypes;
 import com.intellij.openapi.roots.ModuleRootModificationUtil;
+import com.intellij.openapi.util.RecursionManager;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.packageDependencies.DependenciesBuilder;
@@ -226,6 +228,18 @@ public class ResolveClassTest extends ResolveTestCase {
     PlatformTestUtil.assertTiming("exponent?", 20000, System.currentTimeMillis() - start);
   }
 
+  public void testQualifiedAnonymousClass() throws Exception {
+    RecursionManager.assertOnRecursionPrevention(myTestRootDisposable);
+
+    PsiReference ref = configure();
+    VirtualFile file = ref.getElement().getContainingFile().getVirtualFile();
+    assertNotNull(file);
+    VirtualFile pkg = WriteAction.compute(() -> file.getParent().createChildDirectory(this, "foo"));
+    createFile(myModule, pkg, "Outer.java", "package foo; public class Outer { protected static class Inner { protected Inner() {} } }");
+
+    assertEquals("Inner", assertInstanceOf(ref.resolve(), PsiClass.class).getName());
+  }
+
   @SuppressWarnings({"ConstantConditions"})
   private void configureDependency() {
     ApplicationManager.getApplication().runWriteAction(new Runnable() {
index 78eb4760d4ce495b90de678395c0314668cd02e8..983efed5046664960122c1c37641119250e491fd 100644 (file)
@@ -1,6 +1,7 @@
 package com.intellij.psi.resolve;
 
 import com.intellij.navigation.NavigationItem;
+import com.intellij.openapi.util.RecursionManager;
 import com.intellij.psi.*;
 import com.intellij.psi.infos.MethodCandidateInfo;
 import com.intellij.psi.util.PsiTreeUtil;
@@ -242,6 +243,8 @@ public class ResolveMethod15Test extends Resolve15TestCase {
     assertTrue(!((PsiMethod) element).isVarArgs());
   }
   public void testFilterFixedVsVarargs9() throws Exception {
+    RecursionManager.assertOnRecursionPrevention(myTestRootDisposable);
+
     final PsiReference ref = configureByFile();
     assertThat(ref, instanceOf(PsiReferenceExpression.class));
     final PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
@@ -485,6 +488,8 @@ public class ResolveMethod15Test extends Resolve15TestCase {
   }
 
   public void testInheritance4() throws Exception{
+    RecursionManager.assertOnRecursionPrevention(myTestRootDisposable);
+
     PsiReference ref = configureByFile();
     PsiElement target = ref.resolve();
     assertThat(target, instanceOf(PsiMethod.class));
index 808c679d9635e4bc5f680de74200d1fce24e28e1..40be3a539aa35baf89de2b0a7e72075ccf147805 100644 (file)
@@ -264,6 +264,18 @@ public class InlineLocalTest extends LightCodeInsightTestCase {
     doTest(false);
   }
 
+  public void testInsertNarrowingCastToAvoidSemanticsChange() throws Exception {
+    doTest(false);
+  }
+
+  public void testInsertCastToGenericTypeToProvideValidReturnType() throws Exception {
+    doTest(false);
+  }
+
+  public void testOperationPrecedenceWhenInlineToStringConcatenation() throws Exception {
+    doTest(false);
+  }
+
   public void testLocalVarInsideLambdaBodyWriteUsage() throws Exception {
     doTest(true, "Cannot perform refactoring.\n" +
                  "Variable 'hello' is accessed for writing");
index 5e6a31fb1dfa3014f486c6ad84afa39731908883..9a249e4d2993abc34a58c97c986b7999f4d18e8e 100755 (executable)
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2016 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package com.intellij.testFramework.codeInsight.hierarchy;
 
 import com.intellij.codeInsight.CodeInsightTestCase;
@@ -6,7 +21,6 @@ import com.intellij.ide.hierarchy.HierarchyTreeStructure;
 import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.JDOMUtil;
 import com.intellij.openapi.util.io.FileUtil;
-import org.jdom.Document;
 import org.jdom.Element;
 import org.jetbrains.annotations.Nullable;
 
@@ -36,7 +50,7 @@ public abstract class HierarchyViewTestBase extends CodeInsightTestCase {
     final String verificationFilePath = getTestDataPath() + "/" + getBasePath() + "/" + getTestName(false) + "_verification.xml";
     HierarchyTreeStructure structure = treeStructureComputable.compute();
     try {
-      checkHierarchyTreeStructure(structure, JDOMUtil.loadDocument(new File(verificationFilePath)));
+      checkHierarchyTreeStructure(structure, JDOMUtil.load(new File(verificationFilePath)));
     } catch (Throwable e)  {
       assertEquals("XML structure comparison for your convenience, actual failure details BELOW",
                    FileUtil.loadFile(new File(verificationFilePath)), dump(structure, null, 0));
@@ -80,10 +94,9 @@ public abstract class HierarchyViewTestBase extends CodeInsightTestCase {
     }
   }
 
-  private static void checkHierarchyTreeStructure(final HierarchyTreeStructure treeStructure, final Document document) {
+  private static void checkHierarchyTreeStructure(final HierarchyTreeStructure treeStructure, final Element rootElement) {
     final HierarchyNodeDescriptor rootNodeDescriptor = (HierarchyNodeDescriptor)treeStructure.getRootElement();
     rootNodeDescriptor.update();
-    final Element rootElement = document.getRootElement();
     if (rootElement == null || !NODE_ELEMENT_NAME.equals(rootElement.getName())) {
       throw new IllegalArgumentException("Incorrect root element in verification resource");
     }
@@ -130,20 +143,11 @@ public abstract class HierarchyViewTestBase extends CodeInsightTestCase {
     }
     assertEquals(messageBuilder.toString(), expectedChildren.size(), children.length);
 
-    Arrays.sort(children, new Comparator<Object>() {
-      @Override
-      public int compare(final Object first, final Object second) {
-        return ((HierarchyNodeDescriptor)first).getHighlightedText().getText()
-          .compareTo(((HierarchyNodeDescriptor)second).getHighlightedText().getText());
-      }
-    });
+    Arrays.sort(children, (first, second) -> ((HierarchyNodeDescriptor)first).getHighlightedText().getText()
+      .compareTo(((HierarchyNodeDescriptor)second).getHighlightedText().getText()));
 
-    Collections.sort(expectedChildren, new Comparator<Element>() {
-      @Override
-      public int compare(final Element first, final Element second) {
-        return first.getAttributeValue(TEXT_ATTR_NAME).compareTo(second.getAttributeValue(TEXT_ATTR_NAME));
-      }
-    });
+    Collections.sort(expectedChildren,
+                     (first, second) -> first.getAttributeValue(TEXT_ATTR_NAME).compareTo(second.getAttributeValue(TEXT_ATTR_NAME)));
 
     //noinspection unchecked
     final Iterator<Element> iterator = expectedChildren.iterator();
index a0c1e003cbe83453684e106c9b1b54561c3c2d0b..1ca9ee1b4d545b6b4eba967e95e94139692501ca 100644 (file)
@@ -16,8 +16,6 @@
 package com.intellij.testFramework.fixtures;
 
 import com.intellij.codeInsight.TargetElementUtil;
-import com.intellij.openapi.application.Result;
-import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.psi.*;
 import com.intellij.refactoring.inline.InlineConstantFieldProcessor;
@@ -27,6 +25,8 @@ import com.intellij.refactoring.inline.InlineParameterHandler;
 import com.intellij.refactoring.util.InlineUtil;
 import org.jetbrains.annotations.NotNull;
 
+import static com.intellij.testFramework.LightPlatformTestCase.getProject;
+
 
 public class JavaCodeInsightTestUtil {
   private static final int TARGET_FOR_INLINE_FLAGS =
@@ -37,70 +37,50 @@ public class JavaCodeInsightTestUtil {
   public static void doInlineLocalTest(@NotNull final CodeInsightTestFixture fixture,
                                        @NotNull final String before, @NotNull final String after) {
     fixture.configureByFile(before);
-    new WriteCommandAction(fixture.getProject()) {
-      @Override
-      protected void run(@NotNull final Result result) throws Throwable {
-        final Editor editor = fixture.getEditor();
-        final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
-        assert element instanceof PsiLocalVariable : element;
-        InlineLocalHandler.invoke(fixture.getProject(), editor, (PsiLocalVariable)element, null);
-      }
-    }.execute();
+    final Editor editor = fixture.getEditor();
+    final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
+    assert element instanceof PsiLocalVariable : element;
+    InlineLocalHandler.invoke(fixture.getProject(), editor, (PsiLocalVariable)element, null);
     fixture.checkResultByFile(after, false);
   }
 
   public static void doInlineParameterTest(@NotNull final CodeInsightTestFixture fixture,
                                            @NotNull final String before, @NotNull final String after) {
     fixture.configureByFile(before);
-    new WriteCommandAction(fixture.getProject()) {
-      @Override
-      protected void run(@NotNull final Result result) throws Throwable {
-        final Editor editor = fixture.getEditor();
-        final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
-        assert element instanceof PsiParameter : element;
-        new InlineParameterHandler().inlineElement(getProject(), editor, element);
-      }
-    }.execute();
+    final Editor editor = fixture.getEditor();
+    final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
+    assert element instanceof PsiParameter : element;
+    new InlineParameterHandler().inlineElement(getProject(), editor, element);
     fixture.checkResultByFile(after, false);
   }
 
   public static void doInlineMethodTest(@NotNull final CodeInsightTestFixture fixture,
                                         @NotNull final String before, @NotNull final String after) {
     fixture.configureByFile(before);
-    new WriteCommandAction(fixture.getProject()) {
-      @Override
-      protected void run(@NotNull final Result result) throws Throwable {
-        final Editor editor = fixture.getEditor();
-        final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
-        assert element instanceof PsiMethod : element;
+    final Editor editor = fixture.getEditor();
+    final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
+    assert element instanceof PsiMethod : element;
 
-        final PsiReference ref = fixture.getFile().findReferenceAt(editor.getCaretModel().getOffset());
-        final PsiReferenceExpression refExpr = ref instanceof PsiReferenceExpression ? (PsiReferenceExpression)ref : null;
+    final PsiReference ref = fixture.getFile().findReferenceAt(editor.getCaretModel().getOffset());
+    final PsiReferenceExpression refExpr = ref instanceof PsiReferenceExpression ? (PsiReferenceExpression)ref : null;
 
-        final PsiMethod method = (PsiMethod)element;
-        assert !(InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method)) : "Bad returns found";
-        new InlineMethodProcessor(getProject(), method, refExpr, editor, false).run();
-      }
-    }.execute();
+    final PsiMethod method = (PsiMethod)element;
+    assert !(InlineMethodProcessor.checkBadReturns(method) && !InlineUtil.allUsagesAreTailCalls(method)) : "Bad returns found";
+    new InlineMethodProcessor(getProject(), method, refExpr, editor, false).run();
     fixture.checkResultByFile(after, false);
   }
 
   public static void doInlineConstantTest(@NotNull final CodeInsightTestFixture fixture,
                                           @NotNull final String before, @NotNull final String after) {
     fixture.configureByFile(before);
-    new WriteCommandAction(fixture.getProject()) {
-      @Override
-      protected void run(@NotNull final Result result) throws Throwable {
-        final Editor editor = fixture.getEditor();
-        final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
-        assert element instanceof PsiField : element;
+    final Editor editor = fixture.getEditor();
+    final PsiElement element = TargetElementUtil.findTargetElement(editor, TARGET_FOR_INLINE_FLAGS);
+    assert element instanceof PsiField : element;
 
-        final PsiReference ref = fixture.getFile().findReferenceAt(editor.getCaretModel().getOffset());
-        final PsiReferenceExpression refExpr = ref instanceof PsiReferenceExpression ? (PsiReferenceExpression)ref : null;
+    final PsiReference ref = fixture.getFile().findReferenceAt(editor.getCaretModel().getOffset());
+    final PsiReferenceExpression refExpr = ref instanceof PsiReferenceExpression ? (PsiReferenceExpression)ref : null;
 
-        new InlineConstantFieldProcessor((PsiField)element, getProject(), refExpr, false).run();
-      }
-    }.execute();
+    new InlineConstantFieldProcessor((PsiField)element, getProject(), refExpr, false).run();
     fixture.checkResultByFile(after, false);
   }
 }
\ No newline at end of file
index d348a5e450b810738d6ea2f00310cb51f693f08b..165b1c41d7695bb190ba551f508d6088690e0e87 100644 (file)
@@ -23,10 +23,10 @@ import com.intellij.psi.*;
 import com.intellij.psi.impl.JavaPsiFacadeEx;
 import com.intellij.psi.impl.PsiModificationTrackerImpl;
 import com.intellij.psi.search.ProjectScope;
+import com.intellij.testFramework.EdtTestUtil;
 import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
 import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture;
 import com.intellij.testFramework.fixtures.TempDirTestFixture;
-import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.junit.Assert;
@@ -92,7 +92,7 @@ public class JavaCodeInsightTestFixtureImpl extends CodeInsightTestFixtureImpl i
   @Override
   public void tearDown() throws Exception {
     try {
-      UIUtil.invokeLaterIfNeeded(new Runnable() {
+      EdtTestUtil.runInEdtAndWait(new Runnable() {
         @Override
         public void run() {
           ((PsiModificationTrackerImpl)getPsiManager().getModificationTracker()).incCounter();// drop all caches
index cecdd12e411b586a816e0ce887b8a10e8d967dfd..bed7f6bf41a3bda6662c914af034c6199779db0b 100644 (file)
@@ -48,6 +48,8 @@ import org.jetbrains.jps.service.SharedThreadPool;
 
 import javax.tools.*;
 import java.io.File;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
 import java.util.*;
 import java.util.concurrent.TimeUnit;
 
@@ -96,8 +98,14 @@ public class ExternalJavacManager {
                                    compilationRequestsHandler);
       }
     });
-    myChannelRegistrar.add(bootstrap.bind(listenPort).syncUninterruptibly().channel());
-    myListenPort = listenPort;
+    try {
+      final InetAddress loopback = InetAddress.getByName(null);
+      myChannelRegistrar.add(bootstrap.bind(loopback, listenPort).syncUninterruptibly().channel());
+      myListenPort = listenPort;
+    }
+    catch (UnknownHostException e) {
+      throw new RuntimeException(e);
+    }
   }
   
 
index eee77c804894bcc50e3f428dbc61c3f1cf65d92e..736a0036d3f904c3d09ee21984467c7dad86f358 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2016 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -63,7 +63,7 @@ public class JpsGlobalElementSaver {
       return new Element("application");
     }
     try {
-      return JDOMUtil.loadDocument(configFile).getRootElement();
+      return JDOMUtil.load(configFile);
     }
     catch (JDOMException e) {
       throw new RuntimeException(e);
index 9825cb4ed5168722a93e32c4239495ddf591b0e2..88af24c3a2d86cab93aa6e14b709e5f946594ab5 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 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.
@@ -83,7 +83,7 @@