예제 #1
0
  @Nullable
  public static JetClassOrObject getOutermostClassOrObject(
      @NotNull JetClassOrObject classOrObject) {
    JetClassOrObject current = classOrObject;
    while (true) {
      PsiElement parent = current.getParent();
      assert classOrObject.getParent() != null : "Class with no parent: " + classOrObject.getText();

      if (parent instanceof PsiFile) {
        return current;
      }
      if (parent instanceof JetClassObject) {
        // current class IS the class object declaration
        parent = parent.getParent();
        assert parent instanceof JetClassBody
            : "Parent of class object is not a class body: " + parent;
      }
      if (!(parent instanceof JetClassBody)) {
        // It is a local class, no legitimate outer
        return current;
      }

      current = (JetClassOrObject) parent.getParent();
    }
  }
예제 #2
0
  @Nullable
  public static JetElement getEnclosingElementForLocalDeclaration(
      @Nullable JetNamedDeclaration declaration) {
    if (declaration instanceof JetTypeParameter) {
      declaration = PsiTreeUtil.getParentOfType(declaration, JetNamedDeclaration.class);
    } else if (declaration instanceof JetParameter) {
      PsiElement parent = declaration.getParent();
      if (parent != null && parent.getParent() instanceof JetNamedFunction) {
        declaration = (JetNamedFunction) parent.getParent();
      }
    }

    //noinspection unchecked
    JetElement container =
        PsiTreeUtil.getParentOfType(
            declaration,
            JetBlockExpression.class,
            JetClassInitializer.class,
            JetProperty.class,
            JetFunction.class,
            JetParameter.class);
    if (container == null) return null;

    return (container instanceof JetClassInitializer)
        ? ((JetClassInitializer) container).getBody()
        : container;
  }
  private void analyzeDfaWithNestedClosures(
      PsiElement scope,
      ProblemsHolder holder,
      StandardDataFlowRunner dfaRunner,
      Collection<DfaMemoryState> initialStates) {
    final DataFlowInstructionVisitor visitor = new DataFlowInstructionVisitor(dfaRunner);
    final RunnerResult rc =
        dfaRunner.analyzeMethod(scope, visitor, IGNORE_ASSERT_STATEMENTS, initialStates);
    if (rc == RunnerResult.OK) {
      createDescription(dfaRunner, holder, visitor);

      MultiMap<PsiElement, DfaMemoryState> nestedClosures = dfaRunner.getNestedClosures();
      for (PsiElement closure : nestedClosures.keySet()) {
        analyzeDfaWithNestedClosures(closure, holder, dfaRunner, nestedClosures.get(closure));
      }
    } else if (rc == RunnerResult.TOO_COMPLEX) {
      if (scope.getParent() instanceof PsiMethod) {
        PsiMethod method = (PsiMethod) scope.getParent();
        final PsiIdentifier name = method.getNameIdentifier();
        if (name != null) { // Might be null for synthetic methods like JSP page.
          holder.registerProblem(
              name,
              InspectionsBundle.message("dataflow.too.complex"),
              ProblemHighlightType.WEAK_WARNING);
        }
      }
    }
  }
  @Nullable
  private static PsiClass[] getTopLevelClasses(PsiElement element) {
    while (true) {
      if (element == null || element instanceof PsiFile) break;
      if (element instanceof PsiClass
          && element.getParent() != null
          && ((PsiClass) element).getContainingClass() == null
          && !(element instanceof PsiAnonymousClass)) break;
      element = element.getParent();
    }
    if (element instanceof PsiCompiledElement) return null;
    if (element instanceof PsiClassOwner) {
      PsiClass[] classes = ((PsiClassOwner) element).getClasses();
      if (classes.length > 0) {
        for (final PsiClass aClass : classes) {
          if (aClass instanceof SyntheticElement) {
            return null;
          }
        }

        return classes;
      }
    }
    return element instanceof PsiClass ? new PsiClass[] {(PsiClass) element} : null;
  }
  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));
      }
    }
  }
예제 #6
0
 private static boolean checkRawAcceptable(
     PsiLambdaExpression expression, PsiType functionalInterfaceType) {
   PsiElement parent = expression.getParent();
   while (parent instanceof PsiParenthesizedExpression) {
     parent = parent.getParent();
   }
   if (parent instanceof PsiExpressionList) {
     final PsiElement gParent = parent.getParent();
     if (gParent instanceof PsiMethodCallExpression) {
       final PsiExpression qualifierExpression =
           ((PsiMethodCallExpression) gParent).getMethodExpression().getQualifierExpression();
       final PsiType type = qualifierExpression != null ? qualifierExpression.getType() : null;
       if (type instanceof PsiClassType && ((PsiClassType) type).isRaw()) {
         return true;
       }
       final PsiMethod method = ((PsiMethodCallExpression) gParent).resolveMethod();
       if (method != null) {
         int lambdaIdx = getLambdaIdx((PsiExpressionList) parent, expression);
         final PsiParameter[] parameters = method.getParameterList().getParameters();
         final PsiType normalizedType =
             getNormalizedType(parameters[adjustLambdaIdx(lambdaIdx, method, parameters)]);
         if (normalizedType instanceof PsiClassType && ((PsiClassType) normalizedType).isRaw())
           return true;
       }
     }
     if (functionalInterfaceType instanceof PsiClassType
         && ((PsiClassType) functionalInterfaceType).isRaw()) {
       return false;
     }
   }
   return true;
 }
  private PsiElement getStatementToInsertBefore() {
    PsiElement declarationScope =
        myVariable instanceof PsiParameter
            ? ((PsiParameter) myVariable).getDeclarationScope()
            : PsiUtil.getVariableCodeBlock(myVariable, null);
    if (declarationScope == null) return null;

    PsiElement statement = myClass;
    nextInnerClass:
    do {
      statement = PsiUtil.getEnclosingStatement(statement);

      if (statement == null || statement.getParent() == null) {
        return null;
      }
      PsiElement element = statement;
      while (element != declarationScope && !(element instanceof PsiFile)) {
        if (element instanceof PsiClass) {
          statement = statement.getParent();
          continue nextInnerClass;
        }
        element = element.getParent();
      }
      return statement;
    } while (true);
  }
 private static boolean shouldSuggestClassNameCompletion(final PsiElement element) {
   if (element == null) return false;
   final PsiElement parent = element.getParent();
   if (parent == null) return false;
   return parent.getParent() instanceof PsiTypeElement
       || parent.getParent() instanceof PsiExpressionStatement
       || parent.getParent() instanceof PsiReferenceList;
 }
예제 #9
0
 @Nullable
 public static JetScript getScript(@NotNull JetDeclaration namedDeclaration) {
   PsiElement parent = namedDeclaration.getParent();
   if (parent != null && parent.getParent() instanceof JetScript) {
     return (JetScript) parent.getParent();
   } else {
     return null;
   }
 }
  private static void findClassUsages(
      final PsiClass psiClass,
      final PsiElement[] allElementsToDelete,
      final List<UsageInfo> usages) {
    final boolean justPrivates = containsOnlyPrivates(psiClass);
    final String qualifiedName = psiClass.getQualifiedName();
    final boolean annotationType = psiClass.isAnnotationType() && qualifiedName != null;

    ReferencesSearch.search(psiClass)
        .forEach(
            reference -> {
              final PsiElement element = reference.getElement();

              if (!isInside(element, allElementsToDelete)) {
                PsiElement parent = element.getParent();
                if (parent instanceof PsiReferenceList) {
                  final PsiElement pparent = parent.getParent();
                  if (pparent instanceof PsiClass
                      && element instanceof PsiJavaCodeReferenceElement) {
                    final PsiClass inheritor = (PsiClass) pparent;
                    // If psiClass contains only private members, then it is safe to remove it and
                    // change inheritor's extends/implements accordingly
                    if (justPrivates) {
                      if (parent.equals(inheritor.getExtendsList())
                          || parent.equals(inheritor.getImplementsList())) {
                        usages.add(
                            new SafeDeleteExtendsClassUsageInfo(
                                (PsiJavaCodeReferenceElement) element, psiClass, inheritor));
                        return true;
                      }
                    }
                  }
                }
                LOG.assertTrue(element.getTextRange() != null);
                final PsiFile containingFile = psiClass.getContainingFile();
                boolean sameFileWithSingleClass = false;
                if (containingFile instanceof PsiClassOwner) {
                  final PsiClass[] classes = ((PsiClassOwner) containingFile).getClasses();
                  sameFileWithSingleClass =
                      classes.length == 1
                          && classes[0] == psiClass
                          && element.getContainingFile() == containingFile;
                }

                final boolean safeDelete = sameFileWithSingleClass || isInNonStaticImport(element);
                if (annotationType && parent instanceof PsiAnnotation) {
                  usages.add(
                      new SafeDeleteAnnotation((PsiAnnotation) parent, psiClass, safeDelete));
                } else {
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(element, psiClass, safeDelete));
                }
              }
              return true;
            });
  }
예제 #11
0
  @Nullable
  public static PsiElement getOutermostParent(
      @NotNull PsiElement element, @NotNull PsiElement upperBound, boolean strict) {
    PsiElement parent = strict ? element.getParent() : element;
    while (parent != null && parent.getParent() != upperBound) {
      parent = parent.getParent();
    }

    return parent;
  }
  private static boolean shouldSuggestSmartCompletion(final PsiElement element) {
    if (shouldSuggestClassNameCompletion(element)) return false;

    final PsiElement parent = element.getParent();
    if (parent instanceof PsiReferenceExpression
        && ((PsiReferenceExpression) parent).getQualifier() != null) return false;
    if (parent instanceof PsiReferenceExpression
        && parent.getParent() instanceof PsiReferenceExpression) return true;

    return ExpectedTypesGetter.getExpectedTypes(element, false).length > 0;
  }
예제 #13
0
 static PsiElement createStatementIfNeeded(
     PsiExpression expression, PsiElementFactory factory, PsiElement element)
     throws IncorrectOperationException {
   // if element used in expression, subexpression will do
   if (!(element.getParent() instanceof PsiExpressionStatement)
       && !(element.getParent() instanceof PsiDeclarationStatement)) {
     return expression;
   }
   return factory.createStatementFromText(
       (expression == null ? "" : expression.getText()) + ";", null);
 }
예제 #14
0
  @Nullable
  public static JetClass getClassIfParameterIsProperty(@NotNull JetParameter jetParameter) {
    if (jetParameter.getValOrVarNode() != null) {
      PsiElement parent = jetParameter.getParent();
      if (parent instanceof JetParameterList && parent.getParent() instanceof JetClass) {
        return (JetClass) parent.getParent();
      }
    }

    return null;
  }
 public boolean canInlineElement(PsiElement element) {
   if (element instanceof PsiParameter) {
     final PsiElement parent = element.getParent();
     if (parent instanceof PsiParameterList
         && parent.getParent() instanceof PsiMethod
         && element.getLanguage() == JavaLanguage.INSTANCE) {
       return true;
     }
   }
   return false;
 }
 private static SimplifyBooleanExpressionFix createIntention(PsiElement element, boolean value) {
   if (!(element instanceof PsiExpression)) return null;
   final PsiExpression expression = (PsiExpression) element;
   while (element.getParent() instanceof PsiExpression) {
     element = element.getParent();
   }
   final SimplifyBooleanExpressionFix fix = new SimplifyBooleanExpressionFix(expression, value);
   // simplify intention already active
   if (!fix.isAvailable()
       || SimplifyBooleanExpressionFix.canBeSimplified((PsiExpression) element)) {
     return null;
   }
   return fix;
 }
예제 #17
0
 static void deleteWholeStatement(PsiElement element, PsiElementFactory factory)
     throws IncorrectOperationException {
   // just delete it altogether
   if (element.getParent() instanceof PsiExpressionStatement) {
     PsiExpressionStatement parent = (PsiExpressionStatement) element.getParent();
     if (parent.getParent() instanceof PsiCodeBlock) {
       parent.delete();
     } else {
       // replace with empty statement (to handle with 'if (..) i=0;' )
       parent.replace(createStatementIfNeeded(null, factory, element));
     }
   } else {
     element.delete();
   }
 }
  private void reportNullableReturns(
      DataFlowInstructionVisitor visitor,
      ProblemsHolder holder,
      Set<PsiElement> reportedAnchors,
      @NotNull PsiElement block) {
    final PsiMethod method = getScopeMethod(block);
    if (method == null || NullableStuffInspectionBase.isNullableNotInferred(method, true)) return;

    boolean notNullRequired = NullableNotNullManager.isNotNull(method);
    if (!notNullRequired && !SUGGEST_NULLABLE_ANNOTATIONS) return;

    PsiType returnType = method.getReturnType();
    // no warnings in void lambdas, where the expression is not returned anyway
    if (block instanceof PsiExpression
        && block.getParent() instanceof PsiLambdaExpression
        && returnType == PsiType.VOID) return;

    // no warnings for Void methods, where only null can be possibly returned
    if (returnType == null || returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID)) return;

    for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) {
      assert statement instanceof PsiExpression;
      final PsiExpression expr = (PsiExpression) statement;
      if (!reportedAnchors.add(expr)) continue;

      if (notNullRequired) {
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message("dataflow.message.return.null.from.notnull")
                : InspectionsBundle.message("dataflow.message.return.nullable.from.notnull");
        holder.registerProblem(expr, text);
      } else if (AnnotationUtil.isAnnotatingApplicable(statement)) {
        final NullableNotNullManager manager =
            NullableNotNullManager.getInstance(expr.getProject());
        final String defaultNullable = manager.getDefaultNullable();
        final String presentableNullable = StringUtil.getShortName(defaultNullable);
        final String text =
            isNullLiteralExpression(expr)
                ? InspectionsBundle.message(
                    "dataflow.message.return.null.from.notnullable", presentableNullable)
                : InspectionsBundle.message(
                    "dataflow.message.return.nullable.from.notnullable", presentableNullable);
        final LocalQuickFix[] fixes =
            PsiTreeUtil.getParentOfType(expr, PsiMethod.class, PsiLambdaExpression.class)
                    instanceof PsiLambdaExpression
                ? LocalQuickFix.EMPTY_ARRAY
                : new LocalQuickFix[] {
                  new AnnotateMethodFix(
                      defaultNullable, ArrayUtil.toStringArray(manager.getNotNulls())) {
                    @Override
                    public int shouldAnnotateBaseMethod(
                        PsiMethod method, PsiMethod superMethod, Project project) {
                      return 1;
                    }
                  }
                };
        holder.registerProblem(expr, text, fixes);
      }
    }
  }
예제 #19
0
  public String getAttributeValue(String _name, String namespace) {
    if (namespace == null) {
      return getAttributeValue(_name);
    }

    XmlTagImpl current = this;
    PsiElement parent = getParent();

    while (current != null) {
      BidirectionalMap<String, String> map = current.initNamespaceMaps(parent);
      if (map != null) {
        List<String> keysByValue = map.getKeysByValue(namespace);
        if (keysByValue != null && !keysByValue.isEmpty()) {

          for (String prefix : keysByValue) {
            if (prefix != null && prefix.length() > 0) {
              final String value = getAttributeValue(prefix + ":" + _name);
              if (value != null) return value;
            }
          }
        }
      }

      current = parent instanceof XmlTag ? (XmlTagImpl) parent : null;
      parent = parent.getParent();
    }

    if (namespace.length() == 0 || getNamespace().equals(namespace)) {
      return getAttributeValue(_name);
    }
    return null;
  }
 @Nullable
 private static PsiClass getFieldOrMethodAccessedClass(
     PsiReferenceExpression ref, PsiClass fieldOrMethodClass) {
   PsiElement[] children = ref.getChildren();
   if (children.length > 1 && children[0] instanceof PsiExpression) {
     PsiExpression expr = (PsiExpression) children[0];
     PsiType type = expr.getType();
     if (type != null) {
       if (!(type instanceof PsiClassType)) return null;
       return PsiUtil.resolveClassInType(type);
     } else {
       if (expr instanceof PsiReferenceExpression) {
         PsiElement refElement = ((PsiReferenceExpression) expr).resolve();
         if (refElement instanceof PsiClass) return (PsiClass) refElement;
       }
       return null;
     }
   }
   PsiManager manager = ref.getManager();
   for (PsiElement parent = ref; parent != null; parent = parent.getParent()) {
     if (parent instanceof PsiClass
         && (manager.areElementsEquivalent(parent, fieldOrMethodClass)
             || ((PsiClass) parent).isInheritor(fieldOrMethodClass, true))) {
       return (PsiClass) parent;
     }
   }
   return null;
 }
예제 #21
0
 private static PsiElement getNextElement(PsiElement element) {
   PsiElement sibling = element.getNextSibling();
   if (sibling != null) return sibling;
   element = element.getParent();
   if (element != null) return getNextElement(element);
   return null;
 }
  private static Condition<PsiElement> findFieldUsages(
      final PsiField psiField,
      final List<UsageInfo> usages,
      final PsiElement[] allElementsToDelete) {
    final Condition<PsiElement> isInsideDeleted = getUsageInsideDeletedFilter(allElementsToDelete);
    ReferencesSearch.search(psiField)
        .forEach(
            reference -> {
              if (!isInsideDeleted.value(reference.getElement())) {
                final PsiElement element = reference.getElement();
                final PsiElement parent = element.getParent();
                if (parent instanceof PsiAssignmentExpression
                    && element == ((PsiAssignmentExpression) parent).getLExpression()) {
                  usages.add(
                      new SafeDeleteFieldWriteReference(
                          (PsiAssignmentExpression) parent, psiField));
                } else {
                  TextRange range = reference.getRangeInElement();
                  usages.add(
                      new SafeDeleteReferenceJavaDeleteUsageInfo(
                          reference.getElement(),
                          psiField,
                          range.getStartOffset(),
                          range.getEndOffset(),
                          false,
                          PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class)
                              != null));
                }
              }

              return true;
            });

    return isInsideDeleted;
  }
  public static void initOffsets(final PsiFile file, final OffsetMap offsetMap) {
    int offset =
        Math.max(
            offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET),
            offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));

    PsiElement element = file.findElementAt(offset);
    if (element instanceof PsiWhiteSpace
        && (!element.textContains('\n')
            || CodeStyleSettingsManager.getSettings(file.getProject())
                .getCommonSettings(JavaLanguage.INSTANCE)
                .METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE)) {
      element = file.findElementAt(element.getTextRange().getEndOffset());
    }
    if (element == null) return;

    if (LEFT_PAREN.accepts(element)) {
      offsetMap.addOffset(LPAREN_OFFSET, element.getTextRange().getStartOffset());
      PsiElement list = element.getParent();
      PsiElement last = list.getLastChild();
      if (last instanceof PsiJavaToken
          && ((PsiJavaToken) last).getTokenType() == JavaTokenType.RPARENTH) {
        offsetMap.addOffset(RPAREN_OFFSET, last.getTextRange().getStartOffset());
      }

      offsetMap.addOffset(ARG_LIST_END_OFFSET, list.getTextRange().getEndOffset());
    }
  }
  protected void restoreState(@NotNull final V psiField) {
    if (!ReadonlyStatusHandler.ensureDocumentWritable(
        myProject, InjectedLanguageUtil.getTopLevelEditor(myEditor).getDocument())) return;
    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              final PsiFile containingFile = psiField.getContainingFile();
              final RangeMarker exprMarker = getExprMarker();
              if (exprMarker != null) {
                myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText);
              }

              if (myLocalMarker != null) {
                final PsiElement refVariableElement =
                    containingFile.findElementAt(myLocalMarker.getStartOffset());
                if (refVariableElement != null) {
                  final PsiElement parent = refVariableElement.getParent();
                  if (parent instanceof PsiNamedElement) {
                    ((PsiNamedElement) parent).setName(myLocalName);
                  }
                }

                final V localVariable = getLocalVariable();
                if (localVariable != null && localVariable.isPhysical()) {
                  myLocalVariable = localVariable;
                  final PsiElement nameIdentifier = localVariable.getNameIdentifier();
                  if (nameIdentifier != null) {
                    myLocalMarker = createMarker(nameIdentifier);
                  }
                }
              }
              final List<RangeMarker> occurrenceMarkers = getOccurrenceMarkers();
              for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size();
                  i < occurrenceMarkersSize;
                  i++) {
                RangeMarker marker = occurrenceMarkers.get(i);
                if (getExprMarker() != null
                    && marker.getStartOffset() == getExprMarker().getStartOffset()
                    && myExpr != null) {
                  myOccurrences[i] = myExpr;
                  continue;
                }
                final E psiExpression =
                    restoreExpression(
                        containingFile,
                        psiField,
                        marker,
                        getLocalVariable() != null ? myLocalName : myExprText);
                if (psiExpression != null) {
                  myOccurrences[i] = psiExpression;
                }
              }

              if (myExpr != null && myExpr.isPhysical()) {
                myExprMarker = createMarker(myExpr);
              }
              myOccurrenceMarkers = null;
              deleteTemplateField(psiField);
            });
  }
 @Nullable
 private static PsiType guessElementTypeFromReference(
     MethodPatternMap methodPatternMap, PsiElement ref, TextRange rangeToIgnore) {
   PsiElement refParent = ref.getParent();
   if (refParent instanceof PsiReferenceExpression) {
     PsiReferenceExpression parentExpr = (PsiReferenceExpression) refParent;
     if (ref.equals(parentExpr.getQualifierExpression())
         && parentExpr.getParent() instanceof PsiMethodCallExpression) {
       String methodName = parentExpr.getReferenceName();
       PsiMethodCallExpression methodCall = (PsiMethodCallExpression) parentExpr.getParent();
       PsiExpression[] args = methodCall.getArgumentList().getExpressions();
       MethodPattern pattern = methodPatternMap.findPattern(methodName, args.length);
       if (pattern != null) {
         if (pattern.parameterIndex < 0) { // return value
           if (methodCall.getParent() instanceof PsiTypeCastExpression
               && (rangeToIgnore == null || !rangeToIgnore.contains(methodCall.getTextRange()))) {
             return ((PsiTypeCastExpression) methodCall.getParent()).getType();
           }
         } else {
           return args[pattern.parameterIndex].getType();
         }
       }
     }
   }
   return null;
 }
  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));
  }
 private void handleBranchingInstruction(
     ProblemsHolder holder,
     StandardInstructionVisitor visitor,
     Set<Instruction> trueSet,
     Set<Instruction> falseSet,
     HashSet<PsiElement> reportedAnchors,
     BranchingInstruction instruction,
     final boolean onTheFly) {
   PsiElement psiAnchor = instruction.getPsiAnchor();
   boolean underBinary = isAtRHSOfBooleanAnd(psiAnchor);
   if (instruction instanceof InstanceofInstruction
       && visitor.isInstanceofRedundant((InstanceofInstruction) instruction)) {
     if (visitor.canBeNull((BinopInstruction) instruction)) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message("dataflow.message.redundant.instanceof"),
           new RedundantInstanceofFix());
     } else {
       final LocalQuickFix localQuickFix = createSimplifyBooleanExpressionFix(psiAnchor, true);
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(true)),
           localQuickFix == null ? null : new LocalQuickFix[] {localQuickFix});
     }
   } else if (psiAnchor instanceof PsiSwitchLabelStatement) {
     if (falseSet.contains(instruction)) {
       holder.registerProblem(
           psiAnchor, InspectionsBundle.message("dataflow.message.unreachable.switch.label"));
     }
   } else if (psiAnchor != null
       && !reportedAnchors.contains(psiAnchor)
       && !isFlagCheck(psiAnchor)) {
     boolean evaluatesToTrue = trueSet.contains(instruction);
     final PsiElement parent = psiAnchor.getParent();
     if (parent instanceof PsiAssignmentExpression
         && ((PsiAssignmentExpression) parent).getLExpression() == psiAnchor) {
       holder.registerProblem(
           psiAnchor,
           InspectionsBundle.message(
               "dataflow.message.pointless.assignment.expression",
               Boolean.toString(evaluatesToTrue)),
           createConditionalAssignmentFixes(
               evaluatesToTrue, (PsiAssignmentExpression) parent, onTheFly));
     } else if (!skipReportingConstantCondition(visitor, psiAnchor, evaluatesToTrue)) {
       final LocalQuickFix fix = createSimplifyBooleanExpressionFix(psiAnchor, evaluatesToTrue);
       String message =
           InspectionsBundle.message(
               underBinary
                   ? "dataflow.message.constant.condition.when.reached"
                   : "dataflow.message.constant.condition",
               Boolean.toString(evaluatesToTrue));
       holder.registerProblem(psiAnchor, message, fix == null ? null : new LocalQuickFix[] {fix});
     }
     reportedAnchors.add(psiAnchor);
   }
 }
  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));
    }
  }
예제 #29
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());
  }
예제 #30
0
 static PsiElement replaceElementWithExpression(
     PsiExpression expression, PsiElementFactory factory, PsiElement element)
     throws IncorrectOperationException {
   PsiElement elementToReplace = element;
   PsiElement expressionToReplaceWith = expression;
   if (element.getParent() instanceof PsiExpressionStatement) {
     elementToReplace = element.getParent();
     expressionToReplaceWith =
         factory.createStatementFromText(
             (expression == null ? "" : expression.getText()) + ";", null);
   } else if (element.getParent() instanceof PsiDeclarationStatement) {
     expressionToReplaceWith =
         factory.createStatementFromText(
             (expression == null ? "" : expression.getText()) + ";", null);
   }
   return elementToReplace.replace(expressionToReplaceWith);
 }