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);
      }
    }
  }
    @Override
    public boolean execute(PsiElement element, ResolveState state) {
      if (element instanceof PsiMethod || element instanceof PsiField) {
        String propertyName;
        PsiType type;

        if (element instanceof PsiMethod) {
          PsiMethod method = (PsiMethod) element;
          if (!GroovyPropertyUtils.isSimplePropertySetter(method)) return true;

          propertyName = GroovyPropertyUtils.getPropertyNameBySetter(method);
          if (propertyName == null) return true;

          type = method.getParameterList().getParameters()[0].getType();
        } else {
          type = ((PsiField) element).getType();
          propertyName = ((PsiField) element).getName();
        }

        if (((PsiModifierListOwner) element).hasModifierProperty(PsiModifier.STATIC)) return true;

        if (myResult.containsKey(propertyName) || propertyName.equals(METACLASS)) return true;

        PsiSubstitutor substitutor = state.get(PsiSubstitutor.KEY);
        if (substitutor != null) {
          type = substitutor.substitute(type);
        }

        myResult.put(propertyName, new TypeCondition(type, element));
      }

      return true;
    }
  private static TailType getReturnTail(PsiElement position) {
    PsiElement scope = position;
    while (true) {
      if (scope instanceof PsiFile || scope instanceof PsiClassInitializer) {
        return TailType.NONE;
      }

      if (scope instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) scope;
        if (method.isConstructor() || PsiType.VOID.equals(method.getReturnType())) {
          return TailType.SEMICOLON;
        }

        return TailType.HUMBLE_SPACE_BEFORE_WORD;
      }
      if (scope instanceof PsiLambdaExpression) {
        final PsiType returnType =
            LambdaUtil.getFunctionalInterfaceReturnType(((PsiLambdaExpression) scope));
        if (PsiType.VOID.equals(returnType)) {
          return TailType.SEMICOLON;
        }
        return TailType.HUMBLE_SPACE_BEFORE_WORD;
      }
      scope = scope.getParent();
    }
  }
  @Override
  public void visitMethod(PsiMethod method) {
    ArrangementSettingsToken type = method.isConstructor() ? CONSTRUCTOR : METHOD;
    JavaElementArrangementEntry entry =
        createNewEntry(method, method.getTextRange(), type, method.getName(), true);
    if (entry == null) {
      return;
    }

    processEntry(entry, method, method.getBody());
    parseProperties(method, entry);
    myInfo.onMethodEntryCreated(method, entry);
    MethodSignatureBackedByPsiMethod overridden =
        SuperMethodsSearch.search(method, null, true, false).findFirst();
    if (overridden != null) {
      myInfo.onOverriddenMethod(overridden.getMethod(), method);
    }
    boolean reset = myMethodBodyProcessor.setBaseMethod(method);
    try {
      method.accept(myMethodBodyProcessor);
    } finally {
      if (reset) {
        myMethodBodyProcessor.setBaseMethod(null);
      }
    }
  }
    private static void removeUnusedParameterViaChangeSignature(
        final PsiMethod psiMethod, final Collection<PsiElement> parametersToDelete) {
      ArrayList<ParameterInfoImpl> newParameters = new ArrayList<ParameterInfoImpl>();
      PsiParameter[] oldParameters = psiMethod.getParameterList().getParameters();
      for (int i = 0; i < oldParameters.length; i++) {
        PsiParameter oldParameter = oldParameters[i];
        if (!parametersToDelete.contains(oldParameter)) {
          newParameters.add(
              new ParameterInfoImpl(i, oldParameter.getName(), oldParameter.getType()));
        }
      }

      ParameterInfoImpl[] parameterInfos =
          newParameters.toArray(new ParameterInfoImpl[newParameters.size()]);

      ChangeSignatureProcessor csp =
          new ChangeSignatureProcessor(
              psiMethod.getProject(),
              psiMethod,
              false,
              null,
              psiMethod.getName(),
              psiMethod.getReturnType(),
              parameterInfos);

      csp.run();
    }
Пример #6
0
 private static PsiMethod convertMethodToLanguage(PsiMethod method, Language language) {
   if (method.getLanguage().equals(language)) {
     return method;
   }
   return JVMElementFactories.getFactory(language, method.getProject())
       .createMethodFromText(method.getText(), null);
 }
  @Nullable
  private static PsiMethod doFindMethodInSuperClassBySignatureInDerived(
      @NotNull PsiClass superClass,
      @NotNull PsiSubstitutor superSubstitutor,
      @NotNull MethodSignature signature,
      final boolean checkDeep) {
    final String name = signature.getName();
    final PsiMethod[] methods = superClass.findMethodsByName(name, false);
    for (final PsiMethod method : methods) {
      if (isSubsignature(method.getSignature(superSubstitutor), signature)) {
        return method;
      }
    }

    if (checkDeep) {
      final PsiClass clazz = superClass.getSuperClass();
      if (clazz != null && clazz != superClass) {
        PsiSubstitutor substitutor1 =
            TypeConversionUtil.getSuperClassSubstitutor(clazz, superClass, superSubstitutor);
        return doFindMethodInSuperClassBySignatureInDerived(clazz, substitutor1, signature, true);
      }
    }

    return null;
  }
  protected void invokeImpl(final PsiClass targetClass) {
    final Project project = myConstructorCall.getProject();
    PsiElementFactory elementFactory = JavaPsiFacade.getInstance(project).getElementFactory();

    try {
      PsiMethod constructor = (PsiMethod) targetClass.add(elementFactory.createConstructor());

      final PsiFile file = targetClass.getContainingFile();
      TemplateBuilderImpl templateBuilder = new TemplateBuilderImpl(constructor);
      CreateFromUsageUtils.setupMethodParameters(
          constructor,
          templateBuilder,
          myConstructorCall.getArgumentList(),
          getTargetSubstitutor(myConstructorCall));
      final PsiMethod superConstructor =
          CreateClassFromNewFix.setupSuperCall(targetClass, constructor, templateBuilder);

      constructor = CodeInsightUtilBase.forcePsiPostprocessAndRestoreElement(constructor);
      Template template = templateBuilder.buildTemplate();
      if (targetClass == null) return;
      final Editor editor = positionCursor(project, targetClass.getContainingFile(), targetClass);
      final TextRange textRange = constructor.getTextRange();
      editor.getDocument().deleteString(textRange.getStartOffset(), textRange.getEndOffset());
      editor.getCaretModel().moveToOffset(textRange.getStartOffset());

      startTemplate(
          editor,
          template,
          project,
          new TemplateEditingAdapter() {
            public void templateFinished(Template template, boolean brokenOff) {
              ApplicationManager.getApplication()
                  .runWriteAction(
                      new Runnable() {
                        public void run() {
                          try {
                            PsiDocumentManager.getInstance(project)
                                .commitDocument(editor.getDocument());
                            final int offset = editor.getCaretModel().getOffset();
                            PsiMethod constructor =
                                PsiTreeUtil.findElementOfClassAtOffset(
                                    file, offset, PsiMethod.class, false);
                            if (superConstructor == null) {
                              CreateFromUsageUtils.setupMethodBody(constructor);
                            } else {
                              OverrideImplementUtil.setupMethodBody(
                                  constructor, superConstructor, targetClass);
                            }
                            CreateFromUsageUtils.setupEditor(constructor, editor);
                          } catch (IncorrectOperationException e) {
                            LOG.error(e);
                          }
                        }
                      });
            }
          });
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
  }
  private PsiMethod generateDelegate(final PsiMethod methodToReplaceIn)
      throws IncorrectOperationException {
    final PsiMethod delegate = (PsiMethod) methodToReplaceIn.copy();
    final PsiElementFactory elementFactory =
        JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
    ChangeSignatureProcessor.makeEmptyBody(elementFactory, delegate);
    final PsiCallExpression callExpression =
        ChangeSignatureProcessor.addDelegatingCallTemplate(delegate, delegate.getName());
    final PsiExpressionList argumentList = callExpression.getArgumentList();
    assert argumentList != null;
    final PsiParameter[] psiParameters = methodToReplaceIn.getParameterList().getParameters();

    final PsiParameter anchorParameter = getAnchorParameter(methodToReplaceIn);
    if (psiParameters.length == 0) {
      argumentList.add(myParameterInitializer);
    } else {
      if (anchorParameter == null) {
        argumentList.add(myParameterInitializer);
      }
      for (int i = 0; i < psiParameters.length; i++) {
        PsiParameter psiParameter = psiParameters[i];
        if (!myParametersToRemove.contains(i)) {
          final PsiExpression expression =
              elementFactory.createExpressionFromText(psiParameter.getName(), delegate);
          argumentList.add(expression);
        }
        if (psiParameter == anchorParameter) {
          argumentList.add(myParameterInitializer);
        }
      }
    }

    return (PsiMethod)
        methodToReplaceIn.getContainingClass().addBefore(delegate, methodToReplaceIn);
  }
 private void doTest(
     ParameterInfoImpl[] newParameters,
     final ThrownExceptionInfo[] newExceptions,
     Set<PsiMethod> methodsToPropagateParameterChanges,
     Set<PsiMethod> methodsToPropagateExceptionChanges,
     PsiMethod primaryMethod)
     throws Exception {
   final String filePath = getBasePath() + getTestName(false) + ".java";
   final PsiType returnType = primaryMethod.getReturnType();
   final CanonicalTypes.Type type =
       returnType == null ? null : CanonicalTypes.createTypeWrapper(returnType);
   new ChangeSignatureProcessor(
           getProject(),
           primaryMethod,
           false,
           null,
           primaryMethod.getName(),
           type,
           generateParameterInfos(primaryMethod, newParameters),
           generateExceptionInfos(primaryMethod, newExceptions),
           methodsToPropagateParameterChanges,
           methodsToPropagateExceptionChanges)
       .run();
   checkResultByFile(filePath + ".after");
 }
  private static boolean isGetterInvocation(@NotNull GrMethodCall call) {
    GrExpression expr = call.getInvokedExpression();
    if (!(expr instanceof GrReferenceExpression)) return false;

    PsiMethod method = call.resolveMethod();
    if (!GroovyPropertyUtils.isSimplePropertyGetter(method)) return false;
    LOG.assertTrue(method != null);
    if (!GroovyNamesUtil.isValidReference(
        GroovyPropertyUtils.getPropertyNameByGetterName(method.getName(), true),
        ((GrReferenceExpression) expr).getQualifier() != null,
        call.getProject())) {
      return false;
    }

    GrArgumentList args = call.getArgumentList();
    if (args == null || args.getAllArguments().length != 0) {
      return false;
    }

    GrExpression ref = genRefForGetter(call, ((GrReferenceExpression) expr).getReferenceName());
    if (ref instanceof GrReferenceExpression) {
      PsiElement resolved = ((GrReferenceExpression) ref).resolve();
      PsiManager manager = call.getManager();
      if (manager.areElementsEquivalent(resolved, method)
          || areEquivalentAccessors(method, resolved, manager)) {
        return true;
      }
    }

    return false;
  }
 private void parameterPropagationTest(final PsiClassType paramType) throws Exception {
   final PsiMethod method = getPrimaryMethod();
   parameterPropagationTest(
       method,
       new HashSet<PsiMethod>(Arrays.asList(method.getContainingClass().getMethods())),
       paramType);
 }
  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);
        }
      }
    }
  }
  @Override
  public void processQuery(
      @NotNull MethodReferencesSearch.SearchParameters p,
      @NotNull Processor<PsiReference> consumer) {
    final PsiMethod method = p.getMethod();
    final PsiClass aClass = method.getContainingClass();
    if (aClass == null) return;

    final String name = method.getName();
    if (StringUtil.isEmpty(name)) return;

    final boolean strictSignatureSearch = p.isStrictSignatureSearch();
    final PsiMethod[] methods =
        strictSignatureSearch ? new PsiMethod[] {method} : aClass.findMethodsByName(name, false);

    SearchScope accessScope = GroovyScopeUtil.getEffectiveScope(methods);
    final SearchScope restrictedByAccess =
        GroovyScopeUtil.restrictScopeToGroovyFiles(p.getScope(), accessScope);

    final String textToSearch = findLongestWord(name);

    p.getOptimizer()
        .searchWord(
            textToSearch,
            restrictedByAccess,
            UsageSearchContext.IN_STRINGS,
            true,
            new MethodTextOccurrenceProcessor(aClass, strictSignatureSearch, methods));
  }
  private void collectUncaughtExceptions(@NotNull PsiMethod method) {
    if (isExternalOverride()) return;
    if (getRefManager().isOfflineView()) return;
    @NonNls final String name = method.getName();
    if (getOwnerClass().isTestCase() && name.startsWith("test")) return;

    if (getSuperMethods().isEmpty()) {
      PsiClassType[] throwsList = method.getThrowsList().getReferencedTypes();
      if (throwsList.length > 0) {
        myUnThrownExceptions =
            throwsList.length == 1
                ? new SmartList<String>()
                : new ArrayList<String>(throwsList.length);
        for (final PsiClassType type : throwsList) {
          PsiClass aClass = type.resolve();
          String fqn = aClass == null ? null : aClass.getQualifiedName();
          if (fqn != null) {
            myUnThrownExceptions.add(fqn);
          }
        }
      }
    }

    final PsiCodeBlock body = method.getBody();
    if (body == null) return;

    final Collection<PsiClassType> exceptionTypes =
        ExceptionUtil.collectUnhandledExceptions(body, method, false);
    for (final PsiClassType exceptionType : exceptionTypes) {
      updateThrowsList(exceptionType);
    }
  }
  /**
   * @return 1 if second is more preferable 0 if methods are equal -1 if first is more preferable
   */
  private int compareMethods(
      @NotNull PsiMethod method1,
      @NotNull PsiSubstitutor substitutor1,
      @Nullable PsiElement resolveContext1,
      @NotNull PsiMethod method2,
      @NotNull PsiSubstitutor substitutor2,
      @Nullable PsiElement resolveContext2) {
    if (!method1.getName().equals(method2.getName())) return 0;

    if (secondMethodIsPreferable(
        method1, substitutor1, resolveContext1, method2, substitutor2, resolveContext2)) {
      if (secondMethodIsPreferable(
          method2, substitutor2, resolveContext2, method1, substitutor1, resolveContext1)) {
        if (method2 instanceof GrGdkMethod && !(method1 instanceof GrGdkMethod)) {
          return -1;
        }
      }
      return 1;
    }
    if (secondMethodIsPreferable(
        method2, substitutor2, resolveContext2, method1, substitutor1, resolveContext1)) {
      return -1;
    }

    return 0;
  }
Пример #17
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  private static JVMName getJVMSignature(
      @Nullable PsiMethod method, boolean constructor, @Nullable PsiClass declaringClass) {
    JVMNameBuffer signature = new JVMNameBuffer();
    signature.append("(");

    if (constructor) {
      if (declaringClass != null) {
        final PsiClass outerClass = declaringClass.getContainingClass();
        if (outerClass != null) {
          // declaring class is an inner class
          if (!declaringClass.hasModifierProperty(PsiModifier.STATIC)) {
            appendJvmClassQualifiedName(signature, getJVMQualifiedName(outerClass));
          }
        }
      }
    }
    if (method != null) {
      for (PsiParameter psiParameter : method.getParameterList().getParameters()) {
        appendJVMSignature(signature, psiParameter.getType());
      }
    }
    signature.append(")");
    if (!constructor && method != null) {
      appendJVMSignature(signature, method.getReturnType());
    } else {
      signature.append(new JVMRawText("V"));
    }
    return signature.toName();
  }
Пример #18
0
  List<MethodContract> inferContracts() {
    PsiCodeBlock body = myMethod.getBody();
    PsiStatement[] statements = body == null ? PsiStatement.EMPTY_ARRAY : body.getStatements();
    if (statements.length == 0) return Collections.emptyList();

    if (statements.length == 1) {
      if (statements[0] instanceof PsiReturnStatement) {
        List<MethodContract> result =
            handleDelegation(((PsiReturnStatement) statements[0]).getReturnValue(), false);
        if (result != null) return result;
      } else if (statements[0] instanceof PsiExpressionStatement
          && ((PsiExpressionStatement) statements[0]).getExpression()
              instanceof PsiMethodCallExpression) {
        List<MethodContract> result =
            handleDelegation(((PsiExpressionStatement) statements[0]).getExpression(), false);
        if (result != null)
          return ContainerUtil.findAll(
              result,
              new Condition<MethodContract>() {
                @Override
                public boolean value(MethodContract contract) {
                  return contract.returnValue == THROW_EXCEPTION
                      || !textMatches(myMethod.getReturnTypeElement(), PsiKeyword.VOID);
                }
              });
      }
    }

    ValueConstraint[] emptyState =
        MethodContract.createConstraintArray(myMethod.getParameterList().getParametersCount());
    return visitStatements(Collections.singletonList(emptyState), statements);
  }
Пример #19
0
    private void processListenerProperties(@NotNull PsiMethod method) {
      if (!method.getName().startsWith("add")
          || method.getParameterList().getParametersCount() != 1) return;

      final PsiParameter parameter = method.getParameterList().getParameters()[0];
      final PsiType type = parameter.getType();
      if (!(type instanceof PsiClassType)) return;

      final PsiClassType classType = (PsiClassType) type;
      final PsiClass listenerClass = classType.resolve();
      if (listenerClass == null) return;

      final PsiMethod[] listenerMethods = listenerClass.getMethods();
      if (!InheritanceUtil.isInheritorOrSelf(listenerClass, myEventListener, true)) return;

      for (PsiMethod listenerMethod : listenerMethods) {
        final String name = listenerMethod.getName();
        if (myPropertyNames.add(name)) {
          LookupElementBuilder builder =
              LookupElementBuilder.create(
                      generatePropertyResolveResult(name, listenerMethod, null, null), name)
                  .withIcon(JetgroovyIcons.Groovy.Property);
          myConsumer.consume(builder);
        }
      }
    }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   super.visitMethod(method);
   final PsiCodeBlock body = method.getBody();
   if (body == null) {
     return;
   }
   if (method.getNameIdentifier() == null) {
     return;
   }
   final PsiMethod leastConcreteSuperMethod = getLeastConcreteSuperMethod(method);
   if (leastConcreteSuperMethod == null) {
     return;
   }
   final PsiClass objectClass = ClassUtils.findObjectClass(method);
   final PsiMethod[] superMethods = method.findSuperMethods(objectClass);
   if (superMethods.length > 0) {
     return;
   }
   if (ignoreEmptySuperMethods) {
     final PsiMethod superMethod = (PsiMethod) leastConcreteSuperMethod.getNavigationElement();
     if (MethodUtils.isTrivial(superMethod, true)) {
       return;
     }
   }
   if (onlyReportWhenAnnotated) {
     if (!AnnotationUtil.isAnnotated(leastConcreteSuperMethod, annotations)) {
       return;
     }
   }
   if (containsSuperCall(body, leastConcreteSuperMethod)) {
     return;
   }
   registerMethodError(method);
 }
 public static boolean areParametersErasureEqual(
     @NotNull PsiMethod method1, @NotNull PsiMethod method2) {
   if (method1.getParameterList().getParametersCount()
       != method2.getParameterList().getParametersCount()) return false;
   return areSignaturesErasureEqual(
       method1.getSignature(PsiSubstitutor.EMPTY), method2.getSignature(PsiSubstitutor.EMPTY));
 }
    public MultiMap<PsiElement, String> findConflicts(Ref<UsageInfo[]> refUsages) {
      MultiMap<PsiElement, String> conflictDescriptions = new MultiMap<PsiElement, String>();
      addMethodConflicts(conflictDescriptions);
      Set<UsageInfo> usagesSet = new HashSet<UsageInfo>(Arrays.asList(refUsages.get()));
      RenameUtil.removeConflictUsages(usagesSet);
      if (myChangeInfo.isVisibilityChanged()) {
        try {
          addInaccessibilityDescriptions(usagesSet, conflictDescriptions);
        } catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }

      for (UsageInfo usageInfo : usagesSet) {
        if (usageInfo instanceof OverriderUsageInfo) {
          final PsiMethod method = (PsiMethod) usageInfo.getElement();
          final PsiMethod baseMethod = ((OverriderUsageInfo) usageInfo).getBaseMethod();
          final int delta =
              baseMethod.getParameterList().getParametersCount()
                  - method.getParameterList().getParametersCount();
          if (delta > 0) {
            final boolean[] toRemove = myChangeInfo.toRemoveParm();
            if (toRemove[
                toRemove.length - 1]) { // todo check if implicit parameter is not the last one
              conflictDescriptions.putValue(
                  baseMethod, "Implicit last parameter should not be deleted");
            }
          }
        }
      }

      return conflictDescriptions;
    }
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      if (!CodeInsightUtilBase.preparePsiElementForWrite(descriptor.getPsiElement())) return;
      final PsiMethod psiMethod =
          PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethod.class);
      if (psiMethod != null) {
        final ArrayList<PsiElement> psiParameters = new ArrayList<PsiElement>();
        final RefElement refMethod = myManager != null ? myManager.getReference(psiMethod) : null;
        if (refMethod != null) {
          for (final RefParameter refParameter : getUnusedParameters((RefMethod) refMethod)) {
            psiParameters.add(refParameter.getElement());
          }
        } else {
          final PsiParameter[] parameters = psiMethod.getParameterList().getParameters();
          for (PsiParameter parameter : parameters) {
            if (Comparing.strEqual(parameter.getName(), myHint)) {
              psiParameters.add(parameter);
              break;
            }
          }
        }
        final PsiModificationTracker tracker = psiMethod.getManager().getModificationTracker();
        final long startModificationCount = tracker.getModificationCount();

        removeUnusedParameterViaChangeSignature(psiMethod, psiParameters);
        if (refMethod != null && startModificationCount != tracker.getModificationCount()) {
          myProcessor.ignoreElement(refMethod);
        }
      }
    }
 private static boolean doCreate(
     Project project,
     Editor editor,
     PsiParameter[] parameters,
     SmartPsiElementPointer constructorPointer,
     ParameterInfoImpl[] parameterInfos,
     HashMap<PsiField, String> fields) {
   PsiMethod constructor = (PsiMethod) constructorPointer.getElement();
   assert constructor != null;
   PsiParameter[] newParameters = constructor.getParameterList().getParameters();
   if (newParameters == parameters) return false; // user must have canceled dialog
   boolean created = false;
   // do not introduce assignment in chanined constructor
   if (JavaHighlightUtil.getChainedConstructors(constructor) == null) {
     for (PsiField field : fields.keySet()) {
       final String defaultParamName = fields.get(field);
       PsiParameter parameter =
           findParamByName(defaultParamName, field.getType(), newParameters, parameterInfos);
       if (parameter == null) {
         continue;
       }
       notNull(project, field, parameter);
       AssignFieldFromParameterAction.addFieldAssignmentStatement(
           project, field, parameter, editor);
       created = true;
     }
   }
   return created;
 }
  public static void addElementUsages(
      final PsiElement element,
      final Processor<UsageInfo> result,
      final FindUsagesOptions options) {
    final SearchScope searchScope = options.searchScope;
    if (element instanceof PsiMethod
        && ApplicationManager.getApplication()
            .runReadAction(
                new Computable<Boolean>() {
                  @Override
                  public Boolean compute() {
                    return ((PsiMethod) element).isConstructor();
                  }
                })) {
      PsiMethod method = (PsiMethod) element;
      final PsiClass parentClass = method.getContainingClass();

      if (parentClass != null) {
        MethodReferencesSearch.search(
                new MethodReferencesSearch.SearchParameters(
                    method,
                    searchScope,
                    options instanceof JavaMethodFindUsagesOptions
                        ? !((JavaMethodFindUsagesOptions) options).isIncludeOverloadUsages
                        : true,
                    options.fastTrack))
            .forEach(
                new ReadActionProcessor<PsiReference>() {
                  @Override
                  public boolean processInReadAction(final PsiReference ref) {
                    return addResult(result, ref, options);
                  }
                });
      }
      return;
    }

    final ReadActionProcessor<PsiReference> consumer =
        new ReadActionProcessor<PsiReference>() {
          @Override
          public boolean processInReadAction(final PsiReference ref) {
            return addResult(result, ref, options);
          }
        };

    if (element instanceof PsiMethod) {
      final boolean strictSignatureSearch =
          !(options instanceof JavaMethodFindUsagesOptions)
              || // field with getter
              !((JavaMethodFindUsagesOptions) options).isIncludeOverloadUsages;
      MethodReferencesSearch.search(
              new MethodReferencesSearch.SearchParameters(
                  (PsiMethod) element, searchScope, strictSignatureSearch, options.fastTrack))
          .forEach(consumer);
    } else {
      ReferencesSearch.search(
              new ReferencesSearch.SearchParameters(element, searchScope, false, options.fastTrack))
          .forEach(consumer);
    }
  }
  private void generateAccessors() {
    // generate accessors
    myNameToGetter = new HashMap<String, PsiMethod>();
    myNameToSetter = new HashMap<String, PsiMethod>();

    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
      final DocCommentPolicy<PsiDocComment> commentPolicy =
          new DocCommentPolicy<PsiDocComment>(myDescriptor.getJavadocPolicy());

      PsiField field = fieldDescriptor.getField();
      final PsiDocComment docComment = field.getDocComment();
      if (myDescriptor.isToEncapsulateGet()) {
        final PsiMethod prototype = fieldDescriptor.getGetterPrototype();
        assert prototype != null;
        final PsiMethod getter = addOrChangeAccessor(prototype, myNameToGetter);
        if (docComment != null) {
          final PsiDocComment getterJavadoc =
              (PsiDocComment) getter.addBefore(docComment, getter.getFirstChild());
          commentPolicy.processNewJavaDoc(getterJavadoc);
        }
      }
      if (myDescriptor.isToEncapsulateSet() && !field.hasModifierProperty(PsiModifier.FINAL)) {
        PsiMethod prototype = fieldDescriptor.getSetterPrototype();
        assert prototype != null;
        addOrChangeAccessor(prototype, myNameToSetter);
      }

      if (docComment != null) {
        commentPolicy.processOldJavaDoc(docComment);
      }
    }
  }
  private static boolean processMethod(
      @NotNull GrTypeDefinition grType,
      @NotNull PsiScopeProcessor processor,
      @NotNull ResolveState state,
      @NotNull PsiElement place,
      boolean processInstanceMethods,
      @NotNull PsiSubstitutor substitutor,
      @NotNull PsiElementFactory factory,
      @NotNull LanguageLevel level,
      boolean placeGroovy,
      @NotNull CandidateInfo info) {
    PsiMethod method = (PsiMethod) info.getElement();
    if (!processInstanceMember(processInstanceMethods, method)
        || isSameDeclaration(place, method)
        || !isMethodVisible(placeGroovy, method)) {
      return true;
    }
    LOG.assertTrue(method.getContainingClass() != null);
    final PsiSubstitutor finalSubstitutor =
        PsiClassImplUtil.obtainFinalSubstitutor(
            method.getContainingClass(),
            info.getSubstitutor(),
            grType,
            substitutor,
            factory,
            level);

    return processor.execute(method, state.put(PsiSubstitutor.KEY, finalSubstitutor));
  }
Пример #28
0
 @NotNull
 public static PsiElement[] findSuperElements(@NotNull PsiElement element) {
   if (element instanceof PsiClass) {
     PsiClass aClass = (PsiClass) element;
     List<PsiClass> allSupers = new ArrayList<>(Arrays.asList(aClass.getSupers()));
     for (Iterator<PsiClass> iterator = allSupers.iterator(); iterator.hasNext(); ) {
       PsiClass superClass = iterator.next();
       if (CommonClassNames.JAVA_LANG_OBJECT.equals(superClass.getQualifiedName()))
         iterator.remove();
     }
     return allSupers.toArray(new PsiClass[allSupers.size()]);
   }
   if (element instanceof PsiMethod) {
     PsiMethod method = (PsiMethod) element;
     if (method.isConstructor()) {
       PsiMethod constructorInSuper = PsiSuperMethodUtil.findConstructorInSuper(method);
       if (constructorInSuper != null) {
         return new PsiMethod[] {constructorInSuper};
       }
     } else {
       PsiMethod[] superMethods = method.findSuperMethods(false);
       if (superMethods.length == 0) {
         PsiMethod superMethod = getSiblingInheritedViaSubClass(method);
         if (superMethod != null) {
           superMethods = new PsiMethod[] {superMethod};
         }
       }
       return superMethods;
     }
   }
   return PsiElement.EMPTY_ARRAY;
 }
Пример #29
0
  private static List<FunctionDescriptor> getSuperFunctionsForMethod(
      @NotNull PsiMethodWrapper method,
      @NotNull BindingTrace trace,
      @NotNull ClassDescriptor containingClass) {
    List<FunctionDescriptor> superFunctions = Lists.newArrayList();

    Map<ClassDescriptor, JetType> superclassToSupertype =
        getSuperclassToSupertypeMap(containingClass);

    Multimap<FqName, Pair<FunctionDescriptor, PsiMethod>> superclassToFunctions =
        getSuperclassToFunctionsMultimap(method, trace.getBindingContext(), containingClass);

    for (HierarchicalMethodSignature superSignature :
        method.getPsiMethod().getHierarchicalMethodSignature().getSuperSignatures()) {
      PsiMethod superMethod = superSignature.getMethod();

      PsiClass psiClass = superMethod.getContainingClass();
      assert psiClass != null;
      String classFqNameString = psiClass.getQualifiedName();
      assert classFqNameString != null;
      FqName classFqName = new FqName(classFqNameString);

      if (!JavaToKotlinClassMap.getInstance().mapPlatformClass(classFqName).isEmpty()) {
        for (FunctionDescriptor superFun :
            JavaToKotlinMethodMap.INSTANCE.getFunctions(superMethod, containingClass)) {
          superFunctions.add(substituteSuperFunction(superclassToSupertype, superFun));
        }
        continue;
      }

      DeclarationDescriptor superFun =
          superMethod instanceof JetClsMethod
              ? trace.get(
                  BindingContext.DECLARATION_TO_DESCRIPTOR,
                  ((JetClsMethod) superMethod).getOrigin())
              : findSuperFunction(superclassToFunctions.get(classFqName), superMethod);
      if (superFun == null) {
        reportCantFindSuperFunction(method);
        continue;
      }

      assert superFun instanceof FunctionDescriptor : superFun.getClass().getName();

      superFunctions.add(
          substituteSuperFunction(superclassToSupertype, (FunctionDescriptor) superFun));
    }

    // sorting for diagnostic stability
    Collections.sort(
        superFunctions,
        new Comparator<FunctionDescriptor>() {
          @Override
          public int compare(FunctionDescriptor fun1, FunctionDescriptor fun2) {
            FqNameUnsafe fqName1 = getFQName(fun1.getContainingDeclaration());
            FqNameUnsafe fqName2 = getFQName(fun2.getContainingDeclaration());
            return fqName1.getFqName().compareTo(fqName2.getFqName());
          }
        });
    return superFunctions;
  }
 @Override
 public void visitMethod(@NotNull PsiMethod method) {
   // don't call super, to keep this from drilling in
   if (!method.isConstructor()) {
     return;
   }
   if (!method.hasModifierProperty(PsiModifier.PRIVATE)) {
     return;
   }
   final PsiClass aClass = method.getContainingClass();
   if (aClass == null) {
     return;
   }
   if (!aClass.isEnum()) {
     return;
   }
   final PsiModifierList modifiers = method.getModifierList();
   final PsiElement[] children = modifiers.getChildren();
   for (final PsiElement child : children) {
     final String text = child.getText();
     if (PsiModifier.PRIVATE.equals(text)) {
       registerError(child, child, method);
     }
   }
 }