private static boolean canBePrivate(
      PsiMethod method,
      Collection<PsiReference> references,
      Collection<? extends PsiElement> deleted,
      final PsiElement[] allElementsToDelete) {
    final PsiClass containingClass = method.getContainingClass();
    if (containingClass == null) {
      return false;
    }

    PsiManager manager = method.getManager();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(manager.getProject());
    final PsiElementFactory factory = facade.getElementFactory();
    final PsiModifierList privateModifierList;
    try {
      final PsiMethod newMethod = factory.createMethod("x3", PsiType.VOID);
      privateModifierList = newMethod.getModifierList();
      privateModifierList.setModifierProperty(PsiModifier.PRIVATE, true);
    } catch (IncorrectOperationException e) {
      LOG.assertTrue(false);
      return false;
    }
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete)
          && !isInside(element, deleted)
          && !facade
              .getResolveHelper()
              .isAccessible(method, privateModifierList, element, null, null)) {
        return false;
      }
    }
    return true;
  }
  private void findUsagesForMethod(PsiMethod method, List<FixableUsageInfo> usages) {
    final PsiManager psiManager = method.getManager();
    final Project project = psiManager.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope);
    for (PsiReference reference : calls) {
      final PsiElement referenceElement = reference.getElement();
      final PsiElement parent = referenceElement.getParent();
      if (parent instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression call = (PsiMethodCallExpression) parent;
        if (isInMovedElement(call)) {
          continue;
        }
        final PsiReferenceExpression methodExpression = call.getMethodExpression();
        final PsiExpression qualifier = methodExpression.getQualifierExpression();
        if (qualifier == null || qualifier instanceof PsiThisExpression) {
          usages.add(new ReplaceThisCallWithDelegateCall(call, delegateFieldName));
        }
        delegationRequired = true;
      }
    }

    if (!delegationRequired && MethodInheritanceUtils.hasSiblingMethods(method)) {
      delegationRequired = true;
    }

    if (delegationRequired) {
      usages.add(new MakeMethodDelegate(method, delegateFieldName));
    } else {
      usages.add(new RemoveMethod(method));
    }
  }
  private void findUsagesForStaticMethod(PsiMethod method, List<FixableUsageInfo> usages) {
    final PsiManager psiManager = method.getManager();
    final Project project = psiManager.getProject();
    final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
    final Iterable<PsiReference> calls = ReferencesSearch.search(method, scope);
    final String fullyQualifiedName = getQualifiedName();
    for (PsiReference reference : calls) {
      final PsiElement referenceElement = reference.getElement();

      final PsiElement parent = referenceElement.getParent();
      if (parent instanceof PsiMethodCallExpression) {
        final PsiMethodCallExpression call = (PsiMethodCallExpression) parent;
        if (!isInMovedElement(call)) {
          usages.add(new RetargetStaticMethodCall(call, fullyQualifiedName));
        }
      } else if (parent instanceof PsiImportStaticStatement) {
        final PsiJavaCodeReferenceElement importReference =
            ((PsiImportStaticStatement) parent).getImportReference();
        if (importReference != null) {
          final PsiElement qualifier = importReference.getQualifier();
          if (qualifier instanceof PsiJavaCodeReferenceElement) {
            usages.add(
                new ReplaceClassReference(
                    (PsiJavaCodeReferenceElement) qualifier, fullyQualifiedName));
          }
        }
      }
    }
    usages.add(new RemoveMethod(method));
  }
Example #4
0
 @Nullable
 public static String getReferencePrefix(@NotNull PsiElement insertedElement, int offsetInFile) {
   final PsiReference ref = insertedElement.getContainingFile().findReferenceAt(offsetInFile);
   if (ref != null) {
     final PsiElement element = ref.getElement();
     final int endIndex = offsetInFile - element.getTextRange().getStartOffset();
     final int beginIndex = ref.getRangeInElement().getStartOffset();
     if (beginIndex > endIndex) {
       LOG.error(
           "Inconsistent reference (found at offset not included in its range): ref="
               + ref
               + " element="
               + element
               + " text="
               + element.getText());
     }
     if (beginIndex < 0) {
       LOG.error(
           "Inconsistent reference (begin < 0): ref="
               + ref
               + " element="
               + element
               + "; begin="
               + beginIndex
               + " text="
               + element.getText());
     }
     LOG.assertTrue(endIndex >= 0);
     return element.getText().substring(beginIndex, endIndex);
   }
   return null;
 }
  @Nullable
  public static PsiFile resolveFile(XmlAttribute location, PsiFile baseFile) {
    if (location == null) return null;
    final XmlAttributeValue valueElement = location.getValueElement();
    if (valueElement == null) return null;

    // prefer direct relative path
    final String value = valueElement.getValue();
    final PsiFile file = resolveFile(value, baseFile);
    if (file != baseFile && file instanceof XmlFile) {
      return file;
    }

    final PsiReference[] references = valueElement.getReferences();
    for (PsiReference reference : references) {
      final PsiElement target = reference.resolve();
      if (target == null && reference instanceof PsiPolyVariantReference) {
        final ResolveResult[] results = ((PsiPolyVariantReference) reference).multiResolve(false);
        for (ResolveResult result : results) {
          if (result.isValidResult()) {
            // TODO: how to weigh/prioritize the results?
            final PsiElement element = result.getElement();
            if (element != baseFile && element instanceof XmlFile) {
              return (PsiFile) target;
            }
          }
        }
      } else if (target != baseFile && target instanceof XmlFile) {
        return (PsiFile) target;
      }
    }
    return null;
  }
 @NotNull
 public XPathType getExpectedType(XPathExpression expr) {
   final XmlTag tag = PsiTreeUtil.getContextOfType(expr, XmlTag.class, true);
   if (tag != null && XsltSupport.isXsltTag(tag)) {
     final XsltElement element =
         XsltElementFactory.getInstance().wrapElement(tag, XsltElement.class);
     if (element instanceof XsltVariable) {
       return ((XsltVariable) element).getType();
     } else {
       final XmlAttribute attr = PsiTreeUtil.getContextOfType(expr, XmlAttribute.class, true);
       if (attr != null) {
         if (element instanceof XsltWithParam) {
           final XmlAttribute nameAttr = tag.getAttribute("name", null);
           if (nameAttr != null) {
             final XmlAttributeValue valueElement = nameAttr.getValueElement();
             if (valueElement != null) {
               final PsiReference[] references = valueElement.getReferences();
               for (PsiReference reference : references) {
                 final PsiElement psiElement = reference.resolve();
                 if (psiElement instanceof XsltVariable) {
                   return ((XsltVariable) psiElement).getType();
                 }
               }
             }
           }
         } else {
           final String name = attr.getName();
           return getTypeForTag(tag, name);
         }
       }
     }
   }
   return XPathType.UNKNOWN;
 }
  protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();

    checkExistingMethods(conflicts, true);
    checkExistingMethods(conflicts, false);
    final Collection<PsiClass> classes = ClassInheritorsSearch.search(myClass).findAll();
    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
      final Set<PsiMethod> setters = new HashSet<PsiMethod>();
      final Set<PsiMethod> getters = new HashSet<PsiMethod>();

      for (PsiClass aClass : classes) {
        final PsiMethod getterOverrider =
            myDescriptor.isToEncapsulateGet()
                ? aClass.findMethodBySignature(fieldDescriptor.getGetterPrototype(), false)
                : null;
        if (getterOverrider != null) {
          getters.add(getterOverrider);
        }
        final PsiMethod setterOverrider =
            myDescriptor.isToEncapsulateSet()
                ? aClass.findMethodBySignature(fieldDescriptor.getSetterPrototype(), false)
                : null;
        if (setterOverrider != null) {
          setters.add(setterOverrider);
        }
      }
      if (!getters.isEmpty() || !setters.isEmpty()) {
        final PsiField field = fieldDescriptor.getField();
        for (PsiReference reference : ReferencesSearch.search(field)) {
          final PsiElement place = reference.getElement();
          if (place instanceof PsiReferenceExpression) {
            final PsiExpression qualifierExpression =
                ((PsiReferenceExpression) place).getQualifierExpression();
            final PsiClass ancestor;
            if (qualifierExpression == null) {
              ancestor = PsiTreeUtil.getParentOfType(place, PsiClass.class, false);
            } else {
              ancestor = PsiUtil.resolveClassInType(qualifierExpression.getType());
            }

            final boolean isGetter = !PsiUtil.isAccessedForWriting((PsiExpression) place);
            for (PsiMethod overridden : isGetter ? getters : setters) {
              if (InheritanceUtil.isInheritorOrSelf(myClass, ancestor, true)) {
                conflicts.putValue(
                    overridden,
                    "There is already a "
                        + RefactoringUIUtil.getDescription(overridden, true)
                        + " which would hide generated "
                        + (isGetter ? "getter" : "setter")
                        + " for "
                        + place.getText());
                break;
              }
            }
          }
        }
      }
    }
    return showConflicts(conflicts, refUsages.get());
  }
  protected void performRefactoring(UsageInfo[] usages) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return;

    PsiMethod patternMethod = createMethodToAdd();
    final List<PsiReference> docRefs = new ArrayList<PsiReference>();
    for (UsageInfo usage : usages) {
      if (usage instanceof InheritorUsageInfo) {
        final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor();
        addMethodToClass(inheritor, patternMethod, true);
      } else if (usage instanceof MethodCallUsageInfo
          && !((MethodCallUsageInfo) usage).isInternal()) {
        correctMethodCall(((MethodCallUsageInfo) usage).getMethodCallExpression(), false);
      } else if (usage instanceof JavadocUsageInfo) {
        docRefs.add(usage.getElement().getReference());
      }
    }

    try {
      if (myTargetClass.isInterface()) patternMethod.getBody().delete();

      final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false);
      myMethod.delete();
      for (PsiReference reference : docRefs) {
        reference.bindToElement(method);
      }
      VisibilityUtil.fixVisibility(usages, method, myNewVisibility);
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  public static void replaceMovedMemberTypeParameters(
      final PsiElement member,
      final Iterable<PsiTypeParameter> parametersIterable,
      final PsiSubstitutor substitutor,
      final GroovyPsiElementFactory factory) {
    final Map<PsiElement, PsiElement> replacement = new LinkedHashMap<PsiElement, PsiElement>();
    for (PsiTypeParameter parameter : parametersIterable) {
      PsiType substitutedType = substitutor.substitute(parameter);
      if (substitutedType == null) {
        substitutedType = TypeConversionUtil.erasure(factory.createType(parameter));
      }

      PsiElement scopeElement = member instanceof GrField ? member.getParent() : member;
      for (PsiReference reference :
          ReferencesSearch.search(parameter, new LocalSearchScope(scopeElement))) {
        final PsiElement element = reference.getElement();
        final PsiElement parent = element.getParent();
        if (parent instanceof PsiTypeElement) {
          replacement.put(parent, factory.createTypeElement(substitutedType));
        } else if (element instanceof GrCodeReferenceElement
            && substitutedType instanceof PsiClassType) {
          replacement.put(
              element, factory.createReferenceElementByType((PsiClassType) substitutedType));
        }
      }
    }

    for (PsiElement element : replacement.keySet()) {
      if (element.isValid()) {
        element.replace(replacement.get(element));
      }
    }
  }
 private void findUsagesForInnerClass(PsiClass innerClass, List<FixableUsageInfo> usages) {
   final PsiManager psiManager = innerClass.getManager();
   final Project project = psiManager.getProject();
   final GlobalSearchScope scope = GlobalSearchScope.allScope(project);
   final Iterable<PsiReference> calls = ReferencesSearch.search(innerClass, scope);
   final String innerName = innerClass.getQualifiedName();
   assert innerName != null;
   final String sourceClassQualifiedName = sourceClass.getQualifiedName();
   assert sourceClassQualifiedName != null;
   final String newInnerClassName =
       getQualifiedName() + innerName.substring(sourceClassQualifiedName.length());
   boolean hasExternalReference = false;
   for (PsiReference reference : calls) {
     final PsiElement referenceElement = reference.getElement();
     if (referenceElement instanceof PsiJavaCodeReferenceElement) {
       if (!isInMovedElement(referenceElement)) {
         usages.add(
             new ReplaceClassReference(
                 (PsiJavaCodeReferenceElement) referenceElement, newInnerClassName));
         hasExternalReference = true;
       }
     }
   }
   if (hasExternalReference) {
     innerClassesToMakePublic.add(innerClass);
   }
 }
Example #11
0
 private void registerLocalRef(@NotNull PsiReference ref, PsiElement refElement) {
   if (refElement instanceof PsiMethod
       && PsiTreeUtil.isAncestor(refElement, ref.getElement(), true))
     return; // filter self-recursive calls
   if (refElement instanceof PsiClass
       && PsiTreeUtil.isAncestor(refElement, ref.getElement(), true))
     return; // filter inner use of itself
   synchronized (myLocalRefsMap) {
     myLocalRefsMap.put(ref, refElement);
   }
 }
 private boolean willBeUsedInSubclass(PsiElement member, PsiClass superclass, PsiClass subclass) {
   for (PsiReference ref :
       ReferencesSearch.search(member, new LocalSearchScope(subclass), false)) {
     PsiElement element = ref.getElement();
     if (!RefactoringHierarchyUtil.willBeInTargetClass(
         element, myMembersToMove, superclass, false)) {
       return true;
     }
   }
   return false;
 }
  @Nullable
  private static Condition<PsiElement> findMethodUsages(
      final PsiMethod psiMethod, final PsiElement[] allElementsToDelete, List<UsageInfo> usages) {
    final Collection<PsiReference> references = ReferencesSearch.search(psiMethod).findAll();

    if (psiMethod.isConstructor()) {
      return findConstructorUsages(psiMethod, references, usages, allElementsToDelete);
    }
    final PsiMethod[] overridingMethods =
        removeDeletedMethods(
            OverridingMethodsSearch.search(psiMethod).toArray(PsiMethod.EMPTY_ARRAY),
            allElementsToDelete);

    findFunctionalExpressions(usages, ArrayUtil.prepend(psiMethod, overridingMethods));

    final HashMap<PsiMethod, Collection<PsiReference>> methodToReferences = new HashMap<>();
    for (PsiMethod overridingMethod : overridingMethods) {
      final Collection<PsiReference> overridingReferences =
          ReferencesSearch.search(overridingMethod).findAll();
      methodToReferences.put(overridingMethod, overridingReferences);
    }
    final Set<PsiMethod> validOverriding =
        validateOverridingMethods(
            psiMethod,
            references,
            Arrays.asList(overridingMethods),
            methodToReferences,
            usages,
            allElementsToDelete);
    for (PsiReference reference : references) {
      final PsiElement element = reference.getElement();
      if (!isInside(element, allElementsToDelete) && !isInside(element, validOverriding)) {
        usages.add(
            new SafeDeleteReferenceJavaDeleteUsageInfo(
                element,
                psiMethod,
                PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class) != null));
      }
    }

    final List<PsiMethod> calleesSafeToDelete =
        SafeDeleteJavaCalleeChooser.computeCalleesSafeToDelete(psiMethod);
    if (calleesSafeToDelete != null) {
      for (PsiMethod method : calleesSafeToDelete) {
        usages.add(new SafeDeleteMethodCalleeUsageInfo(method, psiMethod));
      }
    }

    return usage -> {
      if (usage instanceof PsiFile) return false;
      return isInside(usage, allElementsToDelete) || isInside(usage, validOverriding);
    };
  }
 private static void rebindExternalReferences(
     PsiElement element,
     Map<PsiClass, PsiElement> oldToNewMap,
     Set<PsiElement> rebindExpressions) {
   final LocalSearchScope searchScope = new LocalSearchScope(element);
   for (PsiClass aClass : oldToNewMap.keySet()) {
     final PsiElement newClass = oldToNewMap.get(aClass);
     for (PsiReference reference : ReferencesSearch.search(aClass, searchScope)) {
       rebindExpressions.add(reference.bindToElement(newClass));
     }
   }
 }
 private static ArrayList<PsiMethod> filterConstructorsIfFieldAlreadyAssigned(
     PsiMethod[] constructors, PsiField field) {
   final ArrayList<PsiMethod> result = new ArrayList<PsiMethod>(Arrays.asList(constructors));
   for (PsiReference reference :
       ReferencesSearch.search(field, new LocalSearchScope(constructors))) {
     final PsiElement element = reference.getElement();
     if (element instanceof PsiReferenceExpression
         && PsiUtil.isOnAssignmentLeftHand((PsiExpression) element)) {
       result.remove(PsiTreeUtil.getParentOfType(element, PsiMethod.class));
     }
   }
   return result;
 }
 public static boolean addResult(
     Processor<UsageInfo> results, PsiReference ref, FindUsagesOptions options) {
   if (filterUsage(ref.getElement(), options)) {
     TextRange rangeInElement = ref.getRangeInElement();
     return results.process(
         new UsageInfo(
             ref.getElement(),
             rangeInElement.getStartOffset(),
             rangeInElement.getEndOffset(),
             false));
   }
   return true;
 }
  @NotNull
  protected UsageInfo[] findUsages() {
    final PsiManager manager = myMethod.getManager();
    final GlobalSearchScope searchScope = GlobalSearchScope.allScope(manager.getProject());
    final List<UsageInfo> usages = new ArrayList<UsageInfo>();
    for (PsiReference ref : ReferencesSearch.search(myMethod, searchScope, false)) {
      final PsiElement element = ref.getElement();
      if (element instanceof PsiReferenceExpression) {
        boolean isInternal = PsiTreeUtil.isAncestor(myMethod, element, true);
        usages.add(new MethodCallUsageInfo((PsiReferenceExpression) element, isInternal));
      } else if (element instanceof PsiDocTagValue) {
        usages.add(new JavadocUsageInfo(((PsiDocTagValue) element)));
      } else {
        throw new UnknownReferenceTypeException(element.getLanguage());
      }
    }

    if (myTargetClass.isInterface()) {
      addInheritorUsages(myTargetClass, searchScope, usages);
    }

    final PsiCodeBlock body = myMethod.getBody();
    if (body != null) {
      body.accept(
          new JavaRecursiveElementWalkingVisitor() {
            @Override
            public void visitNewExpression(PsiNewExpression expression) {
              if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) {
                usages.add(new InternalUsageInfo(expression));
              }
              super.visitNewExpression(expression);
            }

            @Override
            public void visitReferenceExpression(PsiReferenceExpression expression) {
              if (MoveInstanceMembersUtil.getClassReferencedByThis(expression) != null) {
                usages.add(new InternalUsageInfo(expression));
              } else if (!expression.isQualified()) {
                final PsiElement resolved = expression.resolve();
                if (myTargetVariable.equals(resolved)) {
                  usages.add(new InternalUsageInfo(expression));
                }
              }

              super.visitReferenceExpression(expression);
            }
          });
    }

    return usages.toArray(new UsageInfo[usages.size()]);
  }
 private static void rename(
     PsiReference ref, String newName, PsiManager manager, PsiMember elementToResolve) {
   final PsiElement renamed = ref.handleElementRename(newName);
   PsiElement newly_resolved = ref.resolve();
   if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
     if (newly_resolved instanceof PsiMethod) {
       newly_resolved =
           GroovyPropertyUtils.findFieldForAccessor((PsiMethod) newly_resolved, false);
     }
     if (!manager.areElementsEquivalent(newly_resolved, elementToResolve)) {
       qualify(elementToResolve, renamed, newName);
     }
   }
 }
 protected int getCaretOffset() {
   RangeMarker r;
   if (myLocalMarker != null) {
     final PsiReference reference = myExpr != null ? myExpr.getReference() : null;
     if (reference != null && reference.resolve() == myLocalVariable) {
       r = myExprMarker;
     } else {
       r = myLocalMarker;
     }
   } else {
     r = myExprMarker;
   }
   return r != null ? r.getStartOffset() : 0;
 }
Example #20
0
  public static void change(UsageInfo[] usages, TypeMigrationLabeler labeler, Project project) {
    final List<SmartPsiElementPointer<PsiNewExpression>> newExpressionsToCheckDiamonds =
        new SmartList<>();
    final TypeMigrationLabeler.MigrationProducer producer = labeler.createMigratorFor(usages);

    final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(project);
    List<UsageInfo> nonCodeUsages = new ArrayList<>();
    for (UsageInfo usage : usages) {
      if (((TypeMigrationUsageInfo) usage).isExcluded()) continue;
      final PsiElement element = usage.getElement();
      if (element instanceof PsiVariable
          || element instanceof PsiMember
          || element instanceof PsiExpression
          || element instanceof PsiReferenceParameterList) {
        producer.change(
            (TypeMigrationUsageInfo) usage,
            expression ->
                newExpressionsToCheckDiamonds.add(
                    smartPointerManager.createSmartPsiElementPointer(expression)));
      } else {
        nonCodeUsages.add(usage);
      }
    }

    for (SmartPsiElementPointer<PsiNewExpression> newExpressionPointer :
        newExpressionsToCheckDiamonds) {
      final PsiNewExpression newExpression = newExpressionPointer.getElement();
      if (newExpression != null) {
        labeler.postProcessNewExpression(newExpression);
      }
    }

    for (UsageInfo usageInfo : nonCodeUsages) {
      final PsiElement element = usageInfo.getElement();
      if (element != null) {
        final PsiReference reference = element.getReference();
        if (reference != null) {
          final Object target = producer.getConversion(usageInfo);
          if (target instanceof PsiMember) {
            try {
              reference.bindToElement((PsiElement) target);
            } catch (IncorrectOperationException ignored) {
            }
          }
        }
      }
    }

    producer.flush();
  }
  public static void doRenameGenericNamedElement(
      @NotNull PsiElement namedElement,
      String newName,
      UsageInfo[] usages,
      @Nullable RefactoringElementListener listener)
      throws IncorrectOperationException {
    PsiWritableMetaData writableMetaData = null;
    if (namedElement instanceof PsiMetaOwner) {
      final PsiMetaData metaData = ((PsiMetaOwner) namedElement).getMetaData();
      if (metaData instanceof PsiWritableMetaData) {
        writableMetaData = (PsiWritableMetaData) metaData;
      }
    }
    if (writableMetaData == null && !(namedElement instanceof PsiNamedElement)) {
      LOG.error("Unknown element type:" + namedElement);
    }

    boolean hasBindables = false;
    for (UsageInfo usage : usages) {
      if (!(usage.getReference() instanceof BindablePsiReference)) {
        rename(usage, newName);
      } else {
        hasBindables = true;
      }
    }

    if (writableMetaData != null) {
      writableMetaData.setName(newName);
    } else {
      PsiElement namedElementAfterRename = ((PsiNamedElement) namedElement).setName(newName);
      if (namedElementAfterRename != null) namedElement = namedElementAfterRename;
    }

    if (hasBindables) {
      for (UsageInfo usage : usages) {
        final PsiReference ref = usage.getReference();
        if (ref instanceof BindablePsiReference) {
          try {
            ref.bindToElement(namedElement);
          } catch (IncorrectOperationException e) { // fall back to old scheme
            ref.handleElementRename(newName);
          }
        }
      }
    }
    if (listener != null) {
      listener.elementRenamed(namedElement);
    }
  }
  @Nullable
  private static Condition<PsiElement> findConstructorUsages(
      PsiMethod constructor,
      Collection<PsiReference> originalReferences,
      List<UsageInfo> usages,
      final PsiElement[] allElementsToDelete) {
    HashMap<PsiMethod, Collection<PsiReference>> constructorsToRefs = new HashMap<>();
    HashSet<PsiMethod> newConstructors = new HashSet<>();
    if (isTheOnlyEmptyDefaultConstructor(constructor)) return null;

    newConstructors.add(constructor);
    constructorsToRefs.put(constructor, originalReferences);
    HashSet<PsiMethod> passConstructors = new HashSet<>();
    do {
      passConstructors.clear();
      for (PsiMethod method : newConstructors) {
        final Collection<PsiReference> references = constructorsToRefs.get(method);
        for (PsiReference reference : references) {
          PsiMethod overridingConstructor =
              getOverridingConstructorOfSuperCall(reference.getElement());
          if (overridingConstructor != null
              && !constructorsToRefs.containsKey(overridingConstructor)) {
            Collection<PsiReference> overridingConstructorReferences =
                ReferencesSearch.search(overridingConstructor).findAll();
            constructorsToRefs.put(overridingConstructor, overridingConstructorReferences);
            passConstructors.add(overridingConstructor);
          }
        }
      }
      newConstructors.clear();
      newConstructors.addAll(passConstructors);
    } while (!newConstructors.isEmpty());

    final Set<PsiMethod> validOverriding =
        validateOverridingMethods(
            constructor,
            originalReferences,
            constructorsToRefs.keySet(),
            constructorsToRefs,
            usages,
            allElementsToDelete);

    return usage -> {
      if (usage instanceof PsiFile) return false;
      return isInside(usage, allElementsToDelete) || isInside(usage, validOverriding);
    };
  }
 @Nullable
 static PsiElement resolveReference(final PsiReference psiReference) {
   if (psiReference instanceof PsiPolyVariantReference) {
     final ResolveResult[] results = ((PsiPolyVariantReference) psiReference).multiResolve(true);
     if (results.length == 1) return results[0].getElement();
   }
   return psiReference.resolve();
 }
 private void resolveReference(
     @NotNull PsiReference reference, @NotNull Set<PsiElement> resolved) {
   PsiElement element = reference.resolve();
   if (element != null) {
     resolved.add(element);
   }
   refCount.incrementAndGet();
 }
Example #25
0
 public boolean isReferencedForWrite(@NotNull PsiVariable variable) {
   List<PsiReference> array;
   synchronized (myLocalRefsMap) {
     array = myLocalRefsMap.getKeysByValue(variable);
   }
   if (array == null) return false;
   for (PsiReference ref : array) {
     final PsiElement refElement = ref.getElement();
     if (!(refElement instanceof PsiExpression)) { // possible with incomplete code
       return true;
     }
     if (PsiUtil.isAccessedForWriting((PsiExpression) refElement)) {
       return true;
     }
   }
   return false;
 }
 private void removeParametersUsedInExitsOnly(
     PsiElement codeFragment, List<PsiVariable> inputVariables) {
   LocalSearchScope scope = new LocalSearchScope(codeFragment);
   Variables:
   for (Iterator<PsiVariable> iterator = inputVariables.iterator(); iterator.hasNext(); ) {
     PsiVariable variable = iterator.next();
     for (PsiReference ref : ReferencesSearch.search(variable, scope)) {
       PsiElement element = ref.getElement();
       int elementOffset = myControlFlow.getStartOffset(element);
       if (elementOffset == -1) {
         continue Variables;
       }
       if (elementOffset >= myFlowStart && elementOffset <= myFlowEnd) {
         if (!isInExitStatements(element, myExitStatements)) continue Variables;
       }
     }
     iterator.remove();
   }
 }
  protected void performRefactoring(UsageInfo[] usages) {
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, myTargetClass)) return;

    PsiMethod patternMethod = createMethodToAdd();
    final List<PsiReference> docRefs = new ArrayList<PsiReference>();
    for (UsageInfo usage : usages) {
      if (usage instanceof InheritorUsageInfo) {
        final PsiClass inheritor = ((InheritorUsageInfo) usage).getInheritor();
        addMethodToClass(inheritor, patternMethod, true);
      } else if (usage instanceof MethodCallUsageInfo
          && !((MethodCallUsageInfo) usage).isInternal()) {
        final PsiElement expression = ((MethodCallUsageInfo) usage).getMethodCallExpression();
        if (expression instanceof PsiMethodCallExpression) {
          correctMethodCall((PsiMethodCallExpression) expression, false);
        } else if (expression instanceof PsiMethodReferenceExpression) {
          PsiExpression newQualifier =
              JavaPsiFacade.getInstance(myProject)
                  .getElementFactory()
                  .createExpressionFromText(myTargetVariable.getType().getCanonicalText(), null);
          ((PsiMethodReferenceExpression) expression).setQualifierExpression(newQualifier);
        }
      } else if (usage instanceof JavadocUsageInfo) {
        docRefs.add(usage.getElement().getReference());
      }
    }

    try {
      if (myTargetClass.isInterface()) patternMethod.getBody().delete();

      final PsiMethod method = addMethodToClass(myTargetClass, patternMethod, false);
      myMethod.delete();
      for (PsiReference reference : docRefs) {
        reference.bindToElement(method);
      }
      VisibilityUtil.fixVisibility(UsageViewUtil.toElements(usages), method, myNewVisibility);

      if (myOpenInEditor) {
        EditorHelper.openInEditor(method);
      }
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  @Nullable
  private static String getStringValue(@Nullable PsiElement psiElement, int depth) {

    if (psiElement == null || ++depth > 5) {
      return null;
    }

    if (psiElement instanceof StringLiteralExpression) {
      String resolvedString = ((StringLiteralExpression) psiElement).getContents();
      if (StringUtils.isEmpty(resolvedString)) {
        return null;
      }

      return resolvedString;
    }

    if (psiElement instanceof Field) {
      return getStringValue(((Field) psiElement).getDefaultValue(), depth);
    }

    if (psiElement instanceof PhpReference) {

      PsiReference psiReference = psiElement.getReference();
      if (psiReference == null) {
        return null;
      }

      PsiElement ref = psiReference.resolve();
      if (ref instanceof PhpReference) {
        return getStringValue(psiElement, depth);
      }

      if (ref instanceof Field) {
        PsiElement resolved = ((Field) ref).getDefaultValue();

        if (resolved instanceof StringLiteralExpression) {
          return ((StringLiteralExpression) resolved).getContents();
        }
      }
    }

    return null;
  }
Example #29
0
  public boolean isReferencedByMethodReference(
      @NotNull PsiMethod method, @NotNull LanguageLevel languageLevel) {
    if (!languageLevel.isAtLeast(LanguageLevel.JDK_1_8)) return false;

    List<PsiReference> array;
    synchronized (myLocalRefsMap) {
      array = myLocalRefsMap.getKeysByValue(method);
    }

    if (array != null && !array.isEmpty()) {
      for (PsiReference reference : array) {
        final PsiElement element = reference.getElement();
        if (element != null && element instanceof PsiMethodReferenceExpression) {
          return true;
        }
      }
    }

    return false;
  }
Example #30
0
  public static void sortIdenticalShortNameClasses(
      PsiClass[] classes, @NotNull PsiReference context) {
    if (classes.length <= 1) return;

    PsiElement leaf =
        context
            .getElement()
            .getFirstChild(); // the same proximity weighers are used in completion, where the
                              // leafness is critical
    Arrays.sort(classes, new PsiProximityComparator(leaf));
  }