コード例 #1
1
  @Override
  protected void updateTitle(@Nullable final PsiVariable variable, final String value) {
    final PsiElement declarationScope =
        variable != null ? ((PsiParameter) variable).getDeclarationScope() : null;
    if (declarationScope instanceof PsiMethod) {
      final PsiMethod psiMethod = (PsiMethod) declarationScope;
      final StringBuilder buf = new StringBuilder();
      buf.append(psiMethod.getName()).append(" (");
      boolean frst = true;
      final List<TextRange> ranges2Remove = new ArrayList<>();
      TextRange addedRange = null;
      for (PsiParameter parameter : psiMethod.getParameterList().getParameters()) {
        if (frst) {
          frst = false;
        } else {
          buf.append(", ");
        }
        int startOffset = buf.length();
        if (myMustBeFinal || myPanel.isGenerateFinal()) {
          buf.append("final ");
        }
        buf.append(parameter.getType().getPresentableText())
            .append(" ")
            .append(variable == parameter ? value : parameter.getName());
        int endOffset = buf.length();
        if (variable == parameter) {
          addedRange = new TextRange(startOffset, endOffset);
        } else if (myPanel.isParamToRemove(parameter)) {
          ranges2Remove.add(new TextRange(startOffset, endOffset));
        }
      }

      buf.append(")");
      setPreviewText(buf.toString());
      final MarkupModel markupModel =
          DocumentMarkupModel.forDocument(getPreviewEditor().getDocument(), myProject, true);
      markupModel.removeAllHighlighters();
      for (TextRange textRange : ranges2Remove) {
        markupModel.addRangeHighlighter(
            textRange.getStartOffset(),
            textRange.getEndOffset(),
            0,
            getTestAttributesForRemoval(),
            HighlighterTargetArea.EXACT_RANGE);
      }
      markupModel.addRangeHighlighter(
          addedRange.getStartOffset(),
          addedRange.getEndOffset(),
          0,
          getTextAttributesForAdd(),
          HighlighterTargetArea.EXACT_RANGE);
      revalidate();
    }
  }
コード例 #2
0
 private static boolean parametersAreEquivalent(
     @NotNull PsiParameter parameter1, @NotNull PsiParameter parameter2) {
   final PsiType type1 = parameter1.getType();
   final PsiType type2 = parameter2.getType();
   if (!typesAreEquivalent(type1, type2)) {
     return false;
   }
   final String name1 = parameter1.getName();
   final String name2 = parameter2.getName();
   return name1.equals(name2);
 }
コード例 #3
0
    public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) {
      final PsiElement element = descriptor.getPsiElement();
      final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
      LOG.assertTrue(method != null);
      PsiParameter parameter = PsiTreeUtil.getParentOfType(element, PsiParameter.class, false);
      if (parameter == null) {
        final PsiParameter[] parameters = method.getParameterList().getParameters();
        for (PsiParameter psiParameter : parameters) {
          if (Comparing.strEqual(psiParameter.getName(), myParameterName)) {
            parameter = psiParameter;
            break;
          }
        }
      }
      if (parameter == null) return;
      if (!CommonRefactoringUtil.checkReadOnlyStatus(project, parameter)) return;

      final PsiExpression defToInline;
      try {
        defToInline =
            JavaPsiFacade.getInstance(project)
                .getElementFactory()
                .createExpressionFromText(myValue, parameter);
      } catch (IncorrectOperationException e) {
        return;
      }
      final PsiParameter parameterToInline = parameter;
      inlineSameParameterValue(method, parameterToInline, defToInline);
    }
  protected void createRemoveParamsPanel(GridBagConstraints gbConstraints, JPanel panel) {
    final JCheckBox[] removeParamsCb = new JCheckBox[myParametersToRemove.length];
    for (int i = 0; i < myParametersToRemove.length; i++) {
      PsiParameter parameter = myParametersToRemove[i];
      if (parameter == null) continue;
      final NonFocusableCheckBox cb =
          new NonFocusableCheckBox(
              RefactoringBundle.message("remove.parameter.0.no.longer.used", parameter.getName()));
      removeParamsCb[i] = cb;
      cb.setSelected(true);
      gbConstraints.gridy++;
      panel.add(cb, gbConstraints);
      final int i1 = i;
      cb.addChangeListener(
          new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
              myParametersToRemoveChecked[i1] = cb.isSelected();
            }
          });
      myParametersToRemoveChecked[i] = true;
    }

    updateControls(removeParamsCb);
    if (myCbReplaceAllOccurences != null) {
      myCbReplaceAllOccurences.addItemListener(
          new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
              updateControls(removeParamsCb);
            }
          });
    }
  }
コード例 #5
0
 private static String compoundLambdaOrMethodReference(
     PsiParameter parameter,
     PsiExpression expression,
     String samQualifiedName,
     PsiType[] samParamTypes) {
   String result = "";
   final Project project = parameter.getProject();
   final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   final PsiClass functionClass =
       psiFacade.findClass(samQualifiedName, GlobalSearchScope.allScope(project));
   for (int i = 0; i < samParamTypes.length; i++) {
     if (samParamTypes[i] instanceof PsiPrimitiveType) {
       samParamTypes[i] = ((PsiPrimitiveType) samParamTypes[i]).getBoxedType(expression);
     }
   }
   final PsiClassType functionalInterfaceType =
       functionClass != null
           ? psiFacade.getElementFactory().createType(functionClass, samParamTypes)
           : null;
   final PsiParameter[] parameters = {parameter};
   final String methodReferenceText =
       LambdaCanBeMethodReferenceInspection.convertToMethodReference(
           expression, parameters, functionalInterfaceType, null);
   if (methodReferenceText != null) {
     LOG.assertTrue(functionalInterfaceType != null);
     result += "(" + functionalInterfaceType.getCanonicalText() + ")" + methodReferenceText;
   } else {
     result += parameter.getName() + " -> " + expression.getText();
   }
   return result;
 }
コード例 #6
0
    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);
        }
      }
    }
コード例 #7
0
    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();
    }
コード例 #8
0
ファイル: Converter.java プロジェクト: rlnbpr/kotlin
 @NotNull
 public Parameter parameterToParameter(@NotNull PsiParameter parameter) {
   return new Parameter(
       new IdentifierImpl(parameter.getName()),
       typeToType(
           parameter.getType(), ConverterUtil.isAnnotatedAsNotNull(parameter.getModifierList())));
 }
コード例 #9
0
  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);
  }
コード例 #10
0
 @Nullable
 public static String getParameterName(@NotNull PsiParameter param) {
   if (param instanceof PsiCompiledElement) { // don't try to find out a compiled parameter name
     return null;
   } else {
     return param.getName();
   }
 }
コード例 #11
0
 private static boolean shouldRenameSetterParameter(
     JavaCodeStyleManager manager, String propertyName, PsiMethod setter) {
   boolean shouldRenameSetterParameter;
   String parameterName = manager.propertyNameToVariableName(propertyName, VariableKind.PARAMETER);
   PsiParameter setterParameter = setter.getParameterList().getParameters()[0];
   shouldRenameSetterParameter = parameterName.equals(setterParameter.getName());
   return shouldRenameSetterParameter;
 }
 private static boolean isUnique(
     PsiParameter[] params, String newName, HashMap<PsiField, String> usedNames) {
   if (usedNames.containsValue(newName)) return false;
   for (PsiParameter parameter : params) {
     if (Comparing.strEqual(parameter.getName(), newName)) {
       return false;
     }
   }
   return true;
 }
コード例 #13
0
  protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
    final UsageInfo[] usages = refUsages.get();
    MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
    final Set<PsiMember> members = new HashSet<PsiMember>();
    members.add(myMethod);
    if (myTargetVariable instanceof PsiField) members.add((PsiMember) myTargetVariable);
    if (!myTargetClass.isInterface()) {
      RefactoringConflictsUtil.analyzeAccessibilityConflicts(
          members, myTargetClass, conflicts, myNewVisibility);
    } else {
      for (final UsageInfo usage : usages) {
        if (usage instanceof InheritorUsageInfo) {
          RefactoringConflictsUtil.analyzeAccessibilityConflicts(
              members, ((InheritorUsageInfo) usage).getInheritor(), conflicts, myNewVisibility);
        }
      }
    }

    if (myTargetVariable instanceof PsiParameter) {
      PsiParameter parameter = (PsiParameter) myTargetVariable;
      for (final UsageInfo usageInfo : usages) {
        if (usageInfo instanceof MethodCallUsageInfo) {
          final PsiElement methodCall = ((MethodCallUsageInfo) usageInfo).getMethodCallExpression();
          if (methodCall instanceof PsiMethodCallExpression) {
            final PsiExpression[] expressions =
                ((PsiMethodCallExpression) methodCall).getArgumentList().getExpressions();
            final int index = myMethod.getParameterList().getParameterIndex(parameter);
            if (index < expressions.length) {
              PsiExpression instanceValue = expressions[index];
              instanceValue = RefactoringUtil.unparenthesizeExpression(instanceValue);
              if (instanceValue instanceof PsiLiteralExpression
                  && ((PsiLiteralExpression) instanceValue).getValue() == null) {
                String message =
                    RefactoringBundle.message(
                        "0.contains.call.with.null.argument.for.parameter.1",
                        RefactoringUIUtil.getDescription(
                            ConflictsUtil.getContainer(methodCall), true),
                        CommonRefactoringUtil.htmlEmphasize(parameter.getName()));
                conflicts.putValue(instanceValue, message);
              }
            }
          } else if (methodCall instanceof PsiMethodReferenceExpression) {
            conflicts.putValue(methodCall, "Method reference would be broken after move");
          }
        }
      }
    }

    try {
      ConflictsUtil.checkMethodConflicts(myTargetClass, myMethod, getPatternMethod(), conflicts);
    } catch (IncorrectOperationException e) {
    }

    return showConflicts(conflicts, usages);
  }
 @Override
 public void visitThrowStatement(PsiThrowStatement statement) {
   super.visitThrowStatement(statement);
   final PsiCatchSection catchSection =
       PsiTreeUtil.getParentOfType(statement, PsiCatchSection.class, true, PsiClass.class);
   if (catchSection == null) {
     return;
   }
   final PsiParameter parameter = catchSection.getParameter();
   if (parameter == null) {
     return;
   }
   @NonNls final String parameterName = parameter.getName();
   if (PsiUtil.isIgnoredName(parameterName)) {
     return;
   }
   final PsiExpression exception = statement.getException();
   if (exception == null) {
     return;
   }
   if (ignoreCantWrap) {
     final PsiType thrownType = exception.getType();
     if (thrownType instanceof PsiClassType) {
       final PsiClassType classType = (PsiClassType) thrownType;
       final PsiClass exceptionClass = classType.resolve();
       if (exceptionClass != null) {
         final PsiMethod[] constructors = exceptionClass.getConstructors();
         final PsiClassType throwableType =
             TypeUtils.getType(CommonClassNames.JAVA_LANG_THROWABLE, statement);
         boolean canWrap = false;
         outer:
         for (PsiMethod constructor : constructors) {
           final PsiParameterList parameterList = constructor.getParameterList();
           final PsiParameter[] parameters = parameterList.getParameters();
           for (PsiParameter constructorParameter : parameters) {
             final PsiType type = constructorParameter.getType();
             if (throwableType.equals(type)) {
               canWrap = true;
               break outer;
             }
           }
         }
         if (!canWrap) {
           return;
         }
       }
     }
   }
   final ReferenceFinder visitor = new ReferenceFinder(parameter);
   exception.accept(visitor);
   if (visitor.usesParameter()) {
     return;
   }
   registerStatementError(statement);
 }
コード例 #15
0
 private static void addParameterUsages(
     PsiParameter parameter, ArrayList<UsageInfo> results, ParameterInfo info) {
   PsiManager manager = parameter.getManager();
   GlobalSearchScope projectScope = GlobalSearchScope.projectScope(manager.getProject());
   for (PsiReference psiReference : ReferencesSearch.search(parameter, projectScope, false)) {
     PsiElement parmRef = psiReference.getElement();
     UsageInfo usageInfo =
         new ChangeSignatureParameterUsageInfo(parmRef, parameter.getName(), info.getName());
     results.add(usageInfo);
   }
 }
コード例 #16
0
 private static boolean askWhetherShouldSearchForParameterInOverridingMethods(
     final PsiElement psiElement, final PsiParameter parameter) {
   return Messages.showOkCancelDialog(
           psiElement.getProject(),
           FindBundle.message(
               "find.parameter.usages.in.overriding.methods.prompt", parameter.getName()),
           FindBundle.message("find.parameter.usages.in.overriding.methods.title"),
           CommonBundle.getYesButtonText(),
           CommonBundle.getNoButtonText(),
           Messages.getQuestionIcon())
       == 0;
 }
コード例 #17
0
 private static boolean forEachStatementsAreEquivalent(
     @NotNull PsiForeachStatement statement1, @NotNull PsiForeachStatement statement2) {
   final PsiExpression value1 = statement1.getIteratedValue();
   final PsiExpression value2 = statement2.getIteratedValue();
   if (!expressionsAreEquivalent(value1, value2)) {
     return false;
   }
   final PsiParameter parameter1 = statement1.getIterationParameter();
   final PsiParameter parameter2 = statement1.getIterationParameter();
   final String name1 = parameter1.getName();
   final String name2 = parameter2.getName();
   if (!name1.equals(name2)) {
     return false;
   }
   final PsiType type1 = parameter1.getType();
   if (!type1.equals(parameter2.getType())) {
     return false;
   }
   final PsiStatement body1 = statement1.getBody();
   final PsiStatement body2 = statement2.getBody();
   return statementsAreEquivalent(body1, body2);
 }
コード例 #18
0
    public static void removeParameter(final PsiMethod method, final PsiParameter parameter) {
      final PsiParameter[] parameters = method.getParameterList().getParameters();
      final List<ParameterInfoImpl> psiParameters = new ArrayList<ParameterInfoImpl>();
      int paramIdx = 0;
      final String paramName = parameter.getName();
      for (PsiParameter param : parameters) {
        if (!Comparing.strEqual(paramName, param.getName())) {
          psiParameters.add(new ParameterInfoImpl(paramIdx, param.getName(), param.getType()));
        }
        paramIdx++;
      }

      new ChangeSignatureProcessor(
              method.getProject(),
              method,
              false,
              null,
              method.getName(),
              method.getReturnType(),
              psiParameters.toArray(new ParameterInfoImpl[psiParameters.size()]))
          .run();
    }
コード例 #19
0
  private void findParametersUsage(
      final PsiMethod method, ArrayList<UsageInfo> result, PsiMethod[] overriders) {
    if (JavaLanguage.INSTANCE.equals(myChangeInfo.getLanguage())) {
      PsiParameter[] parameters = method.getParameterList().getParameters();
      for (ParameterInfo info : myChangeInfo.getNewParameters()) {
        if (info.getOldIndex() >= 0) {
          PsiParameter parameter = parameters[info.getOldIndex()];
          if (!info.getName().equals(parameter.getName())) {
            addParameterUsages(parameter, result, info);

            for (PsiMethod overrider : overriders) {
              PsiParameter parameter1 =
                  overrider.getParameterList().getParameters()[info.getOldIndex()];
              if (parameter1 != null
                  && Comparing.strEqual(parameter.getName(), parameter1.getName())) {
                addParameterUsages(parameter1, result, info);
              }
            }
          }
        }
      }
    }
  }
コード例 #20
0
ファイル: Converter.java プロジェクト: rlnbpr/kotlin
 @NotNull
 private ParameterList createFunctionParameters(@NotNull PsiMethod method) {
   List<Parameter> result = new LinkedList<Parameter>();
   for (PsiParameter parameter : method.getParameterList().getParameters()) {
     result.add(
         new Parameter(
             new IdentifierImpl(parameter.getName()),
             typeToType(
                 parameter.getType(),
                 ConverterUtil.isAnnotatedAsNotNull(parameter.getModifierList())),
             ConverterUtil.isReadOnly(parameter, method.getBody())));
   }
   return new ParameterList(result);
 }
コード例 #21
0
 private static void appendMethodParameters(
     StringBuffer buf, PsiMethod method, boolean showNames) {
   PsiParameter[] params = method.getParameterList().getParameters();
   buf.append('(');
   for (int i = 0; i < params.length; i++) {
     if (i != 0) buf.append(", ");
     PsiParameter param = params[i];
     buf.append(param.getType().getPresentableText());
     if (showNames) {
       buf.append(' ');
       buf.append(param.getName());
     }
   }
   buf.append(')');
 }
コード例 #22
0
  @Test
  public void shouldNotVerifyThatFieldIsSetInConstructorIfConstructorHasDifferentParameterName() {
    // given
    prepareBehaviourForReturningParameter();
    given(parameter.getType()).willReturn(psiType);
    given(psiField.getType()).willReturn(psiType);
    given(parameter.getName()).willReturn(name);
    given(psiField.getName()).willReturn("differentName");

    // when
    boolean result = psiFieldVerifier.isSetInConstructor(psiField, psiClass);

    // then
    assertThat(result, is(false));
  }
 @NotNull
 @Override
 protected String buildErrorString(Object... infos) {
   final PsiTypeElement typeElement = (PsiTypeElement) infos[0];
   final PsiElement parent = typeElement.getParent();
   if (parent instanceof PsiField) {
     final PsiField field = (PsiField) parent;
     return InspectionGadgetsBundle.message(
         "optional.used.as.field.type.problem.descriptor", field.getName());
   } else if (parent instanceof PsiParameter) {
     final PsiParameter parameter = (PsiParameter) parent;
     return InspectionGadgetsBundle.message(
         "optional.used.as.parameter.type.problem.descriptor", parameter.getName());
   }
   throw new AssertionError();
 }
コード例 #24
0
 private static void resolveParameterVsFieldsConflicts(
     final PsiParameter[] newParms,
     final PsiMethod method,
     final PsiParameterList list,
     boolean[] toRemoveParm)
     throws IncorrectOperationException {
   List<FieldConflictsResolver> conflictResolvers = new ArrayList<FieldConflictsResolver>();
   for (PsiParameter parameter : newParms) {
     conflictResolvers.add(new FieldConflictsResolver(parameter.getName(), method.getBody()));
   }
   ChangeSignatureUtil.synchronizeList(
       list, Arrays.asList(newParms), ParameterList.INSTANCE, toRemoveParm);
   JavaCodeStyleManager.getInstance(list.getProject()).shortenClassReferences(list);
   for (FieldConflictsResolver fieldConflictsResolver : conflictResolvers) {
     fieldConflictsResolver.fix();
   }
 }
コード例 #25
0
 private static String createForEachFunctionalExpressionText(
     Project project, PsiStatement body, PsiParameter parameter) {
   final PsiCallExpression callExpression =
       LambdaCanBeMethodReferenceInspection.extractMethodCallFromBlock(body);
   if (callExpression != null) {
     final PsiClassType functionalType = createDefaultConsumerType(project, parameter);
     final PsiParameter[] parameters = {parameter};
     final PsiElement bodyBlock =
         body instanceof PsiBlockStatement ? ((PsiBlockStatement) body).getCodeBlock() : body;
     final String methodReferenceText =
         LambdaCanBeMethodReferenceInspection.convertToMethodReference(
             bodyBlock, parameters, functionalType, null);
     if (methodReferenceText != null) {
       return methodReferenceText;
     }
   }
   return parameter.getName() + " -> " + wrapInBlock(body);
 }
 @Nullable
 private static PsiParameter findParamByName(
     String newName,
     PsiType type,
     PsiParameter[] newParameters,
     ParameterInfoImpl[] parameterInfos) {
   for (PsiParameter newParameter : newParameters) {
     if (Comparing.strEqual(newName, newParameter.getName())) {
       return newParameter;
     }
   }
   for (int i = 0; i < newParameters.length; i++) {
     if (parameterInfos[i].getOldIndex() == -1) {
       final PsiParameter parameter = newParameters[i];
       final PsiType paramType =
           parameterInfos[i].getTypeWrapper().getType(parameter, parameter.getManager());
       if (type.isAssignableFrom(paramType)) {
         return parameter;
       }
     }
   }
   return null;
 }
コード例 #27
0
  private static void modifySuperCall(
      final PsiMethod subConstructor, final Set<PsiParameter> parametersToPassToSuper) {
    final PsiCodeBlock body = subConstructor.getBody();
    if (body != null) {
      PsiMethodCallExpression superCall = null;
      final PsiStatement[] statements = body.getStatements();
      if (statements.length > 0) {
        if (statements[0] instanceof PsiExpressionStatement) {
          final PsiExpression expression = ((PsiExpressionStatement) statements[0]).getExpression();
          if (expression instanceof PsiMethodCallExpression) {
            final PsiMethodCallExpression methodCall = (PsiMethodCallExpression) expression;
            if ("super".equals(methodCall.getMethodExpression().getText())) {
              superCall = methodCall;
            }
          }
        }
      }

      final PsiElementFactory factory =
          JavaPsiFacade.getInstance(subConstructor.getProject()).getElementFactory();
      try {
        if (superCall == null) {
          PsiExpressionStatement statement =
              (PsiExpressionStatement) factory.createStatementFromText("super();", null);
          statement = (PsiExpressionStatement) body.addAfter(statement, null);
          superCall = (PsiMethodCallExpression) statement.getExpression();
        }

        final PsiExpressionList argList = superCall.getArgumentList();
        for (final PsiParameter parameter : parametersToPassToSuper) {
          argList.add(factory.createExpressionFromText(parameter.getName(), null));
        }
      } catch (IncorrectOperationException e) {
        LOG.error(e);
      }
    }
  }
コード例 #28
0
 private void checkCatchSection(PsiCatchSection section) {
   final PsiCodeBlock block = section.getCatchBlock();
   if (block == null || !isCatchBlockEmpty(block)) {
     return;
   }
   final PsiParameter parameter = section.getParameter();
   if (parameter == null) {
     return;
   }
   final PsiIdentifier identifier = parameter.getNameIdentifier();
   if (identifier == null) {
     return;
   }
   @NonNls final String parameterName = parameter.getName();
   if (m_ignoreIgnoreParameter
       && ("ignore".equals(parameterName) || "ignored".equals(parameterName))) {
     return;
   }
   final PsiElement catchToken = section.getFirstChild();
   if (catchToken == null) {
     return;
   }
   registerError(catchToken);
 }
コード例 #29
0
  public static void visitRefInDocTag(
      final PsiDocTag tag,
      final JavadocManager manager,
      final PsiElement context,
      final ArrayList<ProblemDescriptor> problems,
      final InspectionManager inspectionManager,
      final boolean onTheFly) {
    final String tagName = tag.getName();
    final PsiDocTagValue value = tag.getValueElement();
    if (value == null) return;
    final JavadocTagInfo info = manager.getTagInfo(tagName);
    if (info != null && !info.isValidInContext(context)) return;
    final String message = info == null || !info.isInline() ? null : info.checkTagValue(value);
    if (message != null) {
      problems.add(createDescriptor(value, message, inspectionManager, onTheFly));
    }

    final PsiReference reference = value.getReference();
    if (reference == null) return;
    final PsiElement element = reference.resolve();
    if (element != null) return;
    final int textOffset = value.getTextOffset();
    if (textOffset == value.getTextRange().getEndOffset()) return;
    final PsiDocTagValue valueElement = tag.getValueElement();
    if (valueElement == null) return;

    final CharSequence paramName =
        value
            .getContainingFile()
            .getViewProvider()
            .getContents()
            .subSequence(textOffset, value.getTextRange().getEndOffset());
    final String params = "<code>" + paramName + "</code>";
    final List<LocalQuickFix> fixes = new ArrayList<LocalQuickFix>();
    if (onTheFly && "param".equals(tagName)) {
      final PsiDocCommentOwner commentOwner =
          PsiTreeUtil.getParentOfType(tag, PsiDocCommentOwner.class);
      if (commentOwner instanceof PsiMethod) {
        final PsiMethod method = (PsiMethod) commentOwner;
        final PsiParameter[] parameters = method.getParameterList().getParameters();
        final PsiDocTag[] tags = tag.getContainingComment().getTags();
        final Set<String> unboundParams = new HashSet<String>();
        for (PsiParameter parameter : parameters) {
          if (!JavaDocLocalInspection.isFound(tags, parameter)) {
            unboundParams.add(parameter.getName());
          }
        }
        if (!unboundParams.isEmpty()) {
          fixes.add(new RenameReferenceQuickFix(unboundParams));
        }
      }
    }
    fixes.add(new RemoveTagFix(tagName, paramName));

    problems.add(
        inspectionManager.createProblemDescriptor(
            valueElement,
            reference.getRangeInElement(),
            cannotResolveSymbolMessage(params),
            ProblemHighlightType.LIKE_UNKNOWN_SYMBOL,
            onTheFly,
            fixes.toArray(new LocalQuickFix[fixes.size()])));
  }
コード例 #30
0
  public static PsiMethod generateConstructorPrototype(
      PsiClass aClass, PsiMethod baseConstructor, boolean copyJavaDoc, PsiField[] fields)
      throws IncorrectOperationException {
    PsiManager manager = aClass.getManager();
    JVMElementFactory factory =
        JVMElementFactories.requireFactory(aClass.getLanguage(), aClass.getProject());
    CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(manager.getProject());

    PsiMethod constructor = factory.createConstructor(aClass.getName(), aClass);
    String modifier = PsiUtil.getMaximumModifierForMember(aClass, false);

    if (modifier != null) {
      PsiUtil.setModifierProperty(constructor, modifier, true);
    }

    if (baseConstructor != null) {
      PsiJavaCodeReferenceElement[] throwRefs =
          baseConstructor.getThrowsList().getReferenceElements();
      for (PsiJavaCodeReferenceElement ref : throwRefs) {
        constructor.getThrowsList().add(ref);
      }

      if (copyJavaDoc) {
        final PsiDocComment docComment =
            ((PsiMethod) baseConstructor.getNavigationElement()).getDocComment();
        if (docComment != null) {
          constructor.addAfter(docComment, null);
        }
      }
    }

    boolean isNotEnum = false;
    if (baseConstructor != null) {
      PsiClass superClass = aClass.getSuperClass();
      LOG.assertTrue(superClass != null);
      if (!CommonClassNames.JAVA_LANG_ENUM.equals(superClass.getQualifiedName())) {
        isNotEnum = true;
        if (baseConstructor instanceof PsiCompiledElement) { // to get some parameter names
          PsiClass dummyClass =
              JVMElementFactories.requireFactory(
                      baseConstructor.getLanguage(), baseConstructor.getProject())
                  .createClass("Dummy");
          baseConstructor = (PsiMethod) dummyClass.add(baseConstructor);
        }
        PsiParameter[] params = baseConstructor.getParameterList().getParameters();
        for (PsiParameter param : params) {
          PsiParameter newParam = factory.createParameter(param.getName(), param.getType(), aClass);
          GenerateMembersUtil.copyOrReplaceModifierList(param, newParam);
          constructor.getParameterList().add(newParam);
        }
      }
    }

    JavaCodeStyleManager javaStyle = JavaCodeStyleManager.getInstance(aClass.getProject());

    final PsiMethod dummyConstructor = factory.createConstructor(aClass.getName());
    dummyConstructor.getParameterList().replace(constructor.getParameterList().copy());
    List<PsiParameter> fieldParams = new ArrayList<PsiParameter>();
    for (PsiField field : fields) {
      String fieldName = field.getName();
      String name = javaStyle.variableNameToPropertyName(fieldName, VariableKind.FIELD);
      String parmName = javaStyle.propertyNameToVariableName(name, VariableKind.PARAMETER);
      parmName = javaStyle.suggestUniqueVariableName(parmName, dummyConstructor, true);
      PsiParameter parm = factory.createParameter(parmName, field.getType(), aClass);

      final NullableNotNullManager nullableManager =
          NullableNotNullManager.getInstance(field.getProject());
      final String notNull = nullableManager.getNotNull(field);
      if (notNull != null) {
        parm.getModifierList()
            .addAfter(factory.createAnnotationFromText("@" + notNull, field), null);
      }

      constructor.getParameterList().add(parm);
      dummyConstructor.getParameterList().add(parm.copy());
      fieldParams.add(parm);
    }

    ConstructorBodyGenerator generator =
        ConstructorBodyGenerator.INSTANCE.forLanguage(aClass.getLanguage());
    if (generator != null) {
      @NonNls StringBuilder buffer = new StringBuilder();
      generator.start(buffer, constructor.getName(), PsiParameter.EMPTY_ARRAY);
      if (isNotEnum) {
        generator.generateSuperCallIfNeeded(
            buffer, baseConstructor.getParameterList().getParameters());
      }
      generator.generateFieldInitialization(
          buffer, fields, fieldParams.toArray(new PsiParameter[fieldParams.size()]));
      generator.finish(buffer);
      PsiMethod stub = factory.createMethodFromText(buffer.toString(), aClass);
      constructor.getBody().replace(stub.getBody());
    }

    constructor = (PsiMethod) codeStyleManager.reformat(constructor);
    return constructor;
  }