@Nullable
 private static String getCannotRefactorMessage(PsiMember member) {
   if (member == null) {
     return RefactoringBundle.message("locate.caret.inside.a.method");
   }
   if (member instanceof PsiMethod) {
     if (((PsiMethod) member).isConstructor()) {
       return RefactoringBundle.message("replace.with.method.call.does.not.work.for.constructors");
     }
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     if (body == null) {
       return RefactoringBundle.message("method.does.not.have.a.body", member.getName());
     }
     final PsiStatement[] statements = body.getStatements();
     if (statements.length == 0) {
       return RefactoringBundle.message("method.has.an.empty.body", member.getName());
     }
   } else if (member instanceof PsiField) {
     final PsiField field = (PsiField) member;
     if (field.getInitializer() == null) {
       return "Field " + member.getName() + " doesn't have initializer";
     }
     final PsiClass containingClass = field.getContainingClass();
     if (!field.hasModifierProperty(PsiModifier.FINAL)
         || !field.hasModifierProperty(PsiModifier.STATIC)
         || containingClass == null
         || containingClass.getQualifiedName() == null) {
       return "Replace Duplicates works with constants only";
     }
   } else {
     return "Caret should be inside method or constant";
   }
   return null;
 }
  private boolean isAccessible(final PsiElement element) {
    if (!myCheckAccess) return true;
    if (!(element instanceof PsiMember)) return true;

    PsiMember member = (PsiMember) element;
    return JavaPsiFacade.getInstance(element.getProject())
        .getResolveHelper()
        .isAccessible(
            member, member.getModifierList(), myElement, myQualifierClass, myDeclarationHolder);
  }
 @Override
 @NotNull
 protected UsageInfo[] findUsages() {
   final List<UsageInfo> result = new ArrayList<>();
   for (MemberInfo memberInfo : myMembersToMove) {
     final PsiMember member = memberInfo.getMember();
     if (member.hasModifierProperty(PsiModifier.STATIC)) {
       for (PsiReference reference : ReferencesSearch.search(member)) {
         result.add(new UsageInfo(reference));
       }
     }
   }
   return result.isEmpty() ? UsageInfo.EMPTY_ARRAY : result.toArray(new UsageInfo[result.size()]);
 }
  @NotNull
  @Override
  protected UsageInfo[] findUsages() {
    final List<UsageInfo> result = new ArrayList<UsageInfo>();
    for (GrMemberInfo info : myMembersToMove) {
      final PsiMember member = info.getMember();
      if (member.hasModifierProperty(PsiModifier.STATIC)) {
        for (PsiReference reference : ReferencesSearch.search(member)) {
          result.add(new UsageInfo(reference));
        }
      }
    }

    return DefaultGroovyMethods.asType(result, UsageInfo[].class);
  }
Esempio n. 5
0
 @Nullable
 public static String getPropertyName(final PsiMember member) {
   if (member instanceof PsiMethod) {
     return getPropertyName((PsiMethod) member);
   } else if (member instanceof PsiField) {
     return member.getName();
   } else return null;
 }
 protected void visitClassMemberReferenceElement(
     PsiMember classMember, PsiJavaCodeReferenceElement classMemberReference) {
   if (classMember.hasModifierProperty(PsiModifier.STATIC)) {
     if (!myMembersToMove.contains(classMember)
         && RefactoringHierarchyUtil.isMemberBetween(
             myTargetSuperClass, mySourceClass, classMember)) {
       myReferences.add(classMemberReference);
       myReferees.add(classMember);
       myRefereeClasses.add(classMember.getContainingClass());
     } else if (myMembersToMove.contains(classMember)
         || myMembersAfterMove.contains(classMember)) {
       myReferences.add(classMemberReference);
       myReferees.add(classMember);
       myRefereeClasses.add(myTargetSuperClass);
     }
   }
 }
Esempio n. 7
0
 @Override
 public void visitReferenceElement(PsiJavaCodeReferenceElement reference) {
   if (referenceFound) {
     return;
   }
   super.visitReferenceElement(reference);
   if (reference.isQualified()) {
     return;
   }
   final PsiElement target = reference.resolve();
   for (PsiMember member : members) {
     if (member.equals(target)) {
       referenceFound = true;
       return;
     }
   }
 }
Esempio n. 8
0
 public static boolean isStaticallyImported(
     @NotNull PsiMember member, @NotNull PsiElement context) {
   final PsiClass memberClass = member.getContainingClass();
   if (memberClass == null) {
     return false;
   }
   final PsiClass containingClass = PsiTreeUtil.getParentOfType(context, PsiClass.class);
   if (InheritanceUtil.isInheritorOrSelf(containingClass, memberClass, true)) {
     return false;
   }
   final PsiFile psiFile = context.getContainingFile();
   if (!(psiFile instanceof PsiJavaFile)) {
     return false;
   }
   final PsiJavaFile javaFile = (PsiJavaFile) psiFile;
   final PsiImportList importList = javaFile.getImportList();
   if (importList == null) {
     return false;
   }
   final String memberName = member.getName();
   if (memberName == null) {
     return false;
   }
   final PsiImportStatementBase existingImportStatement =
       importList.findSingleImportStatement(memberName);
   if (existingImportStatement instanceof PsiImportStaticStatement) {
     final PsiClass importClass =
         ((PsiImportStaticStatement) existingImportStatement).resolveTargetClass();
     if (InheritanceUtil.isInheritorOrSelf(importClass, memberClass, true)) {
       return true;
     }
   }
   final String memberClassName = memberClass.getQualifiedName();
   if (memberClassName == null) {
     return false;
   }
   final PsiImportStaticStatement onDemandImportStatement =
       findOnDemandImportStaticStatement(importList, memberClassName);
   if (onDemandImportStatement != null) {
     if (!hasOnDemandImportStaticConflict(memberClassName, memberName, context)) {
       return true;
     }
   }
   return false;
 }
 @NotNull
 private static Map<String, List<Pair<PsiMember, PsiSubstitutor>>> generateMapByList(
     @NotNull final List<Pair<PsiMember, PsiSubstitutor>> list) {
   Map<String, List<Pair<PsiMember, PsiSubstitutor>>> map =
       new THashMap<String, List<Pair<PsiMember, PsiSubstitutor>>>();
   map.put(ALL, list);
   for (final Pair<PsiMember, PsiSubstitutor> info : list) {
     PsiMember element = info.getFirst();
     String currentName = element.getName();
     List<Pair<PsiMember, PsiSubstitutor>> listByName = map.get(currentName);
     if (listByName == null) {
       listByName = new ArrayList<Pair<PsiMember, PsiSubstitutor>>(1);
       map.put(currentName, listByName);
     }
     listByName.add(info);
   }
   return map;
 }
  public static boolean isInExcludedPackage(
      @NotNull final PsiMember member, boolean allowInstanceInnerClasses) {
    final String name = PsiUtil.getMemberQualifiedName(member);
    if (name == null) return false;

    if (!member.hasModifierProperty(PsiModifier.STATIC)) {
      if (member instanceof PsiMethod || member instanceof PsiField) {
        return false;
      }
      if (allowInstanceInnerClasses
          && member instanceof PsiClass
          && member.getContainingClass() != null) {
        return false;
      }
    }

    return ProjectCodeInsightSettings.getSettings(member.getProject()).isExcluded(name);
  }
  private static boolean processInstanceMember(
      boolean shouldProcessInstance, @NotNull PsiMember member) {
    if (shouldProcessInstance) return true;

    if (member instanceof GrReflectedMethod) {
      return ((GrReflectedMethod) member).getBaseMethod().hasModifierProperty(PsiModifier.STATIC);
    } else {
      return member.hasModifierProperty(PsiModifier.STATIC);
    }
  }
 public static Set<String> getAllLookupStrings(@NotNull PsiMember member) {
   Set<String> allLookupStrings = ContainerUtil.newLinkedHashSet();
   String name = member.getName();
   allLookupStrings.add(name);
   PsiClass containingClass = member.getContainingClass();
   while (containingClass != null) {
     final String className = containingClass.getName();
     if (className == null) {
       break;
     }
     name = className + "." + name;
     allLookupStrings.add(name);
     final PsiElement parent = containingClass.getParent();
     if (!(parent instanceof PsiClass)) {
       break;
     }
     containingClass = (PsiClass) parent;
   }
   return allLookupStrings;
 }
Esempio n. 13
0
 @Nullable
 public static PsiField findPropertyFieldByMember(final PsiMember psiMember) {
   if (psiMember instanceof PsiField) {
     return (PsiField) psiMember;
   } else if (psiMember instanceof PsiMethod) {
     final PsiMethod psiMethod = (PsiMethod) psiMember;
     final PsiType returnType = psiMethod.getReturnType();
     if (returnType == null) return null;
     final PsiCodeBlock body = psiMethod.getBody();
     final PsiStatement[] statements = body == null ? null : body.getStatements();
     final PsiStatement statement =
         statements == null || statements.length != 1 ? null : statements[0];
     final PsiElement target;
     if (PsiType.VOID.equals(returnType)) {
       final PsiExpression expression =
           statement instanceof PsiExpressionStatement
               ? ((PsiExpressionStatement) statement).getExpression()
               : null;
       target =
           expression instanceof PsiAssignmentExpression
               ? ((PsiAssignmentExpression) expression).getLExpression()
               : null;
     } else {
       target =
           statement instanceof PsiReturnStatement
               ? ((PsiReturnStatement) statement).getReturnValue()
               : null;
     }
     final PsiElement resolved =
         target instanceof PsiReferenceExpression
             ? ((PsiReferenceExpression) target).resolve()
             : null;
     if (resolved instanceof PsiField) {
       final PsiField field = (PsiField) resolved;
       if (psiMember.getContainingClass() == field.getContainingClass()
           || psiMember.getContainingClass().isInheritor(field.getContainingClass(), true))
         return field;
     }
   }
   return null;
 }
  private static void qualify(PsiMember member, PsiElement renamed, String name) {
    if (!(renamed instanceof GrReferenceExpression)) return;

    final PsiClass clazz = member.getContainingClass();
    if (clazz == null) return;

    final GrReferenceExpression refExpr = (GrReferenceExpression) renamed;
    final PsiElement replaced;
    if (member.hasModifierProperty(GrModifier.STATIC)) {
      final GrReferenceExpression newRefExpr =
          GroovyPsiElementFactory.getInstance(member.getProject())
              .createReferenceExpressionFromText(clazz.getQualifiedName() + "." + name);
      replaced = refExpr.replace(newRefExpr);
    } else {
      final PsiClass containingClass = PsiTreeUtil.getParentOfType(renamed, PsiClass.class);
      if (member.getManager().areElementsEquivalent(containingClass, clazz)) {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText("this." + name);
        replaced = refExpr.replace(newRefExpr);
      } else {
        final GrReferenceExpression newRefExpr =
            GroovyPsiElementFactory.getInstance(member.getProject())
                .createReferenceExpressionFromText(clazz.getQualifiedName() + ".this." + name);
        replaced = refExpr.replace(newRefExpr);
      }
    }
    PsiUtil.shortenReferences((GroovyPsiElement) replaced);
  }
  private void processMethodsDuplicates() {
    ProgressManager.getInstance()
        .runProcessWithProgressSynchronously(
            () ->
                ApplicationManager.getApplication()
                    .runReadAction(
                        () -> {
                          if (!myTargetSuperClass.isValid()) return;
                          final Query<PsiClass> search =
                              ClassInheritorsSearch.search(myTargetSuperClass);
                          final Set<VirtualFile> hierarchyFiles = new HashSet<>();
                          for (PsiClass aClass : search) {
                            final PsiFile containingFile = aClass.getContainingFile();
                            if (containingFile != null) {
                              final VirtualFile virtualFile = containingFile.getVirtualFile();
                              if (virtualFile != null) {
                                hierarchyFiles.add(virtualFile);
                              }
                            }
                          }
                          final Set<PsiMember> methodsToSearchDuplicates = new HashSet<>();
                          for (PsiMember psiMember : myMembersAfterMove) {
                            if (psiMember instanceof PsiMethod
                                && psiMember.isValid()
                                && ((PsiMethod) psiMember).getBody() != null) {
                              methodsToSearchDuplicates.add(psiMember);
                            }
                          }

                          MethodDuplicatesHandler.invokeOnScope(
                              myProject,
                              methodsToSearchDuplicates,
                              new AnalysisScope(myProject, hierarchyFiles),
                              true);
                        }),
            MethodDuplicatesHandler.REFACTORING_NAME,
            true,
            myProject);
  }
  @NotNull
  private static List<PsiMember> findByMap(
      @NotNull PsiClass aClass, String name, boolean checkBases, @NotNull MemberType type) {
    if (name == null) return Collections.emptyList();

    if (checkBases) {
      Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allMethodsMap = getMap(aClass, type);
      List<Pair<PsiMember, PsiSubstitutor>> list = allMethodsMap.get(name);
      if (list == null) return Collections.emptyList();
      List<PsiMember> ret = new ArrayList<PsiMember>(list.size());
      for (final Pair<PsiMember, PsiSubstitutor> info : list) {
        ret.add(info.getFirst());
      }

      return ret;
    } else {
      PsiMember[] members = null;
      switch (type) {
        case METHOD:
          members = aClass.getMethods();
          break;
        case CLASS:
          members = aClass.getInnerClasses();
          break;
        case FIELD:
          members = aClass.getFields();
          break;
      }

      List<PsiMember> list = new ArrayList<PsiMember>();
      for (PsiMember member : members) {
        if (name.equals(member.getName())) {
          list.add(member);
        }
      }
      return list;
    }
  }
  @Override
  public GrReferenceExpression bindToElementViaStaticImport(@NotNull PsiMember member) {
    if (getQualifier() != null) {
      throw new IncorrectOperationException("Reference has qualifier");
    }

    if (StringUtil.isEmpty(getReferenceName())) {
      throw new IncorrectOperationException("Reference has empty name");
    }

    PsiClass containingClass = member.getContainingClass();
    if (containingClass == null) {
      throw new IncorrectOperationException("Member has no containing class");
    }
    final PsiFile file = getContainingFile();
    if (file instanceof GroovyFile) {
      GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(getProject());
      String text = "import static " + containingClass.getQualifiedName() + "." + member.getName();
      final GrImportStatement statement = factory.createImportStatementFromText(text);
      ((GroovyFile) file).addImport(statement);
    }
    return this;
  }
 @Nullable
 public static DuplicatesFinder createDuplicatesFinder(PsiMember member) {
   PsiElement[] pattern;
   ReturnValue matchedReturnValue = null;
   if (member instanceof PsiMethod) {
     final PsiCodeBlock body = ((PsiMethod) member).getBody();
     LOG.assertTrue(body != null);
     final PsiStatement[] statements = body.getStatements();
     pattern = statements;
     matchedReturnValue = null;
     if (statements.length != 1 || !(statements[0] instanceof PsiReturnStatement)) {
       final PsiStatement lastStatement =
           statements.length > 0 ? statements[statements.length - 1] : null;
       if (lastStatement instanceof PsiReturnStatement) {
         final PsiExpression returnValue = ((PsiReturnStatement) lastStatement).getReturnValue();
         if (returnValue instanceof PsiReferenceExpression) {
           final PsiElement resolved = ((PsiReferenceExpression) returnValue).resolve();
           if (resolved instanceof PsiVariable) {
             pattern = new PsiElement[statements.length - 1];
             System.arraycopy(statements, 0, pattern, 0, statements.length - 1);
             matchedReturnValue = new VariableReturnValue((PsiVariable) resolved);
           }
         }
       }
     } else {
       final PsiExpression returnValue = ((PsiReturnStatement) statements[0]).getReturnValue();
       if (returnValue != null) {
         pattern = new PsiElement[] {returnValue};
       }
     }
   } else {
     pattern = new PsiElement[] {((PsiField) member).getInitializer()};
   }
   if (pattern.length == 0) {
     return null;
   }
   final List<? extends PsiVariable> inputVariables =
       member instanceof PsiMethod
           ? Arrays.asList(((PsiMethod) member).getParameterList().getParameters())
           : new ArrayList<>();
   return new DuplicatesFinder(
       pattern,
       new InputVariables(
           inputVariables, member.getProject(), new LocalSearchScope(pattern), false),
       matchedReturnValue,
       new ArrayList<>());
 }
  @Nullable
  public static PsiType getQualifiedMemberReferenceType(
      @Nullable PsiType qualifierType, @NotNull final PsiMember member) {
    final Ref<PsiSubstitutor> subst = Ref.create(PsiSubstitutor.EMPTY);
    class MyProcessor extends BaseScopeProcessor implements NameHint, ElementClassHint {
      @Override
      public boolean execute(@NotNull PsiElement element, @NotNull ResolveState state) {
        if (element == member) {
          subst.set(state.get(PsiSubstitutor.KEY));
        }
        return true;
      }

      @Override
      public String getName(@NotNull ResolveState state) {
        return member.getName();
      }

      @Override
      public boolean shouldProcess(DeclarationKind kind) {
        return member instanceof PsiEnumConstant
            ? kind == DeclarationKind.ENUM_CONST
            : member instanceof PsiField
                ? kind == DeclarationKind.FIELD
                : kind == DeclarationKind.METHOD;
      }

      @Override
      public <T> T getHint(@NotNull Key<T> hintKey) {
        return hintKey == NameHint.KEY || hintKey == ElementClassHint.KEY ? (T) this : null;
      }
    }

    PsiScopesUtil.processTypeDeclarations(qualifierType, member, new MyProcessor());

    PsiType rawType =
        member instanceof PsiField
            ? ((PsiField) member).getType()
            : member instanceof PsiMethod
                ? ((PsiMethod) member).getReturnType()
                : JavaPsiFacade.getElementFactory(member.getProject())
                    .createType((PsiClass) member);
    return subst.get().substitute(rawType);
  }
  private static boolean processCachedMembersByName(
      @NotNull PsiClass aClass,
      @NotNull PsiScopeProcessor processor,
      @NotNull ResolveState state,
      @Nullable Set<PsiClass> visited,
      PsiElement last,
      @NotNull PsiElement place,
      boolean isRaw,
      @NotNull PsiSubstitutor substitutor,
      @NotNull MembersMap value,
      String name,
      @NotNull LanguageLevel languageLevel) {
    final ElementClassHint classHint = processor.getHint(ElementClassHint.KEY);

    PsiElementFactory factory = JavaPsiFacade.getInstance(aClass.getProject()).getElementFactory();

    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.FIELD)) {
      final PsiField fieldByName = aClass.findFieldByName(name, false);
      if (fieldByName != null) {
        processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
        if (!processor.execute(fieldByName, state)) return false;
      } else {
        final Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allFieldsMap =
            value.get(MemberType.FIELD);

        final List<Pair<PsiMember, PsiSubstitutor>> list = allFieldsMap.get(name);
        if (list != null) {
          for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
            PsiMember candidateField = candidate.getFirst();
            PsiSubstitutor finalSubstitutor =
                obtainFinalSubstitutor(
                    candidateField.getContainingClass(),
                    candidate.getSecond(),
                    aClass,
                    substitutor,
                    factory,
                    languageLevel);

            processor.handleEvent(
                PsiScopeProcessor.Event.SET_DECLARATION_HOLDER,
                candidateField.getContainingClass());
            if (!processor.execute(candidateField, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
              return false;
          }
        }
      }
    }
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.CLASS)) {
      if (last != null && last.getParent() == aClass) {
        if (last instanceof PsiClass) {
          if (!processor.execute(last, state)) return false;
        }
        // Parameters
        final PsiTypeParameterList list = aClass.getTypeParameterList();
        if (list != null && !list.processDeclarations(processor, state, last, place)) return false;
      }
      if (!(last instanceof PsiReferenceList)) {
        final PsiClass classByName = aClass.findInnerClassByName(name, false);
        if (classByName != null) {
          processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
          if (!processor.execute(classByName, state)) return false;
        } else {
          Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allClassesMap =
              value.get(MemberType.CLASS);

          List<Pair<PsiMember, PsiSubstitutor>> list = allClassesMap.get(name);
          if (list != null) {
            for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
              PsiMember inner = candidate.getFirst();
              PsiClass containingClass = inner.getContainingClass();
              if (containingClass != null) {
                PsiSubstitutor finalSubstitutor =
                    obtainFinalSubstitutor(
                        containingClass,
                        candidate.getSecond(),
                        aClass,
                        substitutor,
                        factory,
                        languageLevel);
                processor.handleEvent(
                    PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, containingClass);
                if (!processor.execute(inner, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
                  return false;
              }
            }
          }
        }
      }
    }
    if (classHint == null || classHint.shouldProcess(ElementClassHint.DeclarationKind.METHOD)) {
      if (processor instanceof MethodResolverProcessor) {
        final MethodResolverProcessor methodResolverProcessor = (MethodResolverProcessor) processor;
        if (methodResolverProcessor.isConstructor()) {
          final PsiMethod[] constructors = aClass.getConstructors();
          methodResolverProcessor.handleEvent(
              PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, aClass);
          for (PsiMethod constructor : constructors) {
            if (!methodResolverProcessor.execute(constructor, state)) return false;
          }
          return true;
        }
      }
      Map<String, List<Pair<PsiMember, PsiSubstitutor>>> allMethodsMap =
          value.get(MemberType.METHOD);
      List<Pair<PsiMember, PsiSubstitutor>> list = allMethodsMap.get(name);
      if (list != null) {
        for (final Pair<PsiMember, PsiSubstitutor> candidate : list) {
          ProgressIndicatorProvider.checkCanceled();
          PsiMethod candidateMethod = (PsiMethod) candidate.getFirst();
          if (processor instanceof MethodResolverProcessor) {
            if (candidateMethod.isConstructor()
                != ((MethodResolverProcessor) processor).isConstructor()) continue;
          }
          final PsiClass containingClass = candidateMethod.getContainingClass();
          if (visited != null && visited.contains(candidateMethod.getContainingClass())) {
            continue;
          }

          PsiSubstitutor finalSubstitutor =
              obtainFinalSubstitutor(
                  containingClass,
                  candidate.getSecond(),
                  aClass,
                  substitutor,
                  factory,
                  languageLevel);
          finalSubstitutor = checkRaw(isRaw, factory, candidateMethod, finalSubstitutor);
          processor.handleEvent(PsiScopeProcessor.Event.SET_DECLARATION_HOLDER, containingClass);
          if (!processor.execute(candidateMethod, state.put(PsiSubstitutor.KEY, finalSubstitutor)))
            return false;
        }

        if (visited != null) {
          for (Pair<PsiMember, PsiSubstitutor> aList : list) {
            visited.add(aList.getFirst().getContainingClass());
          }
        }
      }
    }
    return true;
  }
  public CommonProblemDescriptor[] checkElement(
      @NotNull final PsiElement psiElement, InspectionManager manager, Project project) {
    final Map<PsiElement, Collection<String>> suppressedScopes =
        new THashMap<PsiElement, Collection<String>>();
    psiElement.accept(
        new JavaRecursiveElementWalkingVisitor() {
          @Override
          public void visitModifierList(PsiModifierList list) {
            super.visitModifierList(list);
            final PsiElement parent = list.getParent();
            if (parent instanceof PsiModifierListOwner && !(parent instanceof PsiClass)) {
              checkElement(parent);
            }
          }

          @Override
          public void visitComment(PsiComment comment) {
            checkElement(comment);
          }

          @Override
          public void visitClass(PsiClass aClass) {
            if (aClass == psiElement) {
              super.visitClass(aClass);
              checkElement(aClass);
            }
          }

          private void checkElement(final PsiElement owner) {
            String idsString = SuppressManager.getInstance().getSuppressedInspectionIdsIn(owner);
            if (idsString != null && idsString.length() != 0) {
              List<String> ids = StringUtil.split(idsString, ",");
              if (IGNORE_ALL
                  && (ids.contains(SuppressionUtil.ALL)
                      || ids.contains(SuppressionUtil.ALL.toLowerCase()))) return;
              Collection<String> suppressed = suppressedScopes.get(owner);
              if (suppressed == null) {
                suppressed = ids;
              } else {
                for (String id : ids) {
                  if (!suppressed.contains(id)) {
                    suppressed.add(id);
                  }
                }
              }
              suppressedScopes.put(owner, suppressed);
            }
          }
        });

    if (suppressedScopes.values().isEmpty()) return null;
    // have to visit all file from scratch since inspections can be written in any perversive way
    // including checkFile() overriding
    Collection<InspectionTool> suppressedTools = new THashSet<InspectionTool>();
    InspectionTool[] tools = getInspectionTools(psiElement, manager);
    for (Collection<String> ids : suppressedScopes.values()) {
      for (Iterator<String> iterator = ids.iterator(); iterator.hasNext(); ) {
        final String shortName = iterator.next().trim();
        for (InspectionTool tool : tools) {
          if (tool instanceof LocalInspectionToolWrapper
              && ((LocalInspectionToolWrapper) tool).getTool().getID().equals(shortName)) {
            if (!((LocalInspectionToolWrapper) tool).isUnfair()) {
              suppressedTools.add(tool);
            } else {
              iterator.remove();
              break;
            }
          } else if (tool.getShortName().equals(shortName)) {
            // ignore global unused as it won't be checked anyway
            if (!(tool instanceof LocalInspectionToolWrapper)
                && !(tool instanceof GlobalInspectionToolWrapper)) {
              iterator.remove();
              break;
            } else {
              suppressedTools.add(tool);
            }
          }
        }
      }
    }

    final AnalysisScope scope = new AnalysisScope(psiElement.getContainingFile());
    final InspectionManagerEx inspectionManagerEx =
        ((InspectionManagerEx) InspectionManager.getInstance(project));
    GlobalInspectionContextImpl globalContext = inspectionManagerEx.createNewGlobalContext(false);
    globalContext.setCurrentScope(scope);
    final RefManagerImpl refManager = ((RefManagerImpl) globalContext.getRefManager());
    refManager.inspectionReadActionStarted();
    final List<ProblemDescriptor> result;
    try {
      result = new ArrayList<ProblemDescriptor>();
      for (InspectionTool tool : suppressedTools) {
        String toolId =
            tool instanceof LocalInspectionToolWrapper
                ? ((LocalInspectionToolWrapper) tool).getTool().getID()
                : tool.getShortName();
        tool.initialize(globalContext);
        Collection<CommonProblemDescriptor> descriptors;
        if (tool instanceof LocalInspectionToolWrapper) {
          LocalInspectionToolWrapper local = (LocalInspectionToolWrapper) tool;
          if (local.isUnfair()) continue; // cant't work with passes other than LocalInspectionPass
          local.processFile(psiElement.getContainingFile(), false, manager);
          descriptors = local.getProblemDescriptors();
        } else if (tool instanceof GlobalInspectionToolWrapper) {
          GlobalInspectionToolWrapper global = (GlobalInspectionToolWrapper) tool;
          if (global.getTool().isGraphNeeded()) {
            refManager.findAllDeclarations();
          }
          global.processFile(scope, manager, globalContext, false);
          descriptors = global.getProblemDescriptors();
        } else {
          continue;
        }
        for (PsiElement suppressedScope : suppressedScopes.keySet()) {
          Collection<String> suppressedIds = suppressedScopes.get(suppressedScope);
          if (!suppressedIds.contains(toolId)) continue;
          for (CommonProblemDescriptor descriptor : descriptors) {
            if (!(descriptor instanceof ProblemDescriptor)) continue;
            PsiElement element = ((ProblemDescriptor) descriptor).getPsiElement();
            if (element == null) continue;
            PsiElement annotation =
                SuppressManager.getInstance().getElementToolSuppressedIn(element, toolId);
            if (annotation != null && PsiTreeUtil.isAncestor(suppressedScope, annotation, false)
                || annotation == null && !PsiTreeUtil.isAncestor(suppressedScope, element, false)) {
              suppressedIds.remove(toolId);
              break;
            }
          }
        }
      }
      for (PsiElement suppressedScope : suppressedScopes.keySet()) {
        Collection<String> suppressedIds = suppressedScopes.get(suppressedScope);
        for (String toolId : suppressedIds) {
          PsiMember psiMember;
          String problemLine = null;
          if (suppressedScope instanceof PsiMember) {
            psiMember = (PsiMember) suppressedScope;
          } else {
            psiMember = PsiTreeUtil.getParentOfType(suppressedScope, PsiDocCommentOwner.class);
            final PsiStatement statement =
                PsiTreeUtil.getNextSiblingOfType(suppressedScope, PsiStatement.class);
            problemLine = statement != null ? statement.getText() : null;
          }
          if (psiMember != null && psiMember.isValid()) {
            String description =
                InspectionsBundle.message("inspection.redundant.suppression.description");
            if (myQuickFixes == null) myQuickFixes = new BidirectionalMap<String, QuickFix>();
            final String key = toolId + (problemLine != null ? ";" + problemLine : "");
            QuickFix fix = myQuickFixes.get(key);
            if (fix == null) {
              fix = new RemoveSuppressWarningAction(toolId, problemLine);
              myQuickFixes.put(key, fix);
            }
            PsiElement identifier = null;
            if (psiMember instanceof PsiMethod) {
              identifier = ((PsiMethod) psiMember).getNameIdentifier();
            } else if (psiMember instanceof PsiField) {
              identifier = ((PsiField) psiMember).getNameIdentifier();
            } else if (psiMember instanceof PsiClass) {
              identifier = ((PsiClass) psiMember).getNameIdentifier();
            }
            if (identifier == null) {
              identifier = psiMember;
            }
            result.add(
                manager.createProblemDescriptor(
                    identifier,
                    description,
                    (LocalQuickFix) fix,
                    ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
                    false));
          }
        }
      }
    } finally {
      refManager.inspectionReadActionFinished();
      globalContext.close(true);
    }
    return result.toArray(new ProblemDescriptor[result.size()]);
  }