Java Code Examples for com.intellij.codeInspection.ProblemDescriptor

The following are top voted examples for showing how to use com.intellij.codeInspection.ProblemDescriptor. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: yii2inspections   File: UnusedTranslationsInspector.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement expression = descriptor.getPsiElement();
    if (expression instanceof ArrayHashElement) {
        PsiElement next = expression.getNextSibling();
        if (next instanceof PsiWhiteSpace) {
            next.delete();
        }
        next = expression.getNextSibling();
        if (null != next && PhpTokenTypes.opCOMMA == next.getNode().getElementType()) {
            next.delete();
        }
        next = expression.getNextSibling();
        if (next instanceof PsiWhiteSpace) {
            next.delete();
        }

        expression.delete();
    }
}
 
Example 2
Project: idea-php-typo3-plugin   File: LegacyClassesForIdeQuickFix.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {

    PsiElement psiElement = descriptor.getPsiElement();
    if (DumbService.isDumb(project)) {
        showIsInDumpModeMessage(project, psiElement);
        return;
    }

    if (psiElement instanceof ClassReference) {
        ClassReference classReference = (ClassReference) psiElement;
        String fqn = classReference.getFQN();
        if (fqn != null) {
            String replacementFQN = LegacyClassesForIDEIndex.findReplacementClass(project, fqn);
            if (replacementFQN != null) {
                try {
                    classReference.replace(PhpPsiElementFactory.createClassReference(project, replacementFQN));
                } catch (IncorrectOperationException e) {
                    showErrorMessage(project, "Could not replace class reference", psiElement);
                }
            }
        }
    }
}
 
Example 3
Project: idea-php-typo3-plugin   File: CreateMissingTranslationQuickFix.java   Source Code and License 6 votes vote down vote up
/**
 * Called to apply the fix.
 *
 * @param project    {@link Project}
 * @param descriptor problem reported by the tool which provided this quick fix action
 */
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement psiElement = descriptor.getPsiElement();
    if (psiElement instanceof StringLiteralExpression) {
        StringLiteralExpression stringElement = (StringLiteralExpression) psiElement;
        String contents = stringElement.getContents();

        String fileName = TranslationUtil.extractResourceFilenameFromTranslationString(contents);
        String key = TranslationUtil.extractTranslationKeyTranslationString(contents);
        if (fileName != null) {
            PsiElement[] elementsForKey = ResourcePathIndex.findElementsForKey(project, fileName);
            if (elementsForKey.length > 0) {
                // TranslationUtil.add();
            }
        }
    }
}
 
Example 4
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 6 votes vote down vote up
private void createProblemDescriptorWithQuickFixes(PsiModifierListOwner owner,
                                                   InspectionManager manager,
                                                   Collection<ProblemDescriptor> problemDescriptors,
                                                   PsiElement element) {
    if (element.isPhysical()) {
        LocalQuickFix[] localQuickFixes = createQuickFixes(owner, isRemoveRedundantAnnotations());
        ProblemDescriptor problemDescriptor = manager.createProblemDescriptor(
                element,
                MISSING_NULLABLE_NONNULL_ANNOTATION,
                localQuickFixes,
                GENERIC_ERROR_OR_WARNING,
                true,
                false);
        problemDescriptors.add(problemDescriptor);
    }
}
 
Example 5
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 6 votes vote down vote up
protected void validateOneRule(
    @NotNull final XmlRule rule,
    @NotNull final ValidateContext context,
    @NotNull final Collection<? super ProblemDescriptor> output
) throws XPathExpressionException {
    final XPathService xPathService = ServiceManager.getService(XPathService.class);

    final NodeList selection = xPathService.computeNodeSet(rule.getSelectionXPath(), context.getDocument());
    for (int i = 0; i < selection.getLength(); i++) {
        final Node nextSelected = selection.item(i);
        boolean passed = xPathService.computeBoolean(rule.getTestXPath(), nextSelected);
        if (rule.isFailOnTestQuery()) {
            passed = !passed;
        }
        if (!passed) {
            output.add(this.createProblem(context, nextSelected, rule));
        }
    }
}
 
Example 6
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 6 votes vote down vote up
protected ProblemDescriptor createProblem(
    @NotNull final ValidateContext context,
    @NotNull final Node problemNode,
    @NotNull final XmlRule rule
) {
    final PsiElement problemPsi = context.mapNodeToPsi(problemNode);
    final ProblemHighlightType highlightType = this.computePriority(rule);

    return context.getManager().createProblemDescriptor(
        problemPsi,
        rule.getDescription(),
        true,
        highlightType,
        context.isOnTheFly()
    );
}
 
Example 7
Project: intellij-csv-validator   File: CsvValidationInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        List<Integer> quotePositions = new ArrayList<>();

        int quotePosition = CsvIntentionHelper.getOpeningQuotePosition(element);
        if (quotePosition != -1) {
            quotePositions.add(quotePosition);
        }
        PsiElement endSeparatorElement = CsvIntentionHelper.findQuotePositionsUntilSeparator(element, quotePositions);
        if (endSeparatorElement == null) {
            quotePositions.add(document.getTextLength());
        } else {
            quotePositions.add(endSeparatorElement.getTextOffset());
        }
        String text = CsvIntentionHelper.addQuotes(document.getText(), quotePositions);
        document.setText(text);
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 8
Project: intellij-ce-playground   File: PyChangeSignatureQuickFix.java   Source Code and License 6 votes vote down vote up
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
  final PyFunction function = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PyFunction.class);
  if (function == null) return;
  final PyClass cls = function.getContainingClass();
  assert cls != null;
  final String functionName = function.getName();
  final String complementaryName = PyNames.NEW.equals(functionName) ? PyNames.INIT : PyNames.NEW;
  final TypeEvalContext context = TypeEvalContext.userInitiated(project, descriptor.getEndElement().getContainingFile());
  final PyFunction complementaryMethod = myOverridenMethod ? (PyFunction)PySuperMethodsSearch.search(function, context).findFirst()
                                                           : cls.findMethodByName(complementaryName, true);

  assert complementaryMethod != null;
  final PyMethodDescriptor methodDescriptor = new PyMethodDescriptor(function) {
    @Override
    public List<PyParameterInfo> getParameters() {
      final List<PyParameterInfo> parameterInfos = super.getParameters();
      final int paramLength = function.getParameterList().getParameters().length;
      final int complementaryParamLength = complementaryMethod.getParameterList().getParameters().length;
      if (complementaryParamLength > paramLength)
        parameterInfos.add(new PyParameterInfo(-1, "**kwargs", "", false));
      return parameterInfos;
    }
  };
  final PyChangeSignatureDialog dialog = new PyChangeSignatureDialog(project, methodDescriptor);
  dialog.show();
}
 
Example 9
Project: intellij-ce-playground   File: ListIndexOfReplaceableByContainsInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiBinaryExpression expression =
    (PsiBinaryExpression)descriptor.getPsiElement();
  final PsiExpression lhs = expression.getLOperand();
  final PsiExpression rhs = expression.getROperand();
  final String newExpressionText;
  if (lhs instanceof PsiMethodCallExpression) {
    final PsiMethodCallExpression callExpression =
      (PsiMethodCallExpression)lhs;
    newExpressionText =
      createContainsExpressionText(callExpression, false,
                                   expression.getOperationTokenType());
  }
  else {
    final PsiMethodCallExpression callExpression =
      (PsiMethodCallExpression)rhs;
    assert callExpression != null;
    newExpressionText =
      createContainsExpressionText(callExpression, true,
                                   expression.getOperationTokenType());
  }
  PsiReplacementUtil.replaceExpression(expression, newExpressionText);
}
 
Example 10
Project: intellij-ce-playground   File: UtilityClassCanBeEnumInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (!(parent instanceof PsiClass)) {
    return;
  }
  final PsiClass aClass = (PsiClass)parent;
  for (PsiMethod constructor : aClass.getConstructors()) {
    constructor.delete();
  }
  final List<PsiKeyword> keywords = PsiTreeUtil.getChildrenOfTypeAsList(aClass, PsiKeyword.class);
  if (keywords.isEmpty()) {
    return;
  }
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiStatement statement = factory.createStatementFromText(";", element);
  final PsiElement token = statement.getChildren()[0];
  aClass.addAfter(token, aClass.getLBrace());
  final PsiKeyword newKeyword = factory.createKeyword(PsiKeyword.ENUM);
  keywords.get(0).replace(newKeyword);
}
 
Example 11
Project: intellij-ce-playground   File: RemoveLeadingZeroFix.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final String text = element.getText();
  final int max = text.length() - 1;
  if (max < 1) {
    return;
  }
  int index = 0;
  while (index < max && (text.charAt(index) == '0' || text.charAt(index) == '_')) {
    index++;
  }
  final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
  final PsiElementFactory factory = psiFacade.getElementFactory();
  final String textWithoutLeadingZeros = text.substring(index);
  final PsiExpression decimalNumber =
    factory.createExpressionFromText(textWithoutLeadingZeros,
                                     element);
  element.replace(decimalNumber);
}
 
Example 12
Project: intellij-ce-playground   File: InnerClassReferencedViaSubclassInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiIdentifier name = (PsiIdentifier)descriptor.getPsiElement();
  final PsiJavaCodeReferenceElement reference = (PsiJavaCodeReferenceElement)name.getParent();
  final PsiClass aClass = (PsiClass)reference.resolve();
  if (aClass == null) {
    return;
  }
  final PsiClass containingClass = aClass.getContainingClass();
  if (containingClass == null) {
    return;
  }
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(reference.getProject());
  final PsiJavaCodeReferenceElement newReferenceElement;
  if (reference instanceof PsiReferenceExpression) {
    newReferenceElement = factory.createReferenceExpression(containingClass);
  } else {
    newReferenceElement = factory.createClassReferenceElement(containingClass);
  }
  final PsiElement qualifier = reference.getQualifier();
  if (qualifier == null) {
    return;
  }
  qualifier.replace(newReferenceElement);
}
 
Example 13
Project: intellij-ce-playground   File: UnnecessaryBlockStatementInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement leftBrace = descriptor.getPsiElement();
  final PsiElement parent = leftBrace.getParent();
  if (!(parent instanceof PsiCodeBlock)) {
    return;
  }
  final PsiCodeBlock block = (PsiCodeBlock)parent;
  final PsiBlockStatement blockStatement =
    (PsiBlockStatement)block.getParent();
  final PsiElement[] children = block.getChildren();
  if (children.length > 2) {
    final PsiElement element = blockStatement.getParent();
    element.addRangeBefore(children[1],
                           children[children.length - 2], blockStatement);
  }
  blockStatement.delete();
}
 
Example 14
Project: intellij-ce-playground   File: NewStringBufferWithCharArgumentInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiNewExpression newExpression =
    (PsiNewExpression)element.getParent();
  final PsiExpressionList argumentList =
    newExpression.getArgumentList();
  if (argumentList == null) {
    return;
  }
  final PsiExpression[] arguments = argumentList.getExpressions();
  if (arguments.length != 1) {
    return;
  }
  final PsiExpression argument = arguments[0];
  final String text = argument.getText();
  final String newArgument = '"' + StringUtil.escapeStringCharacters(StringUtil.stripQuotesAroundValue(text)) + '"';
  PsiReplacementUtil.replaceExpression(argument, newArgument);
}
 
Example 15
Project: intellij-ce-playground   File: OverlyStrongTypeCastInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement castTypeElement = descriptor.getPsiElement();
  final PsiTypeCastExpression expression = (PsiTypeCastExpression)castTypeElement.getParent();
  if (expression == null) {
    return;
  }
  final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, true);
  if (expectedType == null) {
    return;
  }
  final PsiExpression operand = expression.getOperand();
  if (operand == null) {
    return;
  }
  @NonNls
  final String newExpression = '(' + expectedType.getCanonicalText() + ')' + operand.getText();
  PsiReplacementUtil.replaceExpressionAndShorten(expression, newExpression);
}
 
Example 16
Project: intellij-ce-playground   File: UtilityClassWithoutPrivateConstructorInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement classNameIdentifier = descriptor.getPsiElement();
  final PsiElement parent = classNameIdentifier.getParent();
  if (!(parent instanceof PsiClass)) {
    return;
  }
  final PsiClass aClass = (PsiClass)parent;
  final PsiMethod[] constructors = aClass.getConstructors();
  for (final PsiMethod constructor : constructors) {
    final PsiParameterList parameterList = constructor.getParameterList();
    if (parameterList.getParametersCount() == 0) {
      final PsiModifierList modifiers = constructor.getModifierList();
      modifiers.setModifierProperty(PsiModifier.PUBLIC, false);
      modifiers.setModifierProperty(PsiModifier.PROTECTED, false);
      modifiers.setModifierProperty(PsiModifier.PRIVATE, true);
    }
  }
}
 
Example 17
Project: intellij-ce-playground   File: MethodNameSameAsClassNameInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (!(parent instanceof PsiMethod)) {
    return;
  }
  final PsiMethod method = (PsiMethod)parent;
  final PsiTypeElement returnTypeElement =
    method.getReturnTypeElement();
  if (returnTypeElement == null) {
    return;
  }
  returnTypeElement.delete();
}
 
Example 18
Project: intellij-ce-playground   File: PyUpdatePropertySignatureQuickFix.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PyCallable function = PsiTreeUtil.getParentOfType(element, PyCallable.class, false);
  assert function != null;
  final PyParameterList parameterList = function.getParameterList();
  final PyParameter[] parameters = parameterList.getParameters();
  final PyElementGenerator generator = PyElementGenerator.getInstance(project);
  String selfText = parameters.length != 0 ? parameters[0].getText() : PyNames.CANONICAL_SELF;
  final StringBuilder functionText = new StringBuilder("def foo(" + selfText);
  if (myHasValue) {
    String valueText = parameters.length > 1 ? parameters[1].getText() : "value";
    functionText.append(", ").append(valueText);
  }
  functionText.append("): pass");

  final PyParameterList list = generator.createFromText(LanguageLevel.forElement(element),
                                                        PyFunction.class, functionText.toString()).getParameterList();
  parameterList.replace(list);
}
 
Example 19
Project: intellij-ce-playground   File: DeclareCollectionAsInterfaceInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (!(parent instanceof PsiJavaCodeReferenceElement)) {
    return;
  }
  final StringBuilder newElementText = new StringBuilder(typeString);
  final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)parent;
  final PsiReferenceParameterList parameterList = referenceElement.getParameterList();
  if (parameterList != null) {
    newElementText.append(parameterList.getText());
  }
  final PsiElement grandParent = parent.getParent();
  if (!(grandParent instanceof PsiTypeElement)) {
    return;
  }
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiTypeElement newTypeElement = factory.createTypeElementFromText(newElementText.toString(), element);
  JavaCodeStyleManager.getInstance(project).shortenClassReferences(grandParent.replace(newTypeElement));
}
 
Example 20
Project: intellij-ce-playground   File: InstantiatingObjectToGetClassObjectInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiMethodCallExpression expression =
    (PsiMethodCallExpression)descriptor.getPsiElement();
  final PsiReferenceExpression methodExpression =
    expression.getMethodExpression();
  final PsiExpression qualifier =
    methodExpression.getQualifierExpression();
  if (qualifier == null) {
    return;
  }
  final PsiType type = qualifier.getType();
  if (type == null) {
    return;
  }
  PsiReplacementUtil.replaceExpression(expression,
                                       getTypeText(type, new StringBuilder()) + ".class");
}
 
Example 21
Project: intellij-ce-playground   File: InlineVariableFix.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(@NotNull final Project project, final ProblemDescriptor descriptor) {
  final PsiElement nameElement = descriptor.getPsiElement();
  final PsiLocalVariable variable = (PsiLocalVariable)nameElement.getParent();
  final PsiExpression initializer = variable.getInitializer();
  if (initializer == null) {
    return;
  }
  final Collection<PsiReference> references = ReferencesSearch.search(variable).findAll();
  final Collection<PsiElement> replacedElements = new ArrayList<PsiElement>();
  for (PsiReference reference : references) {
    final PsiExpression expression = InlineUtil.inlineVariable(variable, initializer, (PsiJavaCodeReferenceElement)reference);
    replacedElements.add(expression);
  }
  HighlightUtils.highlightElements(replacedElements);
  variable.delete();
}
 
Example 22
Project: intellij-ce-playground   File: ConvertDocstringQuickFix.java   Source Code and License 6 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  PsiElement expression = descriptor.getPsiElement();
  if (expression instanceof PyStringLiteralExpression && expression.isWritable()) {
    PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project);

    String stringText = expression.getText();
    int prefixLength = PyStringLiteralExpressionImpl
      .getPrefixLength(stringText);
    String prefix = stringText.substring(0, prefixLength);
    String content = stringText.substring(prefixLength);
    if (content.startsWith("'''") ) {
      content = content.substring(3, content.length()-3);
    } else if (content.startsWith("\"\"\""))
      return;
    else {
      content = content.length() == 1 ? "" : content.substring(1, content.length()-1);
    }
    if (content.endsWith("\""))
      content = StringUtil.replaceSubstring(content, TextRange.create(content.length()-1, content.length()), "\\\"");

    PyExpression newString = elementGenerator.createDocstring(prefix+"\"\"\"" + content + "\"\"\"").getExpression();
    expression.replace(newString);
  }
}
 
Example 23
Project: intellij-ce-playground   File: PluginXmlDomInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  PsiFile file = descriptor.getPsiElement().getContainingFile();
  DomFileElement<IdeaPlugin> fileElement = DomManager.getDomManager(project).getFileElement((XmlFile)file, IdeaPlugin.class);
  if (fileElement != null) {
    IdeaPlugin root = fileElement.getRootElement();
    XmlTag after = getLastSubTag(root, root.getId(), ContainerUtil.getLastItem(root.getDescriptions()), ContainerUtil.getLastItem(root.getVersions()), root.getName());
    XmlTag rootTag = root.getXmlTag();
    XmlTag vendorTag = rootTag.createChildTag("vendor", rootTag.getNamespace(), PluginManagerMain.JETBRAINS_VENDOR, false);
    if (after == null) {
      rootTag.addSubTag(vendorTag, true);
    }
    else {
      rootTag.addAfter(vendorTag, after);
    }
  }
}
 
Example 24
Project: intellij-ce-playground   File: TypeParameterExtendsFinalClassInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(@NotNull Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (parent instanceof PsiTypeParameter) {
    final PsiTypeParameter typeParameter = (PsiTypeParameter)parent;
    replaceTypeParameterUsagesWithType(typeParameter);
    typeParameter.delete();
  }
  else if (parent instanceof PsiTypeElement) {
    final PsiTypeElement typeElement = (PsiTypeElement)parent;
    final PsiElement lastChild = typeElement.getLastChild();
    if (lastChild == null) {
      return;
    }
    typeElement.replace(lastChild);
  }
}
 
Example 25
Project: intellij-ce-playground   File: ConvertToVarargsMethodFix.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  if (!(parent instanceof PsiMethod)) {
    return;
  }
  final PsiMethod method = (PsiMethod)parent;
  final Collection<PsiElement> writtenElements = new ArrayList<PsiElement>();
  final Collection<PsiReferenceExpression> methodCalls = new ArrayList<PsiReferenceExpression>();
  writtenElements.add(method);
  for (final PsiReference reference : ReferencesSearch.search(method, method.getUseScope(), false)) {
    final PsiElement referenceElement = reference.getElement();
    if (referenceElement instanceof PsiReferenceExpression) {
      writtenElements.add(referenceElement);
      methodCalls.add((PsiReferenceExpression)referenceElement);
    }
  }
  if (!FileModificationService.getInstance().preparePsiElementsForWrite(writtenElements)) {
    return;
  }
  makeMethodVarargs(method);
  makeMethodCallsVarargs(methodCalls);
}
 
Example 26
Project: intellij-ce-playground   File: ConstantOnRHSOfComparisonInspection.java   Source Code and License 6 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiBinaryExpression expression = (PsiBinaryExpression)descriptor.getPsiElement();
  final PsiExpression rhs = expression.getROperand();
  if (rhs == null) {
    return;
  }
  final String flippedComparison = ComparisonUtils.getFlippedComparison(expression.getOperationTokenType());
  if (flippedComparison == null) {
    return;
  }
  final PsiExpression lhs = expression.getLOperand();
  final String rhsText = rhs.getText();
  final String lhsText = lhs.getText();
  PsiReplacementUtil.replaceExpression(expression, rhsText + ' ' + flippedComparison + ' ' + lhsText);
}
 
Example 27
Project: intellij-ce-playground   File: NewInstanceOfSingletonInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected GroovyFix buildFix(@NotNull final PsiElement location) {
  final GrCodeReferenceElement refElement = ((GrNewExpression)location).getReferenceElement();
  LOG.assertTrue(refElement != null);
  final GrTypeDefinition singleton = (GrTypeDefinition)refElement.resolve();
  LOG.assertTrue(singleton != null);

  return new GroovyFix() {
    @Override
    protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
      final GrExpression instanceRef =
        GroovyPsiElementFactory.getInstance(project).createExpressionFromText(singleton.getQualifiedName() + ".instance");

      final GrExpression replaced = ((GrNewExpression)location).replaceWithExpression(instanceRef, true);
      JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced);
    }

    @NotNull
    @Override
    public String getName() {
      return GroovyInspectionBundle.message("replace.new.expression.with.0.instance", singleton.getName());
    }
  };
}
 
Example 28
Project: intellij-ce-playground   File: DanglingJavadocInspection.java   Source Code and License 6 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement docComment = element.getParent();
  final StringBuilder newCommentText = new StringBuilder();
  for (PsiElement child : docComment.getChildren()) {
    if (child instanceof PsiDocToken) {
      final PsiDocToken docToken = (PsiDocToken)child;
      final IElementType tokenType = docToken.getTokenType();
      if (JavaDocTokenType.DOC_COMMENT_START.equals(tokenType)) {
        newCommentText.append("/*");
      }
      else if (!JavaDocTokenType.DOC_COMMENT_LEADING_ASTERISKS.equals(tokenType)) {
        newCommentText.append(child.getText());
      }
    }
    else {
      newCommentText.append(child.getText());
    }
  }
  final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
  final PsiComment newComment = factory.createCommentFromText(newCommentText.toString(), element);
  docComment.replace(newComment);
}
 
Example 29
Project: yii2support   File: UnusedParameterLocalQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    PsiElement item = descriptor.getPsiElement();

    PsiElement context = item.getContext();
    if (context instanceof ArrayCreationExpression) {
        ArrayCreationExpression params = (ArrayCreationExpression) item.getParent();

        PsiUtil.deleteArrayElement(item);

        if (!params.getHashElements().iterator().hasNext()) {
            if (params.getPrevSibling() instanceof PsiWhiteSpace) {
                params.getPrevSibling().delete();
            }
            params.getPrevSibling().delete();
            params.delete();
        }
    }
    if (context instanceof ParameterList && context.getParent() instanceof FunctionReference) {
        FunctionReference functionReference = (FunctionReference) context.getParent();
        if (functionReference.getName() != null && functionReference.getName().equals("compact")) {
            PsiUtil.deleteFunctionParam(item);

            if (functionReference.getParameters().length == 0) {
                PsiUtil.deleteFunctionParam(functionReference);
            }
        }
    }
}
 
Example 30
Project: yii2support   File: MissedViewLocalQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement element = descriptor.getPsiElement().getParent();
    PsiDirectory directory;
    String path = null;

    if (element instanceof StringLiteralExpression) {
        path = ((StringLiteralExpression) element).getContents();
    }

    if (path == null) {
        return;
    }

    if (path.startsWith("/")) {
        directory = ViewsUtil.getRootDirectory(element);
        path = path.substring(1);
    } else {
        directory = ViewsUtil.getContextDirectory(element);
    }

    if (directory == null) {
        return;
    }

    while (directory != null && path.contains("/")) {
        final String subdirectory = path.substring(0, path.indexOf('/'));
        path = path.substring(path.indexOf('/') + 1);

        directory = directory.findSubdirectory(subdirectory);
    }

    if (directory != null) {
        if (!path.contains(".")) {
            path = path + ".php";
        }

        final PsiFile viewPsiFile = directory.createFile(path);
        FileEditorManager.getInstance(project).openFile(viewPsiFile.getVirtualFile(), true);

        final FileTemplate[] templates = FileTemplateManager.getDefaultInstance().getTemplates(FileTemplateManager.DEFAULT_TEMPLATES_CATEGORY);
        FileTemplate template = null;
        for (FileTemplate fileTemplate : templates) {
            if (fileTemplate.getName().equals("PHP File")) {
                template = fileTemplate;
                break;
            }
        }

        if (template != null && viewPsiFile.getViewProvider().getDocument() != null) {
            final Properties properties = FileTemplateManager.getDefaultInstance().getDefaultProperties();
            template.setLiveTemplateEnabled(true);
            template.setReformatCode(true);
            try {
                viewPsiFile.getViewProvider().getDocument().insertString(0, template.getText(properties));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
Example 31
Project: yii2support   File: MissedParamQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) {
    Method method = (Method)methodReference.resolve();
    if (method != null) {
      Parameter[] parameters = method.getParameters();
      int paramParameterIndex = ClassUtils.getParamIndex(method, "params");
      int conditionParameterIndex = ClassUtils.getParamIndex(method, new String[]{ "condition", "expression", "sql"});

      if (paramParameterIndex > -1
              && conditionParameterIndex > -1
              && conditionParameterIndex == paramParameterIndex - 1
              && methodReference.getParameters().length > conditionParameterIndex) {
          String condition = methodReference.getParameters()[conditionParameterIndex].getText();
          String[] conditionParams = DatabaseUtils.extractParamsFromCondition(condition);

          ArrayCreationExpression array = null;
          if (methodReference.getParameters().length > paramParameterIndex) {
              PsiElement paramParameter = methodReference.getParameters()[paramParameterIndex];
              if (paramParameter instanceof ArrayCreationExpression)
                  array = (ArrayCreationExpression)paramParameter;
              paramParameter.delete();
          }

          TemplateManager templateManager = TemplateManager.getInstance(project);
          Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
          if (editor == null || methodReference.getParameterList() == null) return;

          editor.getCaretModel().moveToOffset(methodReference.getParameterList().getLastChild().getTextRange().getEndOffset());
          PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
          Template template = templateManager.createTemplate("", "");
          template.setToReformat(true);
          buildParamArray(template, conditionParams, array, conditionParameterIndex);

          PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
          templateManager.startTemplate(editor, template);
      }
    }

}
 
Example 32
Project: yii2support   File: MissingPropertiesQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor) {
        List<PhpDocPropertyTag> propertyTags = this.comment.getPropertyTags();

        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (editor == null)
            return;
        Document document = editor.getDocument();
        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
        TemplateManager templateManager = TemplateManager.getInstance(project);
        Template template = templateManager.createTemplate("", "");
        template.setToReformat(true);
        for (VirtualProperty missingProperty: this.missingProperties)
        {

            String propertyText = "* @property "+ (missingProperty.getType() != null ? missingProperty.getType() : "") + " $" +missingProperty.getName();
            if ( missingProperty.getComment() != null) {
                propertyText += " " + missingProperty.getComment();
            }
            template.addTextSegment("\n" + propertyText);
        }
        template.addTextSegment("\n");

        int offset =  comment.getLastChild().getTextOffset();
        if (propertyTags.size() > 0) {
            PhpDocPropertyTag phpDocPropertyTag = propertyTags.get(comment.getPropertyTags().size() - 1);
            offset = phpDocPropertyTag.getTextOffset() + phpDocPropertyTag.getTextLength();
        }
        editor.getCaretModel().moveToOffset(offset);
        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
        templateManager.startTemplate(editor, template);
}
 
Example 33
Project: yii2inspections   File: MissingTranslationsInspector.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement expression = descriptor.getPsiElement();
    if (null != expression && expression.getParent() instanceof ArrayCreationExpression) {
        final ArrayCreationExpression container = (ArrayCreationExpression) expression.getParent();
        final PsiElement closingBracket         = container.getLastChild();
        if (null == closingBracket) {
            return;
        }

        for (String translation : missing) {
            /* reach or create a comma */
            PsiElement last = closingBracket.getPrevSibling();
            if (last instanceof PsiWhiteSpace) {
                last = last.getPrevSibling();
            }
            if (null != last && PhpTokenTypes.opCOMMA != last.getNode().getElementType()) {
                last.getParent().addAfter(PhpPsiElementFactory.createComma(project), last);
                last = last.getNextSibling();
            }

            /* add a new translation */
            final String escaped                = PhpStringUtil.escapeText(translation, true, '\n', '\t');
            final String pairPattern            = "array('%s%' => '%s%')".replace("%s%", escaped).replace("%s%", escaped);
            final ArrayCreationExpression array = PhpPsiElementFactory.createFromText(project, ArrayCreationExpression.class, pairPattern);
            final PhpPsiElement pair            = null == array ? null : array.getHashElements().iterator().next();
            final PsiWhiteSpace space           = PhpPsiElementFactory.createFromText(project, PsiWhiteSpace.class, " ");
            if (null == last || null == pair || null == space) {
                continue;
            }
            last.getParent().addAfter(pair, last);
            last.getParent().addAfter(space, last);
        }
    }
}
 
Example 34
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkField(PsiField field, InspectionManager manager, boolean isOnTheFly) {
    if (isFieldMissingNullAnnotation(field, field.getType())) {
        Collection<ProblemDescriptor> problemDescriptors = Lists.newArrayList();
        createProblemDescriptorWithQuickFixes(field, manager, problemDescriptors, field);
        return problemDescriptors.isEmpty()
                ? null
                : problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()]);
    }
    return null;
}
 
Example 35
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkMethod(PsiMethod method, InspectionManager manager, boolean isOnTheFly) {
    if (isNonPrivateMethod(method)) {
        List<ProblemDescriptor> problemDescriptors = new ArrayList<>();
        List<MethodSignatureBackedByPsiMethod> superMethodSignatures = superMethods(method);
        PsiParameter[] parameters = method.getParameterList().getParameters();
        checkMethodParams(manager, problemDescriptors, superMethodSignatures, parameters);
        checkMethodReturnType(method, manager, problemDescriptors);
        return problemDescriptors.isEmpty()
                ? null
                : problemDescriptors.toArray(new ProblemDescriptor[problemDescriptors.size()]);
    }
    return null;
}
 
Example 36
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
private void checkMethodReturnType(PsiMethod method,
                                   InspectionManager manager,
                                   List<ProblemDescriptor> aProblemDescriptors) {
    if (!method.isConstructor()
            && !isIgnoredType(method.getReturnType())
            && !hasAnnotation(method)) {

        PsiTypeElement returnTypeElement = method.getReturnTypeElement();
        if (returnTypeElement == null) {
            return;
        }

        createProblemDescriptorWithQuickFixes(method, manager, aProblemDescriptors, returnTypeElement);
    }
}
 
Example 37
Project: nullability-annotations-inspection   File: NullabilityAnnotationsInspection.java   Source Code and License 5 votes vote down vote up
private void checkMethodParams(InspectionManager manager,
                               List<ProblemDescriptor> aProblemDescriptors,
                               List<MethodSignatureBackedByPsiMethod> aSuperMethodSignatures,
                               PsiParameter[] aParameters) {
    for (int i = 0, parametersLength = aParameters.length; i < parametersLength; i++) {
        PsiParameter parameter = aParameters[i];
        if (parameterNeedsAnnotation(parameter)) {
            if (!hasAnnotation(parameter) && !hasAnnotationInHierarchy(i, aSuperMethodSignatures)) {
                createProblemDescriptorWithQuickFixes(parameter, manager, aProblemDescriptors, parameter);
            }
        }
    }
}
 
Example 38
Project: laravel-insight   File: PropertyQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(
    @NotNull final Project project,
    @NotNull final ProblemDescriptor descriptor
) {
    final PhpClass primaryClass = primaryClassPointer.getElement();
    assert primaryClass != null;

    final PhpDocComment primaryClassDocComment = primaryClass.getDocComment();

    if (primaryClassDocComment != null) {
        final PhpDocProperty primaryClassProperty = PhpDocCommentUtil.findProperty(primaryClassDocComment, propertyName);

        if (!Objects.equals(primaryClassProperty, null)) {
            return;
        }
    }

    final PhpDocTag  docCommentNewTag    = PhpDocCommentUtil.createTag(primaryClass, "@property", propertyType + " $" + propertyName);
    final PsiElement docCommentReference = docCommentNewTag.getParent();

    final Navigatable navigator = PsiNavigationSupport.getInstance().getDescriptor(docCommentReference.getNavigationElement());
    if (navigator != null) {
        navigator.navigate(true);

        final Editor selectedTextEditor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (selectedTextEditor != null) {
            final int startOffset = docCommentNewTag.getTextOffset() + 10;
            final int endOffset   = startOffset + propertyType.length();

            selectedTextEditor.getSelectionModel().setSelection(startOffset, endOffset);
            selectedTextEditor.getCaretModel().moveToOffset(endOffset);
        }
    }
}
 
Example 39
Project: idea-php-dotenv-plugin   File: DuplicateKeyInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    if(!(file instanceof DotEnvFile)) {
        return null;
    }

    return analyzeFile(file, manager, isOnTheFly).getResultsArray();
}
 
Example 40
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(
    final @NotNull PsiFile file,
    final @NotNull InspectionManager manager,
    final boolean isOnTheFly
) {
    if (!TypeSystemUtils.isTypeSystemXmlFile(file)) {
        return null;
    }
    final XmlFile xmlFile = (XmlFile) file;

    if (!TypeSystemValidationUtils.isCustomExtensionFile(file)) {
        return null;
    }

    final ValidateContext sharedContext = ValidateContextImpl.createFileContext(manager, isOnTheFly, xmlFile);
    if (sharedContext == null) {
        return null;
    }

    final List<ProblemDescriptor> result = new ArrayList<>();
    for (XmlRule nextRule : this.getRules()) {
        try {
            this.validateOneRule(nextRule, sharedContext, result);
        } catch (XPathExpressionException e) {
            result.add(this.createValidationFailedProblem(sharedContext, xmlFile, nextRule, e));
        }
    }

    return result.toArray(new ProblemDescriptor[result.size()]);
}
 
Example 41
Project: hybris-integration-intellij-idea-plugin   File: XmlRuleInspection.java   Source Code and License 5 votes vote down vote up
protected ProblemDescriptor createValidationFailedProblem(
    @NotNull final ValidateContext context,
    @NotNull final PsiElement file,
    @NotNull final XmlRule failedRule,
    @NotNull final Exception failure
) {

    return context.getManager().createProblemDescriptor(
        file,
        "XmlRule '" + failedRule.getID() + "' has failed to validate: " + failure.getMessage(),
        true,
        ProblemHighlightType.GENERIC_ERROR,
        context.isOnTheFly()
    );
}
 
Example 42
Project: roc-completion   File: QuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor problemDescriptor)
{
    PsiElement problemElement = problemDescriptor.getPsiElement();
    PsiElement parent = getParentProperty(problemElement);

    // If there are still other settings present, just remove this one.
    if (childCount(parent) > 1)
    {
        problemElement.delete();

        CodeStyleManager
            .getInstance(project)
            .adjustLineIndent(parent.getContainingFile(), parent.getTextRange());

        return;
    }

    // Navigate upwards until a node containing more than one setting is found.
    while (true)
    {
        PsiElement nextParent = getParentProperty(parent);

        if (nextParent == null || childCount(nextParent) != 1)
        {
            // Remove entire unused tree.
            parent.delete();
            return;
        }

        parent = nextParent;
    }
}
 
Example 43
Project: intellij-csv-validator   File: CsvValidationInspection.java   Source Code and License 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        String text = document.getText();
        document.setText(text.substring(0, element.getTextOffset()) + CsvCodeStyleSettings.getCurrentSeparator(project) + text.substring(element.getTextOffset()));
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 44
Project: intellij-csv-validator   File: CsvValidationInspection.java   Source Code and License 5 votes vote down vote up
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    try {
        PsiElement element = descriptor.getPsiElement();
        Document document = PsiDocumentManager.getInstance(project).getDocument(element.getContainingFile());
        document.setText(document.getText() + "\"");
    } catch (IncorrectOperationException e) {
        LOG.error(e);
    }
}
 
Example 45
Project: intellij-ce-playground   File: ReturnOfCollectionFieldInspection.java   Source Code and License 5 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  if (!(element instanceof PsiReferenceExpression)) {
    return;
  }
  final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element;
  fixContainingMethodReturnType(referenceExpression);
  PsiReplacementUtil.replaceExpressionAndShorten(referenceExpression, myReplacementText);
}
 
Example 46
Project: intellij-ce-playground   File: GrUnusedIncDecInspection.java   Source Code and License 5 votes vote down vote up
@Nullable
private static GrUnaryExpression findUnaryExpression(ProblemDescriptor descriptor) {
  GrUnaryExpression expr;
  PsiElement element = descriptor.getPsiElement();
  if (element == null) return null;
  PsiElement parent = element.getParent();
  IElementType opType = element.getNode().getElementType();
  if (opType != GroovyTokenTypes.mINC && opType != GroovyTokenTypes.mDEC) return null;
  if (!(parent instanceof GrUnaryExpression)) return null;
  expr = (GrUnaryExpression)parent;
  return expr;
}
 
Example 47
Project: intellij-ce-playground   File: RenameParameterFix.java   Source Code and License 5 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement nameIdentifier = descriptor.getPsiElement();
  final PsiElement elementToRename = nameIdentifier.getParent();
  final RefactoringFactory factory =
    RefactoringFactory.getInstance(project);
  final RenameRefactoring renameRefactoring =
    factory.createRename(elementToRename, m_targetName);
  renameRefactoring.setSearchInComments(false);
  renameRefactoring.setSearchInNonJavaFiles(false);
  renameRefactoring.run();
}
 
Example 48
Project: yii2inspections   File: MissingTranslationsInspector.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
    final PsiElement expression = descriptor.getPsiElement();
    if (null != expression && expression.getParent() instanceof ArrayCreationExpression) {
        final ArrayCreationExpression container = (ArrayCreationExpression) expression.getParent();
        final PsiElement closingBracket         = container.getLastChild();
        if (null == closingBracket) {
            return;
        }

        for (String translation : missing) {
            /* reach or create a comma */
            PsiElement last = closingBracket.getPrevSibling();
            if (last instanceof PsiWhiteSpace) {
                last = last.getPrevSibling();
            }
            if (null != last && PhpTokenTypes.opCOMMA != last.getNode().getElementType()) {
                last.getParent().addAfter(PhpPsiElementFactory.createComma(project), last);
                last = last.getNextSibling();
            }

            /* add a new translation */
            final String escaped                = PhpStringUtil.escapeText(translation, true, '\n', '\t');
            final String pairPattern            = "array('%s%' => '%s%')".replace("%s%", escaped).replace("%s%", escaped);
            final ArrayCreationExpression array = PhpPsiElementFactory.createFromText(project, ArrayCreationExpression.class, pairPattern);
            final PhpPsiElement pair            = null == array ? null : array.getHashElements().iterator().next();
            final PsiWhiteSpace space           = PhpPsiElementFactory.createFromText(project, PsiWhiteSpace.class, " ");
            if (null == last || null == pair || null == space) {
                continue;
            }
            last.getParent().addAfter(pair, last);
            last.getParent().addAfter(space, last);
        }
    }
}
 
Example 49
Project: intellij-ce-playground   File: GenerateToStringQuickFix.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor desc) {
  final PsiClass clazz = PsiTreeUtil.getParentOfType(desc.getPsiElement(), PsiClass.class);
  if (clazz == null) {
    return; // no class to fix
  }
  GenerateToStringActionHandler handler = ServiceManager.getService(GenerateToStringActionHandler.class);
  handler.executeActionQuickFix(project, clazz);
}
 
Example 50
Project: intellij-ce-playground   File: CharUsedInArithmeticContextInspection.java   Source Code and License 5 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  if (!(element instanceof PsiExpression)) {
    return;
  }
  final PsiExpression expression = (PsiExpression)element;
  final String expressionText = expression.getText();
  PsiReplacementUtil.replaceExpression(expression, '(' + typeText + ')' + expressionText);
}
 
Example 51
Project: intellij-ce-playground   File: DomHighlightingHelperImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull final Project project, @NotNull final ProblemDescriptor descriptor) {
  XmlTag tag = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), XmlTag.class, false);
  if (tag != null) {
    doFix(tag);
  }
}
 
Example 52
Project: intellij-ce-playground   File: ReturnOfDateFieldInspection.java   Source Code and License 5 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  if (!(element instanceof PsiReferenceExpression)) {
    return;
  }
  final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)element;
  final String type =
    TypeUtils.expressionHasTypeOrSubtype(referenceExpression, CommonClassNames.JAVA_UTIL_DATE, CommonClassNames.JAVA_UTIL_CALENDAR);
  if (type == null) {
    return;
  }
  PsiReplacementUtil.replaceExpression(referenceExpression, '(' + type + ')' + referenceExpression.getText() + ".clone()");
}
 
Example 53
Project: intellij-ce-playground   File: AndroidNonConstantResIdsInSwitchInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  if (element == null) {
    return;
  }

  final PsiSwitchStatement switchStatement = PsiTreeUtil.getParentOfType(element, PsiSwitchStatement.class);
  if (switchStatement == null) {
    return;
  }

  ConvertSwitchToIfIntention.doProcessIntention(switchStatement); 
}
 
Example 54
Project: intellij-ce-playground   File: CStyleArrayDeclarationInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement().getParent();
  if (element instanceof PsiVariable) {
    final PsiVariable variable = (PsiVariable)element;
    variable.normalizeDeclaration();
    CodeStyleManager.getInstance(project).reformat(variable);
  }
  else if (element instanceof PsiMethod) {
    final PsiMethod method = (PsiMethod)element;
    final PsiTypeElement returnTypeElement = method.getReturnTypeElement();
    if (returnTypeElement == null) {
      return;
    }
    final PsiType returnType = method.getReturnType();
    if (returnType == null) {
      return;
    }
    PsiElement child = method.getParameterList();
    while (!(child instanceof PsiCodeBlock)) {
      final PsiElement element1 = child;
      child = child.getNextSibling();
      if (element1 instanceof PsiJavaToken) {
        final PsiJavaToken token = (PsiJavaToken)element1;
        final IElementType tokenType = token.getTokenType();
        if (JavaTokenType.LBRACKET.equals(tokenType) || JavaTokenType.RBRACKET.equals(tokenType)) {
          token.delete();
        }
      }
    }
    final PsiTypeElement typeElement = JavaPsiFacade.getElementFactory(project).createTypeElement(returnType);
    returnTypeElement.replace(typeElement);
  }
}
 
Example 55
Project: intellij-ce-playground   File: AssignmentUsedAsConditionInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiAssignmentExpression expression = (PsiAssignmentExpression)descriptor.getPsiElement();
  final PsiExpression leftExpression = expression.getLExpression();
  final PsiExpression rightExpression = expression.getRExpression();
  assert rightExpression != null;
  final String newExpression = leftExpression.getText() + "==" + rightExpression.getText();
  PsiReplacementUtil.replaceExpression(expression, newExpression);
}
 
Example 56
Project: intellij-ce-playground   File: SameParameterValueInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull final Project project, @NotNull ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  final PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
  if (method == null) return;
  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);
}
 
Example 57
Project: intellij-ce-playground   File: ArrayHashCodeInspection.java   Source Code and License 5 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement element = descriptor.getPsiElement();
  final PsiElement parent = element.getParent();
  final PsiElement grandParent = parent.getParent();
  if (!(grandParent instanceof PsiMethodCallExpression)) {
    return;
  }
  final PsiMethodCallExpression methodCallExpression =
    (PsiMethodCallExpression)grandParent;
  final PsiReferenceExpression methodExpression =
    methodCallExpression.getMethodExpression();
  final PsiExpression qualifier =
    methodExpression.getQualifierExpression();
  if (qualifier == null) {
    return;
  }
  @NonNls final StringBuilder newExpressionText = new StringBuilder();
  if (deepHashCode) {
    newExpressionText.append("java.util.Arrays.deepHashCode(");
  }
  else {
    newExpressionText.append("java.util.Arrays.hashCode(");
  }
  newExpressionText.append(qualifier.getText());
  newExpressionText.append(')');
  PsiReplacementUtil.replaceExpressionAndShorten(methodCallExpression,
                                                 newExpressionText.toString());
}
 
Example 58
Project: intellij-ce-playground   File: TooBroadCatchInspection.java   Source Code and License 5 votes vote down vote up
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
  final PsiElement element = descriptor.getPsiElement();
  if (!(element instanceof PsiTypeElement)) {
    return;
  }
  final PsiTypeElement typeElement = (PsiTypeElement)element;
  final PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
  final PsiClassType type = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION);
  final PsiTypeElement newTypeElement = factory.createTypeElement(type);
  typeElement.replace(newTypeElement);
}
 
Example 59
Project: intellij-ce-playground   File: UnusedLabelInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void doFix(Project project, ProblemDescriptor descriptor)
  throws IncorrectOperationException {
  final PsiElement label = descriptor.getPsiElement();
  final PsiLabeledStatement labeledStatement =
    (PsiLabeledStatement)label.getParent();
  assert labeledStatement != null;
  final PsiStatement statement = labeledStatement.getStatement();
  if (statement == null) {
    return;
  }
  final String statementText = statement.getText();
  PsiReplacementUtil.replaceStatement(labeledStatement, statementText);
}
 
Example 60
Project: intellij-ce-playground   File: UnsafeReturnStatementVisitorInspection.java   Source Code and License 5 votes vote down vote up
@Override
public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
  PsiElement element = descriptor.getPsiElement();
  if (element instanceof PsiClass) {
    FileModificationService.getInstance().preparePsiElementsForWrite(element);
    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
    for (String method : myMethods) {
      element.add(factory.createMethodFromText(method, element));
    }
  }
}