Search in sources :

Example 86 with MultiMap

use of com.intellij.util.containers.MultiMap in project intellij-community by JetBrains.

the class InspectionTree method getSelectedDescriptors.

@NotNull
public CommonProblemDescriptor[] getSelectedDescriptors(boolean sortedByPosition, @Nullable Set<VirtualFile> readOnlyFilesSink, boolean allowResolved, boolean allowSuppressed) {
    final TreePath[] paths = getSelectionPaths();
    if (paths == null)
        return CommonProblemDescriptor.EMPTY_ARRAY;
    final TreePath[] selectionPaths = TreeUtil.selectMaximals(paths);
    final List<CommonProblemDescriptor> descriptors = new ArrayList<>();
    MultiMap<Object, ProblemDescriptionNode> parentToChildNode = new MultiMap<>();
    final List<InspectionTreeNode> nonDescriptorNodes = new SmartList<>();
    for (TreePath path : selectionPaths) {
        final Object[] pathAsArray = path.getPath();
        final int length = pathAsArray.length;
        final Object node = pathAsArray[length - 1];
        if (node instanceof ProblemDescriptionNode) {
            if (isNodeValidAndIncluded((ProblemDescriptionNode) node, allowResolved, allowSuppressed)) {
                if (length >= 2) {
                    parentToChildNode.putValue(pathAsArray[length - 2], (ProblemDescriptionNode) node);
                } else {
                    parentToChildNode.putValue(node, (ProblemDescriptionNode) node);
                }
            }
        } else {
            nonDescriptorNodes.add((InspectionTreeNode) node);
        }
    }
    for (InspectionTreeNode node : nonDescriptorNodes) {
        processChildDescriptorsDeep(node, descriptors, sortedByPosition, allowResolved, allowSuppressed, readOnlyFilesSink);
    }
    for (Map.Entry<Object, Collection<ProblemDescriptionNode>> entry : parentToChildNode.entrySet()) {
        final Collection<ProblemDescriptionNode> siblings = entry.getValue();
        if (siblings.size() == 1) {
            final ProblemDescriptionNode descriptorNode = ContainerUtil.getFirstItem(siblings);
            LOG.assertTrue(descriptorNode != null);
            CommonProblemDescriptor descriptor = descriptorNode.getDescriptor();
            if (descriptor != null) {
                descriptors.add(descriptor);
                if (readOnlyFilesSink != null) {
                    collectReadOnlyFiles(descriptor, readOnlyFilesSink);
                }
            }
        } else {
            List<CommonProblemDescriptor> currentDescriptors = new ArrayList<>();
            for (ProblemDescriptionNode sibling : siblings) {
                final CommonProblemDescriptor descriptor = sibling.getDescriptor();
                if (descriptor != null) {
                    if (readOnlyFilesSink != null) {
                        collectReadOnlyFiles(descriptor, readOnlyFilesSink);
                    }
                    currentDescriptors.add(descriptor);
                }
            }
            if (sortedByPosition) {
                Collections.sort(currentDescriptors, DESCRIPTOR_COMPARATOR);
            }
            descriptors.addAll(currentDescriptors);
        }
    }
    return descriptors.toArray(new CommonProblemDescriptor[descriptors.size()]);
}
Also used : MultiMap(com.intellij.util.containers.MultiMap) TreePath(javax.swing.tree.TreePath) CommonProblemDescriptor(com.intellij.codeInspection.CommonProblemDescriptor) SmartList(com.intellij.util.SmartList) MultiMap(com.intellij.util.containers.MultiMap) NotNull(org.jetbrains.annotations.NotNull)

Example 87 with MultiMap

use of com.intellij.util.containers.MultiMap in project intellij-community by JetBrains.

the class StateQueue method getNextInstructionStates.

@NotNull
List<DfaInstructionState> getNextInstructionStates(Set<Instruction> joinInstructions) {
    DfaInstructionState state = myQueue.poll();
    final Instruction instruction = state.getInstruction();
    mySet.remove(Pair.create(instruction, state.getMemoryState()));
    DfaInstructionState next = myQueue.peek();
    if (next == null || next.compareTo(state) != 0)
        return Collections.singletonList(state);
    List<DfaMemoryStateImpl> memoryStates = ContainerUtil.newArrayList();
    memoryStates.add((DfaMemoryStateImpl) state.getMemoryState());
    while (!myQueue.isEmpty() && myQueue.peek().compareTo(state) == 0) {
        DfaMemoryState anotherState = myQueue.poll().getMemoryState();
        mySet.remove(Pair.create(instruction, anotherState));
        memoryStates.add((DfaMemoryStateImpl) anotherState);
    }
    if (memoryStates.size() > 1 && joinInstructions.contains(instruction)) {
        MultiMap<Object, DfaMemoryStateImpl> groups = MultiMap.create();
        for (DfaMemoryStateImpl memoryState : memoryStates) {
            groups.putValue(memoryState.getSuperficialKey(), memoryState);
        }
        memoryStates = ContainerUtil.newArrayList();
        for (Map.Entry<Object, Collection<DfaMemoryStateImpl>> entry : groups.entrySet()) {
            memoryStates.addAll(mergeGroup((List<DfaMemoryStateImpl>) entry.getValue()));
        }
    }
    return ContainerUtil.map(memoryStates, state1 -> new DfaInstructionState(instruction, state1));
}
Also used : Instruction(com.intellij.codeInspection.dataFlow.instructions.Instruction) MultiMap(com.intellij.util.containers.MultiMap) NotNull(org.jetbrains.annotations.NotNull)

Example 88 with MultiMap

use of com.intellij.util.containers.MultiMap in project intellij-community by JetBrains.

the class InlineMethodProcessor method preprocessUsages.

protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
    if (!myInlineThisOnly && checkReadOnly()) {
        if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myMethod))
            return false;
    }
    final UsageInfo[] usagesIn = refUsages.get();
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    if (!myInlineThisOnly) {
        final PsiMethod[] superMethods = myMethod.findSuperMethods();
        for (PsiMethod method : superMethods) {
            final String message = method.hasModifierProperty(PsiModifier.ABSTRACT) ? RefactoringBundle.message("inlined.method.implements.method.from.0", method.getContainingClass().getQualifiedName()) : RefactoringBundle.message("inlined.method.overrides.method.from.0", method.getContainingClass().getQualifiedName());
            conflicts.putValue(method, message);
        }
        for (UsageInfo info : usagesIn) {
            final PsiElement element = info.getElement();
            if (element instanceof PsiDocMethodOrFieldRef && !PsiTreeUtil.isAncestor(myMethod, element, false)) {
                conflicts.putValue(element, "Inlined method is used in javadoc");
            }
            if (element instanceof PsiMethodReferenceExpression) {
                final PsiExpression qualifierExpression = ((PsiMethodReferenceExpression) element).getQualifierExpression();
                if (qualifierExpression != null) {
                    final List<PsiElement> sideEffects = new ArrayList<>();
                    SideEffectChecker.checkSideEffects(qualifierExpression, sideEffects);
                    if (!sideEffects.isEmpty()) {
                        conflicts.putValue(element, "Inlined method is used in method reference with side effects in qualifier");
                    }
                }
            }
            final String errorMessage = checkCalledInSuperOrThisExpr(myMethod.getBody(), element);
            if (errorMessage != null) {
                conflicts.putValue(element, errorMessage);
            }
        }
    }
    ArrayList<PsiReference> refs = convertUsagesToRefs(usagesIn);
    myInliners = GenericInlineHandler.initializeInliners(myMethod, new InlineHandler.Settings() {

        @Override
        public boolean isOnlyOneReferenceToInline() {
            return myInlineThisOnly;
        }
    }, refs);
    //hack to prevent conflicts 'Cannot inline reference from Java'
    myInliners.put(JavaLanguage.INSTANCE, new InlineHandler.Inliner() {

        @Nullable
        @Override
        public MultiMap<PsiElement, String> getConflicts(PsiReference reference, PsiElement referenced) {
            return MultiMap.emptyInstance();
        }

        @Override
        public void inlineUsage(@NotNull UsageInfo usage, @NotNull PsiElement referenced) {
            if (usage instanceof NonCodeUsageInfo)
                return;
            throw new UnsupportedOperationException("usage: " + usage.getClass().getName() + ", usage element: " + usage.getElement() + ", referenced: " + referenced.getClass().getName() + ", text: " + referenced.getText());
        }
    });
    for (PsiReference ref : refs) {
        GenericInlineHandler.collectConflicts(ref, myMethod, myInliners, conflicts);
    }
    final PsiReturnStatement[] returnStatements = PsiUtil.findReturnStatements(myMethod);
    for (PsiReturnStatement statement : returnStatements) {
        PsiExpression value = statement.getReturnValue();
        if (value != null && !(value instanceof PsiCallExpression)) {
            for (UsageInfo info : usagesIn) {
                PsiReference reference = info.getReference();
                if (reference != null) {
                    InlineUtil.TailCallType type = InlineUtil.getTailCallType(reference);
                    if (type == InlineUtil.TailCallType.Simple) {
                        conflicts.putValue(statement, "Inlined result would contain parse errors");
                        break;
                    }
                }
            }
        }
    }
    addInaccessibleMemberConflicts(myMethod, usagesIn, new ReferencedElementsCollector(), conflicts);
    addInaccessibleSuperCallsConflicts(usagesIn, conflicts);
    return showConflicts(conflicts, usagesIn);
}
Also used : MultiMap(com.intellij.util.containers.MultiMap) UsageInfo(com.intellij.usageView.UsageInfo) InlineHandler(com.intellij.lang.refactoring.InlineHandler) PsiDocMethodOrFieldRef(com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef) Nullable(org.jetbrains.annotations.Nullable)

Example 89 with MultiMap

use of com.intellij.util.containers.MultiMap in project intellij-community by JetBrains.

the class ExtractClassProcessor method preprocessUsages.

@Override
protected boolean preprocessUsages(@NotNull final Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    myExtractEnumProcessor.findEnumConstantConflicts(refUsages);
    if (!DestinationFolderComboBox.isAccessible(myProject, sourceClass.getContainingFile().getVirtualFile(), myClass.getContainingFile().getContainingDirectory().getVirtualFile())) {
        conflicts.putValue(sourceClass, "Extracted class won't be accessible in " + RefactoringUIUtil.getDescription(sourceClass, true));
    }
    ApplicationManager.getApplication().runWriteAction(() -> myClass.delete());
    final Project project = sourceClass.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final PsiClass existingClass = JavaPsiFacade.getInstance(project).findClass(getQualifiedName(), scope);
    if (existingClass != null) {
        conflicts.putValue(existingClass, RefactorJBundle.message("cannot.perform.the.refactoring") + RefactorJBundle.message("there.already.exists.a.class.with.the.chosen.name"));
    }
    if (!myGenerateAccessors) {
        calculateInitializersConflicts(conflicts);
        final NecessaryAccessorsVisitor visitor = checkNecessaryGettersSetters4ExtractedClass();
        final NecessaryAccessorsVisitor srcVisitor = checkNecessaryGettersSetters4SourceClass();
        final Set<PsiField> fieldsNeedingGetter = new LinkedHashSet<>();
        fieldsNeedingGetter.addAll(visitor.getFieldsNeedingGetter());
        fieldsNeedingGetter.addAll(srcVisitor.getFieldsNeedingGetter());
        for (PsiField field : fieldsNeedingGetter) {
            conflicts.putValue(field, "Field \'" + field.getName() + "\' needs getter");
        }
        final Set<PsiField> fieldsNeedingSetter = new LinkedHashSet<>();
        fieldsNeedingSetter.addAll(visitor.getFieldsNeedingSetter());
        fieldsNeedingSetter.addAll(srcVisitor.getFieldsNeedingSetter());
        for (PsiField field : fieldsNeedingSetter) {
            conflicts.putValue(field, "Field \'" + field.getName() + "\' needs setter");
        }
    }
    checkConflicts(refUsages, conflicts);
    return showConflicts(conflicts, refUsages.get());
}
Also used : MultiMap(com.intellij.util.containers.MultiMap) Project(com.intellij.openapi.project.Project) GlobalSearchScope(com.intellij.psi.search.GlobalSearchScope)

Example 90 with MultiMap

use of com.intellij.util.containers.MultiMap in project intellij-community by JetBrains.

the class InheritanceToDelegationProcessor method preprocessUsages.

protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
    final UsageInfo[] usagesIn = refUsages.get();
    ArrayList<UsageInfo> oldUsages = new ArrayList<>();
    Collections.addAll(oldUsages, usagesIn);
    final ObjectUpcastedUsageInfo[] objectUpcastedUsageInfos = objectUpcastedUsages(usagesIn);
    if (myPrepareSuccessfulSwingThreadCallback != null) {
        MultiMap<PsiElement, String> conflicts = new MultiMap<>();
        if (objectUpcastedUsageInfos.length > 0) {
            final String message = RefactoringBundle.message("instances.of.0.upcasted.to.1.were.found", RefactoringUIUtil.getDescription(myClass, true), CommonRefactoringUtil.htmlEmphasize(CommonClassNames.JAVA_LANG_OBJECT));
            conflicts.putValue(myClass, message);
        }
        analyzeConflicts(usagesIn, conflicts);
        if (!conflicts.isEmpty()) {
            ConflictsDialog conflictsDialog = prepareConflictsDialog(conflicts, usagesIn);
            if (!conflictsDialog.showAndGet()) {
                if (conflictsDialog.isShowConflicts())
                    prepareSuccessful();
                return false;
            }
        }
        if (objectUpcastedUsageInfos.length > 0) {
            showObjectUpcastedUsageView(objectUpcastedUsageInfos);
            setPreviewUsages(true);
        }
    }
    ArrayList<UsageInfo> filteredUsages = filterUsages(oldUsages);
    refUsages.set(filteredUsages.toArray(new UsageInfo[filteredUsages.size()]));
    prepareSuccessful();
    return true;
}
Also used : MultiMap(com.intellij.util.containers.MultiMap) ConflictsDialog(com.intellij.refactoring.ui.ConflictsDialog) UsageInfo(com.intellij.usageView.UsageInfo)

Aggregations

MultiMap (com.intellij.util.containers.MultiMap)138 NotNull (org.jetbrains.annotations.NotNull)37 UsageInfo (com.intellij.usageView.UsageInfo)26 VirtualFile (com.intellij.openapi.vfs.VirtualFile)25 Project (com.intellij.openapi.project.Project)18 PsiElement (com.intellij.psi.PsiElement)18 ConflictsDialog (com.intellij.refactoring.ui.ConflictsDialog)16 Collection (java.util.Collection)16 Nullable (org.jetbrains.annotations.Nullable)15 Map (java.util.Map)14 File (java.io.File)11 HashSet (com.intellij.util.containers.HashSet)10 ContainerUtil (com.intellij.util.containers.ContainerUtil)9 THashSet (gnu.trove.THashSet)9 java.util (java.util)9 Module (com.intellij.openapi.module.Module)8 com.intellij.psi (com.intellij.psi)8 Pair (com.intellij.openapi.util.Pair)7 PsiFile (com.intellij.psi.PsiFile)7 ArrayList (java.util.ArrayList)7