コード例 #1
0
 @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;
 }
コード例 #2
0
 public static PsiReferenceExpression qualifyReference(
     PsiReferenceExpression referenceExpression,
     final PsiMember member,
     @Nullable final PsiClass qualifyingClass)
     throws IncorrectOperationException {
   PsiManager manager = referenceExpression.getManager();
   PsiMethodCallExpression methodCallExpression =
       PsiTreeUtil.getParentOfType(referenceExpression, PsiMethodCallExpression.class, true);
   while ((methodCallExpression) != null) {
     if (HighlightUtil.isSuperOrThisMethodCall(methodCallExpression)) {
       return referenceExpression;
     }
     methodCallExpression =
         PsiTreeUtil.getParentOfType(methodCallExpression, PsiMethodCallExpression.class, true);
   }
   PsiReferenceExpression expressionFromText;
   final PsiElementFactory factory =
       JavaPsiFacade.getInstance(manager.getProject()).getElementFactory();
   if (qualifyingClass == null) {
     PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
     final PsiClass containingClass = member.getContainingClass();
     if (parentClass != null
         && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
       while (parentClass != null
           && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
         parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
       }
       LOG.assertTrue(parentClass != null);
       expressionFromText =
           (PsiReferenceExpression)
               factory.createExpressionFromText("A.this." + member.getName(), null);
       ((PsiThisExpression) expressionFromText.getQualifierExpression())
           .getQualifier()
           .replace(factory.createClassReferenceElement(parentClass));
     } else {
       expressionFromText =
           (PsiReferenceExpression)
               factory.createExpressionFromText("this." + member.getName(), null);
     }
   } else {
     expressionFromText =
         (PsiReferenceExpression) factory.createExpressionFromText("A." + member.getName(), null);
     expressionFromText.setQualifierExpression(factory.createReferenceExpression(qualifyingClass));
   }
   CodeStyleManager codeStyleManager = manager.getCodeStyleManager();
   expressionFromText = (PsiReferenceExpression) codeStyleManager.reformat(expressionFromText);
   return (PsiReferenceExpression) referenceExpression.replace(expressionFromText);
 }
コード例 #3
0
ファイル: PropertyUtil.java プロジェクト: jexp/idea2
 @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;
 }
  @Override
  public InspectionGadgetsFix buildFix(Object... infos) {
    final PsiClass aClass = (PsiClass) infos[0];
    final String className = aClass.getName();
    if (infos.length == 1) {
      return new MakePackagePrivateFix(className, true);
    }
    final PsiMember member = (PsiMember) infos[1];
    @NonNls final String memberName;
    if (member instanceof PsiMethod) {
      final PsiMethod method = (PsiMethod) member;
      if (method.isConstructor()) {}

      memberName = member.getName() + "()";
    } else {
      memberName = member.getName();
    }
    @NonNls final String elementName = className + '.' + memberName;
    return new MakePackagePrivateFix(elementName, false);
  }
コード例 #5
0
  @Nullable
  public static String getMemberQualifiedName(PsiMember member) {
    if (member instanceof PsiClass) {
      return ((PsiClass) member).getQualifiedName();
    }

    PsiClass containingClass = member.getContainingClass();
    if (containingClass == null) return null;
    String className = containingClass.getQualifiedName();
    if (className == null) return null;
    return className + "." + member.getName();
  }
コード例 #6
0
 public static GrReferenceExpression qualifyReference(
     GrReferenceExpression referenceExpression,
     final PsiMember member,
     @Nullable final PsiClass qualifyingClass)
     throws IncorrectOperationException {
   PsiManager manager = referenceExpression.getManager();
   GrReferenceExpression expressionFromText;
   final GroovyPsiElementFactory factory =
       GroovyPsiElementFactory.getInstance(referenceExpression.getProject());
   if (qualifyingClass == null) {
     PsiClass parentClass = PsiTreeUtil.getParentOfType(referenceExpression, PsiClass.class);
     final PsiClass containingClass = member.getContainingClass();
     if (parentClass != null
         && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
       while (parentClass != null
           && !InheritanceUtil.isInheritorOrSelf(parentClass, containingClass, true)) {
         parentClass = PsiTreeUtil.getParentOfType(parentClass, PsiClass.class, true);
       }
       LOG.assertTrue(parentClass != null);
       expressionFromText =
           factory.createReferenceExpressionFromText("A.this." + member.getName());
       //noinspection ConstantConditions
       ((GrReferenceExpression) expressionFromText.getQualifier())
           .getQualifier()
           .replace(factory.createReferenceElementForClass(parentClass));
     } else {
       expressionFromText =
           (GrReferenceExpression) factory.createExpressionFromText("this." + member.getName());
     }
   } else {
     expressionFromText =
         (GrReferenceExpression) factory.createExpressionFromText("A." + member.getName());
     expressionFromText.setQualifier(factory.createReferenceElementForClass(qualifyingClass));
   }
   CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());
   expressionFromText = (GrReferenceExpression) codeStyleManager.reformat(expressionFromText);
   return (GrReferenceExpression) referenceExpression.replace(expressionFromText);
 }
コード例 #7
0
 private static void shortenWithStaticImports(
     PsiElement affectedElement, int startOffset, int endOffset) {
   final int elementOffset = affectedElement.getTextOffset();
   final int finalStartOffset = startOffset + elementOffset;
   final int finalEndOffset = endOffset + elementOffset;
   final List<PsiReferenceExpression> references = new ArrayList<PsiReferenceExpression>();
   final JavaRecursiveElementVisitor collector =
       new JavaRecursiveElementVisitor() {
         @Override
         public void visitReferenceExpression(PsiReferenceExpression expression) {
           final int offset = expression.getTextOffset();
           if (offset > finalEndOffset) {
             return;
           }
           super.visitReferenceExpression(expression);
           if (offset + expression.getTextLength() < finalStartOffset)
             if (expression.getQualifierExpression() == null) {
               return;
             }
           references.add(expression);
         }
       };
   affectedElement.accept(collector);
   for (PsiReferenceExpression expression : references) {
     final PsiElement target = expression.resolve();
     if (!(target instanceof PsiMember)) {
       continue;
     }
     final PsiMember member = (PsiMember) target;
     final PsiClass containingClass = member.getContainingClass();
     if (containingClass == null) {
       continue;
     }
     final String className = containingClass.getQualifiedName();
     if (className == null) {
       continue;
     }
     final String name = member.getName();
     if (name == null) {
       continue;
     }
     if (ImportUtils.addStaticImport(className, name, expression)) {
       final PsiExpression qualifierExpression = expression.getQualifierExpression();
       if (qualifierExpression != null) {
         qualifierExpression.delete();
       }
     }
   }
 }
コード例 #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;
 }
コード例 #9
0
  public void checkMemberPlacementInTargetClassConflict(
      final PsiClass targetClass, final PsiMember movedMember) {
    if (movedMember instanceof PsiField) {
      String name = movedMember.getName();
      final PsiField field = targetClass.findFieldByName(name, false);
      if (field != null) {
        String message =
            RefactoringBundle.message(
                "0.already.contains.field.1",
                RefactoringUIUtil.getDescription(targetClass, false),
                CommonRefactoringUtil.htmlEmphasize(name));
        myConflicts.putValue(field, CommonRefactoringUtil.capitalize(message));
      }
    } else if (movedMember instanceof PsiMethod) {
      /*
      final PsiModifierList modifierList = movedMember.getModifierList();
      assert modifierList != null;
      if (!modifierList.hasModifierProperty(PsiModifier.ABSTRACT)) {
        PsiMethod method = (PsiMethod)movedMember;
        final PsiMethod overrider = targetClass.findMethodBySignature(method, false);
        if (overrider != null) {
          String message = RefactoringBundle.message("0.is.already.overridden.in.1",
                                                     RefactoringUIUtil.getDescription(method, true), RefactoringUIUtil.getDescription(targetClass, false));
          myConflicts.putValue(overrider, CommonRefactoringUtil.capitalize(message));
        }
      }
      */
    } else if (movedMember instanceof PsiClass) {
      PsiClass aClass = (PsiClass) movedMember;
      final String name = aClass.getName();
      final PsiClass[] allInnerClasses = targetClass.getAllInnerClasses();
      for (PsiClass innerClass : allInnerClasses) {
        if (innerClass.equals(movedMember)) continue;

        if (name.equals(innerClass.getName())) {
          String message =
              RefactoringBundle.message(
                  "0.already.contains.inner.class.named.1",
                  RefactoringUIUtil.getDescription(targetClass, false),
                  CommonRefactoringUtil.htmlEmphasize(name));
          myConflicts.putValue(innerClass, message);
        }
      }
    }
  }
コード例 #10
0
 @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;
 }
コード例 #11
0
 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;
 }
コード例 #12
0
  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;
  }
コード例 #13
0
  @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;
    }
  }
コード例 #14
0
  private static void checkSuperclassMembers(
      PsiClass superClass,
      MemberInfoBase<? extends PsiMember>[] infos,
      MultiMap<PsiElement, String> conflictsList) {
    for (MemberInfoBase<? extends PsiMember> info : infos) {
      PsiMember member = info.getMember();
      boolean isConflict = false;
      if (member instanceof PsiField) {
        String name = member.getName();

        isConflict = superClass.findFieldByName(name, false) != null;
      } else if (member instanceof PsiMethod) {
        PsiSubstitutor superSubstitutor =
            TypeConversionUtil.getSuperClassSubstitutor(
                superClass, member.getContainingClass(), PsiSubstitutor.EMPTY);
        MethodSignature signature = ((PsiMethod) member).getSignature(superSubstitutor);
        final PsiMethod superClassMethod =
            MethodSignatureUtil.findMethodBySignature(superClass, signature, false);
        isConflict = superClassMethod != null;
      }

      if (isConflict) {
        String message =
            RefactoringBundle.message(
                "0.already.contains.a.1",
                RefactoringUIUtil.getDescription(superClass, false),
                RefactoringUIUtil.getDescription(member, false));
        message = CommonRefactoringUtil.capitalize(message);
        conflictsList.putValue(superClass, message);
      }

      if (member instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) member;
        final PsiModifierList modifierList = method.getModifierList();
        if (!modifierList.hasModifierProperty(PsiModifier.PRIVATE)) {
          for (PsiClass subClass : ClassInheritorsSearch.search(superClass)) {
            if (method.getContainingClass() != subClass) {
              MethodSignature signature =
                  ((PsiMethod) member)
                      .getSignature(
                          TypeConversionUtil.getSuperClassSubstitutor(
                              superClass, subClass, PsiSubstitutor.EMPTY));
              final PsiMethod wouldBeOverriden =
                  MethodSignatureUtil.findMethodBySignature(subClass, signature, false);
              if (wouldBeOverriden != null
                  && VisibilityUtil.compare(
                          VisibilityUtil.getVisibilityModifier(wouldBeOverriden.getModifierList()),
                          VisibilityUtil.getVisibilityModifier(modifierList))
                      > 0) {
                conflictsList.putValue(
                    wouldBeOverriden,
                    CommonRefactoringUtil.capitalize(
                        RefactoringUIUtil.getDescription(method, true)
                            + " in super class would clash with local method from "
                            + RefactoringUIUtil.getDescription(subClass, true)));
              }
            }
          }
        }
      }
    }
  }
コード例 #15
0
    private void checkMember(@NotNull final PsiMember member) {
      if (member.hasModifierProperty(PsiModifier.PRIVATE)
          || member.hasModifierProperty(PsiModifier.NATIVE)) return;
      if (member instanceof PsiMethod && member instanceof SyntheticElement || !member.isPhysical())
        return;

      if (member instanceof PsiMethod) {
        PsiMethod method = (PsiMethod) member;
        if (!method.getHierarchicalMethodSignature().getSuperSignatures().isEmpty()) {
          log(member.getName() + " overrides");
          return; // overrides
        }
        if (MethodUtils.isOverridden(method)) {
          log(member.getName() + " overridden");
          return;
        }
      }
      if (member instanceof PsiEnumConstant) return;
      if (member instanceof PsiClass
          && (member instanceof PsiAnonymousClass
              || member instanceof PsiTypeParameter
              || member instanceof PsiSyntheticClass
              || PsiUtil.isLocalClass((PsiClass) member))) {
        return;
      }
      final PsiClass memberClass = member.getContainingClass();
      if (memberClass != null
          && (memberClass.isInterface()
              || memberClass.isEnum()
              || memberClass.isAnnotationType()
              || PsiUtil.isLocalClass(memberClass) && member instanceof PsiClass)) {
        return;
      }
      final PsiFile memberFile = member.getContainingFile();
      Project project = memberFile.getProject();

      if (myDeadCodeInspection.isEntryPoint(member)) {
        log(member.getName() + " is entry point");
        return;
      }

      PsiModifierList memberModifierList = member.getModifierList();
      if (memberModifierList == null) return;
      final int currentLevel = PsiUtil.getAccessLevel(memberModifierList);
      final AtomicInteger maxLevel = new AtomicInteger(PsiUtil.ACCESS_LEVEL_PRIVATE);
      final AtomicBoolean foundUsage = new AtomicBoolean();
      PsiDirectory memberDirectory = memberFile.getContainingDirectory();
      final PsiPackage memberPackage =
          memberDirectory == null
              ? null
              : JavaDirectoryService.getInstance().getPackage(memberDirectory);
      log(member.getName() + ": checking effective level for " + member);
      boolean result =
          UnusedSymbolUtil.processUsages(
              project,
              memberFile,
              member,
              new EmptyProgressIndicator(),
              null,
              new Processor<UsageInfo>() {
                @Override
                public boolean process(UsageInfo info) {
                  foundUsage.set(true);
                  PsiFile psiFile = info.getFile();
                  if (psiFile == null) return true;
                  if (!(psiFile instanceof PsiJavaFile)) {
                    log("     refd from " + psiFile.getName() + "; set to public");
                    maxLevel.set(PsiUtil.ACCESS_LEVEL_PUBLIC);
                    if (memberClass != null) {
                      childMembersAreUsedOutsideMyPackage.add(memberClass);
                    }
                    return false; // referenced from XML, has to be public
                  }
                  // int offset = info.getNavigationOffset();
                  // if (offset == -1) return true;
                  PsiElement element = info.getElement();
                  if (element == null) return true;
                  @PsiUtil.AccessLevel
                  int level =
                      getEffectiveLevel(element, psiFile, memberFile, memberClass, memberPackage);
                  log(
                      "    ref in file "
                          + psiFile.getName()
                          + "; level = "
                          + PsiUtil.getAccessModifier(level)
                          + "; ("
                          + element
                          + ")");
                  while (true) {
                    int oldLevel = maxLevel.get();
                    if (level <= oldLevel || maxLevel.compareAndSet(oldLevel, level)) break;
                  }
                  if (level == PsiUtil.ACCESS_LEVEL_PUBLIC && memberClass != null) {
                    childMembersAreUsedOutsideMyPackage.add(memberClass);
                  }

                  return level != PsiUtil.ACCESS_LEVEL_PUBLIC;
                }
              });

      if (!foundUsage.get()) {
        log(member.getName() + " unused; ignore");
        return; // do not propose private for unused method
      }
      int max = maxLevel.get();
      if (max == PsiUtil.ACCESS_LEVEL_PRIVATE && memberClass == null) {
        max = PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL;
      }

      log(member.getName() + ": effective level is '" + PsiUtil.getAccessModifier(max) + "'");

      if (max < currentLevel) {
        if (max == PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL
            && member instanceof PsiClass
            && childMembersAreUsedOutsideMyPackage.contains(member)) {
          log(member.getName() + "  children used outside my package; ignore");
          return; // e.g. some public method is used outside my package (without importing class)
        }
        PsiElement toHighlight =
            currentLevel == PsiUtil.ACCESS_LEVEL_PACKAGE_LOCAL
                ? ((PsiNameIdentifierOwner) member).getNameIdentifier()
                : ContainerUtil.find(
                    memberModifierList.getChildren(),
                    new Condition<PsiElement>() {
                      @Override
                      public boolean value(PsiElement element) {
                        return element instanceof PsiKeyword
                            && element.getText().equals(PsiUtil.getAccessModifier(currentLevel));
                      }
                    });
        assert toHighlight != null
            : member
                + " ; "
                + ((PsiNameIdentifierOwner) member).getNameIdentifier()
                + "; "
                + memberModifierList.getText();
        myHolder.registerProblem(
            toHighlight,
            "Access can be " + PsiUtil.getAccessModifier(max),
            new ChangeModifierFix(PsiUtil.getAccessModifier(max)));
      }
    }