com.intellij.psi.util.PsiTypesUtil Java Examples

The following examples show how to use com.intellij.psi.util.PsiTypesUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReplaceConditionalWithPolymorphism.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
private void replaceCastExpressionWithThisExpression(List<PsiExpression> oldCastExpressions,
                                                     List<PsiExpression> newCastExpressions,
                                                     PsiClass subclassTypeDeclaration) {
    int j = 0;
    for (PsiExpression expression : oldCastExpressions) {
        PsiTypeCastExpression castExpression = (PsiTypeCastExpression) expression;
        if (castExpression.getCastType().getType().equals(PsiTypesUtil.getClassType(subclassTypeDeclaration))) {
            if (castExpression.getOperand() instanceof PsiReferenceExpression) {
                PsiReferenceExpression castSimpleName = (PsiReferenceExpression) castExpression.getOperand();
                if (typeVariable != null && typeVariable.equals(castSimpleName.resolve())) {
                    newCastExpressions.get(j).replace(elementFactory.createExpressionFromText("this", null));
                }
            } else if (castExpression.getOperand() instanceof PsiMethodCallExpression) {
                PsiMethodCallExpression castMethodInvocation = (PsiMethodCallExpression) castExpression.getOperand();
                if (typeMethodInvocation != null && typeMethodInvocation.resolveMethod().equals(castMethodInvocation.resolveMethod())) { // TODO: not sure if it works correctly
                    newCastExpressions.get(j).replace(elementFactory.createExpressionFromText("this", null));
                }
            }
        }
        j++;
    }
}
 
Example #2
Source File: IocBeanInterfaceLineMarkerProvider.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public LineMarkerInfo getLineMarkerInfo(@NotNull PsiElement psiElement) {
    try {
        PsiField psiFiled = this.getPsiFiled(psiElement);
        PsiAnnotation psiAnnotation = this.getPsiAnnotation(psiFiled);
        if (psiFiled != null && psiAnnotation != null) {
            GlobalSearchScope moduleScope = psiElement.getResolveScope();
            PsiTypeElementImpl psiTypeElement = this.getPsiTypeElement(psiAnnotation);
            PsiClass psiClass = PsiTypesUtil.getPsiClass(psiTypeElement.getType());
            String name = psiClass.getName();
            List<PsiElement> list = this.getImplListElements(name, psiClass.getQualifiedName(), psiElement, moduleScope);
            if (CollectionUtils.isNotEmpty(list)) {
                return new LineMarkerInfo<>(psiTypeElement, psiTypeElement.getTextRange(), icon,
                        new FunctionTooltip(MessageFormat.format("快速跳转至 {0} 的 @IocBean 实现类", name)),
                        new IocBeanInterfaceNavigationHandler(name, list),
                        GutterIconRenderer.Alignment.LEFT);
            }
        }
    } catch (Exception e) {
    }
    return null;
}
 
Example #3
Source File: TypeCheckElimination.java    From IntelliJDeodorant with MIT License 5 votes vote down vote up
private boolean typeCheckClassPartOfExistingInheritanceTree() {
    Collection<List<PsiType>> subTypeCollection = subclassTypeMap.values();
    for (List<PsiType> subTypes : subTypeCollection) {
        for (PsiType subType : subTypes) {
            if (subType.equals(PsiTypesUtil.getClassType(getTypeCheckClass()))) {
                return true;
            }
        }
    }
    return false;
}
 
Example #4
Source File: PsiEventDeclarationsExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
static EventDeclarationModel getEventDeclarationModel(
    PsiClassObjectAccessExpression psiExpression) {
  PsiType valueType = psiExpression.getOperand().getType();
  PsiClass valueClass = PsiTypesUtil.getPsiClass(valueType);

  return new EventDeclarationModel(
      PsiTypeUtils.guessClassName(valueType.getCanonicalText()),
      getReturnType(valueClass),
      getFields(valueClass),
      psiExpression);
}
 
Example #5
Source File: PsiUtils.java    From data-mediator with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given type is an implementer of the given canonicalName with the given typed parameters
 *
 * @param type                what we're checking against
 * @param canonicalName       the type must extend/implement this generic
 * @param canonicalParamNames the type that the generic(s) must be (in this order)
 * @return
 */
public static boolean isTypedClass(PsiType type, String canonicalName, String... canonicalParamNames) {
    PsiClass parameterClass = PsiTypesUtil.getPsiClass(type);

    if (parameterClass == null) {
        return false;
    }

    // This is a safe cast, for if parameterClass != null, the type was checked in PsiTypesUtil#getPsiClass(...)
    PsiClassType pct = (PsiClassType) type;

    // Main class name doesn't match; exit early
    if (!canonicalName.equals(parameterClass.getQualifiedName())) {
        return false;
    }

    List<PsiType> psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());

    for (int i = 0; i < canonicalParamNames.length; i++) {
        if (!isOfType(psiTypes.get(i), canonicalParamNames[i])) {
            return false;
        }
    }

    // Passed all screenings; must be a match!
    return true;
}
 
Example #6
Source File: EqualsAndHashCodeProcessor.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
private PsiMethod createCanEqualMethod(@NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation) {
  final PsiManager psiManager = psiClass.getManager();

  final String blockText = String.format("return other instanceof %s;", PsiTypesUtil.getClassType(psiClass).getCanonicalText());
  final LombokLightMethodBuilder methodBuilder = new LombokLightMethodBuilder(psiManager, CAN_EQUAL_METHOD_NAME)
    .withModifier(PsiModifier.PROTECTED)
    .withMethodReturnType(PsiType.BOOLEAN)
    .withContainingClass(psiClass)
    .withNavigationElement(psiAnnotation)
    .withFinalParameter("other", PsiType.getJavaLangObject(psiManager, psiClass.getResolveScope()));
  methodBuilder.withBody(PsiMethodUtil.createCodeBlockFromText(blockText, methodBuilder));
  return methodBuilder;
}
 
Example #7
Source File: DelegateHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean validateRecursion(PsiType psiType, ProblemBuilder builder) {
  final PsiClass psiClass = PsiTypesUtil.getPsiClass(psiType);
  if (null != psiClass) {
    final DelegateAnnotationElementVisitor delegateAnnotationElementVisitor = new DelegateAnnotationElementVisitor(psiType, builder);
    psiClass.acceptChildren(delegateAnnotationElementVisitor);
    return delegateAnnotationElementVisitor.isValid();
  }
  return true;
}
 
Example #8
Source File: PsiUtils.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given type is an implementer of the given canonicalName with the given typed parameters
 *
 * @param type                what we're checking against
 * @param canonicalName       the type must extend/implement this generic
 * @param canonicalParamNames the type that the generic(s) must be (in this order)
 * @return
 */
public static boolean isTypedClass(PsiType type, String canonicalName, String... canonicalParamNames) {
    PsiClass parameterClass = PsiTypesUtil.getPsiClass(type);

    if (parameterClass == null) {
        return false;
    }

    // This is a safe cast, for if parameterClass != null, the type was checked in PsiTypesUtil#getPsiClass(...)
    PsiClassType pct = (PsiClassType) type;

    // Main class name doesn't match; exit early
    if (!canonicalName.equals(parameterClass.getQualifiedName())) {
        return false;
    }

    List<PsiType> psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());

    for (int i = 0; i < canonicalParamNames.length; i++) {
        if (!isOfType(psiTypes.get(i), canonicalParamNames[i])) {
            return false;
        }
    }

    // Passed all screenings; must be a match!
    return true;
}
 
Example #9
Source File: ElementUtils.java    From aircon with MIT License 4 votes vote down vote up
public static String getQualifiedName(final PsiType type) {
	final PsiClass psiClass = PsiTypesUtil.getPsiClass(type);
	return psiClass != null ? psiClass.getQualifiedName() : JAVA_LANG_PACKAGE + type.getPresentableText();
}
 
Example #10
Source File: ReplaceConditionalWithPolymorphism.java    From IntelliJDeodorant with MIT License 4 votes vote down vote up
private PsiMethod createPolymorphicMethodHeader() {
    String methodName = typeCheckElimination.getAbstractMethodName();
    PsiType returnType = PsiType.VOID;

    if (returnedVariable != null) {
        returnType = returnedVariable.getType();
    } else if (typeCheckElimination.typeCheckCodeFragmentContainsReturnStatement()) { // TODO: looks really suspicious
        returnType = typeCheckElimination.getTypeCheckMethodReturnType();
    }

    PsiMethod createdMethod = elementFactory.createMethod(methodName, returnType);
    PsiUtil.setModifierProperty(createdMethod, PsiModifier.PUBLIC, true);

    PsiParameterList abstractMethodParameters = createdMethod.getParameterList();
    if (returnedVariable != null && !typeCheckElimination.returnedVariableDeclaredAndReturnedInBranches()) {
        abstractMethodParameters.add(elementFactory.createParameter(returnedVariable.getName(), returnedVariable.getType()));
    }
    for (PsiParameter accessedParameter : typeCheckElimination.getAccessedParameters()) {
        if (!accessedParameter.equals(returnedVariable) && !accessedParameter.equals(typeVariable)) {
            abstractMethodParameters.add(elementFactory.createParameter(accessedParameter.getName(), accessedParameter.getType()));
        }
    }
    for (PsiVariable fragment : typeCheckElimination.getAccessedLocalVariables()) {
        if (!fragment.equals(returnedVariable) && !fragment.equals(typeVariable)) {
            abstractMethodParameters.add(elementFactory.createParameter(fragment.getName(), fragment.getType()));
        }
    }

    if (sourceTypeRequiredForExtraction()) {
        String parameterName = sourceTypeDeclaration.getName();
        parameterName = parameterName.substring(0, 1).toLowerCase() + parameterName.substring(1);
        PsiType parameterType = PsiTypesUtil.getClassType(sourceTypeDeclaration);
        abstractMethodParameters.add(elementFactory.createParameter(parameterName, parameterType));
    }

    PsiReferenceList abstractMethodThrownExceptionsRewrite = createdMethod.getThrowsList();
    for (PsiClassType typeBinding : thrownExceptions) {
        abstractMethodThrownExceptionsRewrite.add(elementFactory.createReferenceElementByType(typeBinding));
    }
    return createdMethod;
}
 
Example #11
Source File: EqualsAndHashCodeProcessor.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String createEqualsBlockString(@NotNull PsiClass psiClass, @NotNull PsiAnnotation psiAnnotation, boolean hasCanEqualMethod, Collection<MemberInfo> memberInfos) {
  final boolean callSuper = readCallSuperAnnotationOrConfigProperty(psiAnnotation, psiClass, ConfigKey.EQUALSANDHASHCODE_CALL_SUPER);
  final boolean doNotUseGetters = readAnnotationOrConfigProperty(psiAnnotation, psiClass, "doNotUseGetters", ConfigKey.EQUALSANDHASHCODE_DO_NOT_USE_GETTERS);

  final String canonicalClassName = PsiTypesUtil.getClassType(psiClass).getCanonicalText();
  final String canonicalWildcardClassName = PsiClassUtil.getWildcardClassType(psiClass).getCanonicalText();

  final StringBuilder builder = new StringBuilder();

  builder.append("if (o == this) return true;\n");
  builder.append("if (!(o instanceof ").append(canonicalClassName).append(")) return false;\n");
  builder.append("final ").append(canonicalWildcardClassName).append(" other = (").append(canonicalWildcardClassName).append(")o;\n");

  if (hasCanEqualMethod) {
    builder.append("if (!other.canEqual((java.lang.Object)this)) return false;\n");
  }
  if (callSuper) {
    builder.append("if (!super.equals(o)) return false;\n");
  }

  EqualsAndHashCodeToStringHandler handler = getEqualsAndHashCodeToStringHandler();
  for (MemberInfo memberInfo : memberInfos) {
    final String memberAccessor = handler.getMemberAccessorName(memberInfo, doNotUseGetters, psiClass);

    final PsiType memberType = memberInfo.getType();
    if (memberType instanceof PsiPrimitiveType) {
      if (PsiType.FLOAT.equals(memberType)) {
        builder.append("if (java.lang.Float.compare(this.").append(memberAccessor).append(", other.").append(memberAccessor).append(") != 0) return false;\n");
      } else if (PsiType.DOUBLE.equals(memberType)) {
        builder.append("if (java.lang.Double.compare(this.").append(memberAccessor).append(", other.").append(memberAccessor).append(") != 0) return false;\n");
      } else {
        builder.append("if (this.").append(memberAccessor).append(" != other.").append(memberAccessor).append(") return false;\n");
      }
    } else if (memberType instanceof PsiArrayType) {
      final PsiType componentType = ((PsiArrayType) memberType).getComponentType();
      if (componentType instanceof PsiPrimitiveType) {
        builder.append("if (!java.util.Arrays.equals(this.").append(memberAccessor).append(", other.").append(memberAccessor).append(")) return false;\n");
      } else {
        builder.append("if (!java.util.Arrays.deepEquals(this.").append(memberAccessor).append(", other.").append(memberAccessor).append(")) return false;\n");
      }
    } else {
      final String memberName = memberInfo.getName();
      builder.append("final java.lang.Object this$").append(memberName).append(" = this.").append(memberAccessor).append(";\n");
      builder.append("final java.lang.Object other$").append(memberName).append(" = other.").append(memberAccessor).append(";\n");
      builder.append("if (this$").append(memberName).append(" == null ? other$").append(memberName).append(" != null : !this$")
        .append(memberName).append(".equals(other$").append(memberName).append(")) return false;\n");
    }
  }
  builder.append("return true;\n");
  return builder.toString();
}