Пример #1
0
  @Nullable
  private Collection<DfaMemoryState> createInitialStates(
      @NotNull PsiElement psiBlock, @NotNull InstructionVisitor visitor) {
    PsiElement container =
        PsiTreeUtil.getParentOfType(psiBlock, PsiClass.class, PsiLambdaExpression.class);
    if (container != null
        && (!(container instanceof PsiClass)
            || PsiUtil.isLocalOrAnonymousClass((PsiClass) container))) {
      final PsiElement parent = container.getParent();
      final PsiCodeBlock block = DfaPsiUtil.getTopmostBlockInSameClass(parent);
      if (block != null) {
        final RunnerResult result = analyzeMethod(block, visitor);
        if (result == RunnerResult.OK) {
          final Collection<DfaMemoryState> closureStates =
              myNestedClosures.get(DfaPsiUtil.getTopmostBlockInSameClass(psiBlock));
          if (!closureStates.isEmpty()) {
            return closureStates;
          }
        }
        return null;
      }
    }

    return Collections.singletonList(createMemoryState());
  }
 @Nullable
 public static List<? extends PsiElement> getAllPsiElements(final LookupElement item) {
   List<PsiMethod> allMethods = getAllMethods(item);
   if (allMethods != null) return allMethods;
   if (item.getObject() instanceof PsiElement)
     return Collections.singletonList((PsiElement) item.getObject());
   return null;
 }
Пример #3
0
  private static void createValueRootNode(
      NullAnalysisResult result,
      SliceRootNode oldRoot,
      final Map<SliceNode, NullAnalysisResult> map,
      SliceRootNode root,
      SliceNode oldRootStart,
      String nodeName,
      final int group) {
    Collection<PsiElement> groupedByValue = result.groupedByValue[group];
    if (groupedByValue.isEmpty()) {
      return;
    }
    SliceLeafValueClassNode valueRoot =
        new SliceLeafValueClassNode(root.getProject(), root, nodeName);
    root.myCachedChildren.add(valueRoot);

    Set<PsiElement> uniqueValues =
        new THashSet<PsiElement>(groupedByValue, SliceLeafAnalyzer.LEAF_ELEMENT_EQUALITY);
    for (final PsiElement expression : uniqueValues) {
      SliceNode newRoot =
          SliceLeafAnalyzer.filterTree(
              oldRootStart,
              new NullableFunction<SliceNode, SliceNode>() {
                @Override
                public SliceNode fun(SliceNode oldNode) {
                  if (oldNode.getDuplicate() != null) {
                    return null;
                  }

                  for (PsiElement nullSuspect : group(oldNode, map, group)) {
                    if (PsiEquivalenceUtil.areElementsEquivalent(nullSuspect, expression)) {
                      return oldNode.copy();
                    }
                  }
                  return null;
                }
              },
              new PairProcessor<SliceNode, List<SliceNode>>() {
                @Override
                public boolean process(SliceNode node, List<SliceNode> children) {
                  if (!children.isEmpty()) return true;
                  PsiElement element = node.getValue().getElement();
                  if (element == null) return false;
                  return PsiEquivalenceUtil.areElementsEquivalent(
                      element, expression); // leaf can be there only if it's filtering expression
                }
              });
      valueRoot.myCachedChildren.add(
          new SliceLeafValueRootNode(
              root.getProject(),
              expression,
              valueRoot,
              Collections.singletonList(newRoot),
              oldRoot.getValue().params));
    }
  }
  private static List<? extends LookupElement> createLookupElements(
      CompletionElement completionElement, PsiJavaReference reference) {
    Object completion = completionElement.getElement();
    assert !(completion instanceof LookupElement);

    if (reference instanceof PsiJavaCodeReferenceElement) {
      if (completion instanceof PsiMethod
          && ((PsiJavaCodeReferenceElement) reference).getParent()
              instanceof PsiImportStaticStatement) {
        return Collections.singletonList(
            JavaLookupElementBuilder.forMethod((PsiMethod) completion, PsiSubstitutor.EMPTY));
      }

      if (completion instanceof PsiClass) {
        return JavaClassNameCompletionContributor.createClassLookupItems(
            (PsiClass) completion,
            JavaClassNameCompletionContributor.AFTER_NEW.accepts(reference),
            JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER,
            Conditions.<PsiClass>alwaysTrue());
      }
    }

    if (reference instanceof PsiMethodReferenceExpression
        && completion instanceof PsiMethod
        && ((PsiMethod) completion).isConstructor()) {
      return Collections.singletonList(
          JavaLookupElementBuilder.forMethod(
              (PsiMethod) completion, "new", PsiSubstitutor.EMPTY, null));
    }

    LookupElement _ret = LookupItemUtil.objectToLookupItem(completion);
    if (_ret instanceof LookupItem) {
      final PsiSubstitutor substitutor = completionElement.getSubstitutor();
      if (substitutor != null) {
        ((LookupItem<?>) _ret).setAttribute(LookupItem.SUBSTITUTOR, substitutor);
      }
    }
    return Collections.singletonList(_ret);
  }
Пример #5
0
 @NotNull
 public static Collection<? extends PsiElement> getPossibleInitializationElements(
     final PsiElement qualifierExpression) {
   if (qualifierExpression instanceof PsiMethodCallExpression) {
     return Collections.singletonList(qualifierExpression);
   }
   if (qualifierExpression instanceof PsiReferenceExpression) {
     final PsiElement targetElement = ((PsiReferenceExpression) qualifierExpression).resolve();
     if (!(targetElement instanceof PsiVariable)) {
       return Collections.emptyList();
     }
     final Collection<? extends PsiElement> variableValues =
         getCachedVariableValues((PsiVariable) targetElement, qualifierExpression);
     if (variableValues == null || variableValues.isEmpty()) {
       return DfaPsiUtil.getVariableAssignmentsInFile(
           (PsiVariable) targetElement, false, qualifierExpression);
     }
     return variableValues;
   }
   if (qualifierExpression instanceof PsiLiteralExpression) {
     return Collections.singletonList(qualifierExpression);
   }
   return Collections.emptyList();
 }
 /**
  * intersection may spread over several injected fragments
  *
  * @param rangeToEdit range in encoded(raw) PSI
  * @return list of ranges in encoded (raw) PSI
  */
 @Override
 @SuppressWarnings({"ConstantConditions", "unchecked"})
 @NotNull
 public List<TextRange> intersectWithAllEditableFragments(
     @NotNull PsiFile injectedPsi, @NotNull TextRange rangeToEdit) {
   Place shreds = InjectedLanguageUtil.getShreds(injectedPsi);
   if (shreds == null) return Collections.emptyList();
   Object result = null; // optimization: TextRange or ArrayList
   int count = 0;
   int offset = 0;
   for (PsiLanguageInjectionHost.Shred shred : shreds) {
     TextRange encodedRange =
         TextRange.from(
             offset + shred.getPrefix().length(), shred.getRangeInsideHost().getLength());
     TextRange intersection = encodedRange.intersection(rangeToEdit);
     if (intersection != null) {
       count++;
       if (count == 1) {
         result = intersection;
       } else if (count == 2) {
         TextRange range = (TextRange) result;
         if (range.isEmpty()) {
           result = intersection;
           count = 1;
         } else if (intersection.isEmpty()) {
           count = 1;
         } else {
           List<TextRange> list = new ArrayList<TextRange>();
           list.add(range);
           list.add(intersection);
           result = list;
         }
       } else if (intersection.isEmpty()) {
         count--;
       } else {
         ((List<TextRange>) result).add(intersection);
       }
     }
     offset +=
         shred.getPrefix().length()
             + shred.getRangeInsideHost().getLength()
             + shred.getSuffix().length();
   }
   return count == 0
       ? Collections.<TextRange>emptyList()
       : count == 1 ? Collections.singletonList((TextRange) result) : (List<TextRange>) result;
 }
  static List<? extends LookupElement> createLookupElements(
      CompletionElement completionElement, PsiJavaReference reference) {
    Object completion = completionElement.getElement();
    assert !(completion instanceof LookupElement);

    if (reference instanceof PsiJavaCodeReferenceElement) {
      if (completion instanceof PsiMethod
          && ((PsiJavaCodeReferenceElement) reference).getParent()
              instanceof PsiImportStaticStatement) {
        return Collections.singletonList(
            JavaLookupElementBuilder.forMethod((PsiMethod) completion, PsiSubstitutor.EMPTY));
      }

      if (completion instanceof PsiClass) {
        return JavaClassNameCompletionContributor.createClassLookupItems(
            (PsiClass) completion,
            JavaClassNameCompletionContributor.AFTER_NEW.accepts(reference),
            JavaClassNameInsertHandler.JAVA_CLASS_INSERT_HANDLER,
            Conditions.<PsiClass>alwaysTrue());
      }
    }

    if (reference instanceof PsiMethodReferenceExpression
        && completion instanceof PsiMethod
        && ((PsiMethod) completion).isConstructor()) {
      return Collections.singletonList(
          JavaLookupElementBuilder.forMethod(
              (PsiMethod) completion, "new", PsiSubstitutor.EMPTY, null));
    }

    PsiSubstitutor substitutor = completionElement.getSubstitutor();
    if (substitutor == null) substitutor = PsiSubstitutor.EMPTY;
    if (completion instanceof PsiClass) {
      return Collections.singletonList(
          JavaClassNameCompletionContributor.createClassLookupItem((PsiClass) completion, true)
              .setSubstitutor(substitutor));
    }
    if (completion instanceof PsiMethod) {
      return Collections.singletonList(
          new JavaMethodCallElement((PsiMethod) completion).setQualifierSubstitutor(substitutor));
    }
    if (completion instanceof PsiVariable) {
      return Collections.singletonList(
          new VariableLookupItem((PsiVariable) completion).setSubstitutor(substitutor));
    }

    return Collections.singletonList(LookupItemUtil.objectToLookupItem(completion));
  }
  public Collection<String> findConflicts(
      @NotNull final PsiElement element, @NotNull final PsiElement[] allElementsToDelete) {
    if (element instanceof PsiMethod) {
      final PsiClass containingClass = ((PsiMethod) element).getContainingClass();

      if (containingClass != null && !containingClass.hasModifierProperty(PsiModifier.ABSTRACT)) {
        final PsiMethod[] superMethods = ((PsiMethod) element).findSuperMethods();
        for (PsiMethod superMethod : superMethods) {
          if (isInside(superMethod, allElementsToDelete)) continue;
          if (superMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
            String message =
                RefactoringBundle.message(
                    "0.implements.1",
                    RefactoringUIUtil.getDescription(element, true),
                    RefactoringUIUtil.getDescription(superMethod, true));
            return Collections.singletonList(message);
          }
        }
      }
    } else if (element instanceof PsiParameter) {
      final PsiElement scope = ((PsiParameter) element).getDeclarationScope();
      if (scope instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) scope;
        final PsiClass containingClass = method.getContainingClass();
        if (containingClass != null) {
          final int parameterIndex =
              method.getParameterList().getParameterIndex((PsiParameter) element);
          final PsiMethod methodCopy = (PsiMethod) method.copy();
          methodCopy.getParameterList().getParameters()[parameterIndex].delete();
          final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
          ConflictsUtil.checkMethodConflicts(containingClass, method, methodCopy, conflicts);
          return (Collection<String>) conflicts.values();
        }
      }
    }
    return null;
  }
Пример #9
0
 /** @return (super method, sub class) or null if can't find any siblings */
 @Nullable
 public static SiblingInfo getSiblingInfoInheritedViaSubClass(@NotNull final PsiMethod method) {
   return getSiblingInheritanceInfos(Collections.singletonList(method)).get(method);
 }
 @NotNull
 @Override
 protected Collection<? extends PsiElement> getElementsToWrite(
     @NotNull UsageViewDescriptor descriptor) {
   return Collections.singletonList(mySourceClass);
 }
  @Nullable
  @Override
  public Collection<? extends PsiElement> getElementsToSearch(
      @NotNull PsiElement element,
      @Nullable Module module,
      @NotNull Collection<PsiElement> allElementsToDelete) {
    Project project = element.getProject();
    if (element instanceof PsiPackage && module != null) {
      final PsiDirectory[] directories =
          ((PsiPackage) element).getDirectories(module.getModuleScope());
      if (directories.length == 0) return null;
      return Arrays.asList(directories);
    } else if (element instanceof PsiMethod) {
      final PsiMethod[] methods =
          SuperMethodWarningUtil.checkSuperMethods(
              (PsiMethod) element,
              RefactoringBundle.message("to.delete.with.usage.search"),
              allElementsToDelete);
      if (methods.length == 0) return null;
      final ArrayList<PsiMethod> psiMethods = new ArrayList<>(Arrays.asList(methods));
      psiMethods.add((PsiMethod) element);
      return psiMethods;
    } else if (element instanceof PsiParameter
        && ((PsiParameter) element).getDeclarationScope() instanceof PsiMethod) {
      PsiMethod method = (PsiMethod) ((PsiParameter) element).getDeclarationScope();
      final Set<PsiParameter> parametersToDelete = new HashSet<>();
      parametersToDelete.add((PsiParameter) element);
      final int parameterIndex =
          method.getParameterList().getParameterIndex((PsiParameter) element);
      final List<PsiMethod> superMethods =
          new ArrayList<>(Arrays.asList(method.findDeepestSuperMethods()));
      if (superMethods.isEmpty()) {
        superMethods.add(method);
      }
      for (PsiMethod superMethod : superMethods) {
        parametersToDelete.add(superMethod.getParameterList().getParameters()[parameterIndex]);
        OverridingMethodsSearch.search(superMethod)
            .forEach(
                overrider -> {
                  parametersToDelete.add(
                      overrider.getParameterList().getParameters()[parameterIndex]);
                  return true;
                });
      }

      if (parametersToDelete.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
        String message =
            RefactoringBundle.message(
                "0.is.a.part.of.method.hierarchy.do.you.want.to.delete.multiple.parameters",
                UsageViewUtil.getLongName(method));
        int result =
            Messages.showYesNoCancelDialog(
                project, message, SafeDeleteHandler.REFACTORING_NAME, Messages.getQuestionIcon());
        if (result == Messages.CANCEL) return null;
        if (result == Messages.NO) return Collections.singletonList(element);
      }
      return parametersToDelete;
    } else if (element instanceof PsiTypeParameter) {
      final PsiTypeParameterListOwner owner = ((PsiTypeParameter) element).getOwner();
      if (owner instanceof PsiMethod && !owner.hasModifierProperty(PsiModifier.STATIC)) {
        final PsiTypeParameterList typeParameterList = owner.getTypeParameterList();
        if (typeParameterList != null) {
          final int index = typeParameterList.getTypeParameterIndex((PsiTypeParameter) element);
          if (index >= 0) {
            final ArrayList<PsiTypeParameter> overriders = new ArrayList<>();
            overriders.add((PsiTypeParameter) element);
            OverridingMethodsSearch.search((PsiMethod) owner)
                .forEach(
                    overrider -> {
                      final PsiTypeParameter[] typeParameters = overrider.getTypeParameters();
                      if (index < typeParameters.length) {
                        overriders.add(typeParameters[index]);
                      }
                      return true;
                    });
            if (overriders.size() > 1) {
              String message =
                  RefactoringBundle.message(
                      "0.is.a.part.of.method.hierarchy.do.you.want.to.delete.multiple.type.parameters",
                      UsageViewUtil.getLongName(owner));
              int result =
                  ApplicationManager.getApplication().isUnitTestMode()
                      ? Messages.YES
                      : Messages.showYesNoCancelDialog(
                          project,
                          message,
                          SafeDeleteHandler.REFACTORING_NAME,
                          Messages.getQuestionIcon());
              if (result == Messages.CANCEL) return null;
              if (result == Messages.YES) return overriders;
            }
          }
        }
      }
    }

    return Collections.singletonList(element);
  }
Пример #12
0
 @NotNull
 public File fileToFileWithCompatibilityImport(@NotNull PsiJavaFile javaFile) {
   return fileToFile(javaFile, Collections.singletonList("kotlin.compatibility.*"));
 }
 @Override
 @NotNull
 public List<? extends Class<? extends PsiElement>> elementsToInjectIn() {
   return Collections.singletonList(PsiLanguageInjectionHost.class);
 }
  private static PsiMethod generateDelegateMethod(
      PsiMethod method,
      PsiClass superClass,
      PsiSubstitutor substitutor,
      boolean keepParameterAnnotations) {
    final LightMethodBuilder builder =
        new LightMethodBuilder(
            superClass.getManager(), GroovyFileType.GROOVY_LANGUAGE, method.getName());
    builder.setContainingClass(superClass);
    builder.setMethodReturnType(substitutor.substitute(method.getReturnType()));
    builder.setNavigationElement(method);
    builder.addModifier(PsiModifier.PUBLIC);

    final PsiTypeParameter[] typeParameters = method.getTypeParameters();

    final PsiClass containingClass = method.getContainingClass();
    boolean isRaw =
        containingClass != null && PsiUtil.isRawSubstitutor(containingClass, substitutor);
    if (isRaw) {
      substitutor =
          JavaPsiFacade.getInstance(method.getProject())
              .getElementFactory()
              .createRawSubstitutor(substitutor, typeParameters);
    }

    if (!isRaw) {
      for (PsiTypeParameter typeParameter : typeParameters) {
        builder.addTypeParameter(typeParameter);
      }
    }

    final PsiParameter[] originalParameters = method.getParameterList().getParameters();

    for (int i = 0; i < originalParameters.length; i++) {
      PsiParameter originalParameter = originalParameters[i];
      PsiType type;
      if (isRaw) {
        type = TypeConversionUtil.erasure(substitutor.substitute(originalParameter.getType()));
      } else {
        type = substitutor.substitute(originalParameter.getType());
      }
      if (type == null) {
        type = PsiType.getJavaLangObject(superClass.getManager(), superClass.getResolveScope());
      }
      final LightParameter lightParameter =
          new LightParameter(
              StringUtil.notNullize(originalParameter.getName(), "p" + i),
              type,
              builder,
              JavaLanguage.INSTANCE);
      if (keepParameterAnnotations) {
        final PsiCompositeModifierList delegatingModifierList =
            new PsiCompositeModifierList(
                method.getManager(),
                Collections.singletonList(originalParameter.getModifierList()));
        lightParameter.setModifierList(delegatingModifierList);
      }
      builder.addParameter(lightParameter);
    }
    builder.setBaseIcon(JetgroovyIcons.Groovy.Method);

    return new DelegatedMethod(builder, method);
  }