@NotNull private String createConversionForExpression( @Nullable PsiExpression expression, @NotNull PsiType expectedType) { String conversion = ""; if (expression != null) { PsiType actualType = expression.getType(); boolean isPrimitiveTypeOrNull = actualType == null || Node.PRIMITIVE_TYPES.contains(actualType.getCanonicalText()); boolean isRef = (expression instanceof PsiReferenceExpression && ((PsiReferenceExpression) expression).isQualified() || expression instanceof PsiMethodCallExpression); boolean containsQuestDot = expressionToExpression(expression).toKotlin().contains("?."); if (isPrimitiveTypeOrNull && isRef && containsQuestDot) { conversion += "!!"; } if (actualType != null) { if (isConversionNeeded(actualType, expectedType)) { conversion += getPrimitiveTypeConversion(expectedType.getCanonicalText()); } } } return conversion; }
@Nullable @Override protected List<ClosureParameterInfo> getParameterInfos( InsertionContext context, PsiMethod method, PsiSubstitutor substitutor, Document document, int offset, PsiElement parent) { final String name = method.getName(); if (!"eachWithIndex".equals(name)) return null; if (method instanceof GrGdkMethod) method = ((GrGdkMethod) method).getStaticMethod(); final PsiClass containingClass = method.getContainingClass(); if (containingClass == null) return null; final String qname = containingClass.getQualifiedName(); if (!GroovyCommonClassNames.DEFAULT_GROOVY_METHODS.equals(qname)) return null; final PsiParameter[] parameters = method.getParameterList().getParameters(); if (parameters.length != 2) return null; final PsiType type = parameters[0].getType(); final PsiType collection = substitutor.substitute(type); final PsiType iterable = getIteratedType(parent, collection); if (iterable != null) { return Arrays.asList( new ClosureParameterInfo(iterable.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } if (InheritanceUtil.isInheritor(collection, CommonClassNames.JAVA_UTIL_MAP)) { final PsiType[] typeParams = ((PsiClassType) collection).getParameters(); final Project project = context.getProject(); final PsiClass entry = JavaPsiFacade.getInstance(project) .findClass("java.util.Map.Entry", parent.getResolveScope()); if (entry == null) return null; final PsiClassType entryType = JavaPsiFacade.getElementFactory(project).createType(entry, typeParams); return Arrays.asList( new ClosureParameterInfo(entryType.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); } return Arrays.asList( new ClosureParameterInfo(collection.getCanonicalText(), "entry"), new ClosureParameterInfo("int", "i")); }
public static boolean typesAreEquivalent(@Nullable PsiType type1, @Nullable PsiType type2) { if (type1 == null) { return type2 == null; } if (type2 == null) { return false; } final String type1Text = type1.getCanonicalText(); final String type2Text = type2.getCanonicalText(); return type1Text.equals(type2Text); }
@Nullable private static PsiType getLeastUpperBoundForNumericType( @NotNull PsiType lType, @NotNull PsiType rType) { String lCanonical = lType.getCanonicalText(); String rCanonical = rType.getCanonicalText(); if (JAVA_LANG_FLOAT.equals(lCanonical)) lCanonical = JAVA_LANG_DOUBLE; if (JAVA_LANG_FLOAT.equals(rCanonical)) rCanonical = JAVA_LANG_DOUBLE; if (TYPE_TO_RANK.containsKey(lCanonical) && TYPE_TO_RANK.containsKey(rCanonical)) { return TYPE_TO_RANK.get(lCanonical) > TYPE_TO_RANK.get(rCanonical) ? lType : rType; } return null; }
@NotNull @Override public PsiMethod createMethod(@NotNull final String name, final PsiType returnType) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(returnType)) { throw new IncorrectOperationException("Cannot create method with type \"null\"."); } final String canonicalText = returnType.getCanonicalText(); final PsiJavaFile aFile = createDummyJavaFile("class _Dummy_ { public " + canonicalText + " " + name + "() {} }"); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException( "Class was not created. Method name: " + name + "; return type: " + canonicalText); } final PsiMethod[] methods = classes[0].getMethods(); if (methods.length < 1) { throw new IncorrectOperationException( "Method was not created. Method name: " + name + "; return type: " + canonicalText); } PsiMethod method = methods[0]; method = (PsiMethod) JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(method); return (PsiMethod) CodeStyleManager.getInstance(myManager.getProject()).reformat(method); }
@NotNull @Override public PsiField createField(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException { PsiUtil.checkIsIdentifier(myManager, name); if (PsiType.NULL.equals(type)) { throw new IncorrectOperationException("Cannot create field with type \"null\"."); } @NonNls final String text = "class _Dummy_ { private " + type.getCanonicalText() + " " + name + "; }"; final PsiJavaFile aFile = createDummyJavaFile(text); final PsiClass[] classes = aFile.getClasses(); if (classes.length < 1) { throw new IncorrectOperationException("Class was not created " + text); } final PsiClass psiClass = classes[0]; final PsiField[] fields = psiClass.getFields(); if (fields.length < 1) { throw new IncorrectOperationException("Field was not created " + text); } PsiField field = fields[0]; field = (PsiField) JavaCodeStyleManager.getInstance(myManager.getProject()).shortenClassReferences(field); return (PsiField) CodeStyleManager.getInstance(myManager.getProject()).reformat(field); }
public String calcGenerics(@NotNull PsiElement context, InsertionContext insertionContext) { if (insertionContext.getCompletionChar() == '<') { return ""; } assert context.isValid(); if (myDiamond) { return "<>"; } if (getObject() instanceof PsiClass) { PsiClass psiClass = (PsiClass) getObject(); PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(psiClass.getProject()).getResolveHelper(); PsiSubstitutor substitutor = getSubstitutor(); StringBuilder builder = new StringBuilder(); for (PsiTypeParameter parameter : psiClass.getTypeParameters()) { PsiType substitute = substitutor.substitute(parameter); if (substitute == null || (PsiUtil.resolveClassInType(substitute) == parameter && resolveHelper.resolveReferencedClass(parameter.getName(), context) != CompletionUtil.getOriginalOrSelf(parameter))) { return ""; } if (builder.length() > 0) { builder.append(", "); } builder.append(substitute.getCanonicalText()); } if (builder.length() > 0) { return "<" + builder + ">"; } } return ""; }
@Nullable private static String getTypeText(GrVariable var) { final PsiType type = var.getTypeGroovy(); if (type == null) return null; return type.getCanonicalText(); }
public static boolean isNumericType(@Nullable PsiType type) { if (type instanceof PsiClassType) { return TYPE_TO_RANK.contains(type.getCanonicalText()); } return type instanceof PsiPrimitiveType && TypeConversionUtil.isNumericType(type); }
public static String[] getParameterString(ExtractInfoHelper helper, boolean useCanonicalText) { int i = 0; ParameterInfo[] infos = helper.getParameterInfos(); int number = 0; for (ParameterInfo info : infos) { if (info.passAsParameter()) number++; } ArrayList<String> params = new ArrayList<String>(); for (ParameterInfo info : infos) { if (info.passAsParameter()) { PsiType paramType = info.getType(); final PsiPrimitiveType unboxed = PsiPrimitiveType.getUnboxedType(paramType); if (unboxed != null) paramType = unboxed; String paramTypeText; if (paramType == null || paramType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) { paramTypeText = ""; } else { paramTypeText = (useCanonicalText ? paramType.getCanonicalText() : paramType.getPresentableText()) + " "; } params.add(paramTypeText + info.getName() + (i < number - 1 ? ", " : "")); i++; } } return ArrayUtil.toStringArray(params); }
private static String gettext(PsiField field, PsiType uiComponentType) { return UIDesignerBundle.message( "action.change.field.type", field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()); }
@Override public void visitNewExpression(@NotNull PsiNewExpression expression) { if (!PsiUtil.isLanguageLevel5OrHigher(expression)) { return; } super.visitNewExpression(expression); final PsiType type = expression.getType(); if (type == null) { return; } final String canonicalText = type.getCanonicalText(); if (!cachedNumberTypes.contains(canonicalText)) { return; } final PsiClass aClass = ClassUtils.getContainingClass(expression); if (aClass != null && cachedNumberTypes.contains(aClass.getQualifiedName())) { return; } final PsiExpressionList argumentList = expression.getArgumentList(); if (argumentList == null) { return; } final PsiExpression[] arguments = argumentList.getExpressions(); if (arguments.length != 1) { return; } final PsiExpression argument = arguments[0]; final PsiType argumentType = argument.getType(); if (argumentType == null || argumentType.equalsToText("java.lang.String")) { return; } registerError(expression, expression); }
@NotNull @Override public PsiCatchSection createCatchSection( @NotNull final PsiType exceptionType, @NotNull final String exceptionName, @Nullable final PsiElement context) throws IncorrectOperationException { if (!(exceptionType instanceof PsiClassType || exceptionType instanceof PsiDisjunctionType)) { throw new IncorrectOperationException("Unexpected type:" + exceptionType); } @NonNls final String text = "catch (" + exceptionType.getCanonicalText() + " " + exceptionName + ") {}"; final DummyHolder holder = DummyHolderFactory.createHolder( myManager, new JavaDummyElement(text, CATCH_SECTION, level(context)), context); final PsiElement element = SourceTreeToPsiMap.treeElementToPsi(holder.getTreeElement().getFirstChildNode()); if (!(element instanceof PsiCatchSection)) { throw new IncorrectOperationException( "Incorrect catch section '" + text + "'. Parsed element: " + element); } final Project project = myManager.getProject(); final JavaPsiImplementationHelper helper = JavaPsiImplementationHelper.getInstance(project); helper.setupCatchBlock(exceptionName, exceptionType, context, (PsiCatchSection) element); final CodeStyleManager styleManager = CodeStyleManager.getInstance(project); final PsiCatchSection catchSection = (PsiCatchSection) styleManager.reformat(element); GeneratedMarkerVisitor.markGenerated(catchSection); return catchSection; }
public static boolean isTypeConvertible(PsiType to, PsiExpression from) { if (from != null) for (String methodName : OOMethods.valueOf) if (resolveMethod( from.getProject(), from.getContext(), to.getCanonicalText(), methodName, from) != null) return true; return false; }
@NotNull @Override public PsiMethod createMethod( @NotNull @NonNls String name, PsiType returnType, PsiElement context) throws IncorrectOperationException { return createMethodFromText( "public " + returnType.getCanonicalText(true) + " " + name + "() {}", context); }
private static void generateVariableNameByTypeInner( PsiType type, Set<String> possibleNames, NameValidator validator) { String unboxed = PsiTypesUtil.unboxIfPossible(type.getCanonicalText()); if (unboxed != null && !unboxed.equals(type.getCanonicalText())) { String name = generateNameForBuiltInType(unboxed); name = validator.validateName(name, true); if (GroovyNamesUtil.isIdentifier(name)) { possibleNames.add(name); } } else if (type instanceof PsiIntersectionType) { for (PsiType psiType : ((PsiIntersectionType) type).getConjuncts()) { generateByType(psiType, possibleNames, validator); } } else { generateByType(type, possibleNames, validator); } }
public static String checkReturnType( PsiMethodReferenceExpression expression, JavaResolveResult result, PsiType functionalInterfaceType) { final PsiElement resolve = result.getElement(); if (resolve instanceof PsiMethod) { final PsiClass containingClass = ((PsiMethod) resolve).getContainingClass(); LOG.assertTrue(containingClass != null); PsiSubstitutor subst = result.getSubstitutor(); PsiClass qContainingClass = getQualifierResolveResult(expression).getContainingClass(); if (qContainingClass != null && isReceiverType(functionalInterfaceType, containingClass, (PsiMethod) resolve)) { subst = TypeConversionUtil.getClassSubstitutor(containingClass, qContainingClass, subst); LOG.assertTrue(subst != null); } final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(functionalInterfaceType); PsiType returnType = PsiTypesUtil.patchMethodGetClassReturnType( expression, expression, (PsiMethod) resolve, null, PsiUtil.getLanguageLevel(expression)); if (returnType == null) { returnType = ((PsiMethod) resolve).getReturnType(); } PsiType methodReturnType = subst.substitute(returnType); if (interfaceReturnType != null && interfaceReturnType != PsiType.VOID) { if (methodReturnType == null) { methodReturnType = JavaPsiFacade.getElementFactory(expression.getProject()) .createType(containingClass, subst); } if (!TypeConversionUtil.isAssignable(interfaceReturnType, methodReturnType, false)) { return "Bad return type in method reference: cannot convert " + methodReturnType.getCanonicalText() + " to " + interfaceReturnType.getCanonicalText(); } } } return null; }
public void testInferWithBounds1() throws Exception { PsiReferenceExpression ref = configure(); JavaResolveResult resolveResult = ref.advancedResolve(false); PsiSubstitutor substitutor = resolveResult.getSubstitutor(); PsiMethod method = (PsiMethod) resolveResult.getElement(); PsiType type = substitutor.substitute(method.getTypeParameters()[0]); assertEquals("java.lang.String", type.getCanonicalText()); }
@Override public PsiParameter createParameter( @NotNull @NonNls String name, PsiType type, PsiElement context) throws IncorrectOperationException { final PsiMethod psiMethod = createMethodFromText("void f(" + type.getCanonicalText() + " " + name + ") {}", context); final PsiParameter[] parameters = psiMethod.getParameterList().getParameters(); return parameters[0]; }
private static boolean isConversionNeeded(@Nullable PsiType actual, @Nullable PsiType expected) { if (actual == null || expected == null) { return false; } Map<String, String> typeMap = new HashMap<String, String>(); typeMap.put(JAVA_LANG_BYTE, "byte"); typeMap.put(JAVA_LANG_SHORT, "short"); typeMap.put(JAVA_LANG_INTEGER, "int"); typeMap.put(JAVA_LANG_LONG, "long"); typeMap.put(JAVA_LANG_FLOAT, "float"); typeMap.put(JAVA_LANG_DOUBLE, "double"); typeMap.put(JAVA_LANG_CHARACTER, "char"); String expectedStr = expected.getCanonicalText(); String actualStr = actual.getCanonicalText(); boolean o1 = AstUtil.getOrElse(typeMap, actualStr, "").equals(expectedStr); boolean o2 = AstUtil.getOrElse(typeMap, expectedStr, "").equals(actualStr); return !actualStr.equals(expectedStr) && (!(o1 ^ o2)); }
private int substituteToTypeParameters( PsiTypeElement typeElement, PsiTypeElement inplaceTypeElement, PsiType[] paramVals, PsiTypeParameter[] params, TemplateBuilder builder, PsiSubstitutor rawingSubstitutor, boolean toplevel) { PsiType type = inplaceTypeElement.getType(); List<PsiType> types = new ArrayList<>(); for (int i = 0; i < paramVals.length; i++) { PsiType val = paramVals[i]; if (val == null) return SUBSTITUTED_NONE; if (type.equals(val)) { types.add(myFactory.createType(params[i])); } } if (!types.isEmpty()) { Project project = typeElement.getProject(); PsiType substituted = rawingSubstitutor.substitute(type); if (!CommonClassNames.JAVA_LANG_OBJECT.equals(substituted.getCanonicalText()) && (toplevel || substituted.equals(type))) { types.add(substituted); } builder.replaceElement( typeElement, new TypeExpression(project, types.toArray(PsiType.createArray(types.size())))); return toplevel ? SUBSTITUTED_IN_REF : SUBSTITUTED_IN_PARAMETERS; } boolean substituted = false; PsiJavaCodeReferenceElement ref = typeElement.getInnermostComponentReferenceElement(); PsiJavaCodeReferenceElement inplaceRef = inplaceTypeElement.getInnermostComponentReferenceElement(); if (ref != null) { LOG.assertTrue(inplaceRef != null); PsiTypeElement[] innerTypeElements = ref.getParameterList().getTypeParameterElements(); PsiTypeElement[] inplaceInnerTypeElements = inplaceRef.getParameterList().getTypeParameterElements(); for (int i = 0; i < innerTypeElements.length; i++) { substituted |= substituteToTypeParameters( innerTypeElements[i], inplaceInnerTypeElements[i], paramVals, params, builder, rawingSubstitutor, false) != SUBSTITUTED_NONE; } } return substituted ? SUBSTITUTED_IN_PARAMETERS : SUBSTITUTED_NONE; }
@SuppressWarnings({"HardCodedStringLiteral"}) private static void appendJVMSignature(JVMNameBuffer buffer, PsiType type) { if (type == null) { return; } final PsiType psiType = TypeConversionUtil.erasure(type); if (psiType instanceof PsiArrayType) { buffer.append(new JVMRawText("[")); appendJVMSignature(buffer, ((PsiArrayType) psiType).getComponentType()); } else if (psiType instanceof PsiClassType) { final JVMName jvmName = getJVMQualifiedName(psiType); appendJvmClassQualifiedName(buffer, jvmName); } else if (psiType instanceof PsiPrimitiveType) { buffer.append(getPrimitiveSignature(psiType.getCanonicalText())); } else { LOG.error("unknown type " + type.getCanonicalText()); } }
public MethodReturnTypeFix( @NotNull PsiMethod method, @NotNull PsiType returnType, boolean fixWholeHierarchy) { super(method); myReturnTypePointer = SmartTypePointerManager.getInstance(method.getProject()).createSmartTypePointer(returnType); myFixWholeHierarchy = fixWholeHierarchy; myName = method.getName(); myCanonicalText = returnType.getCanonicalText(); }
@Override public TypeSerializer getSerializer(PsiType psiType) { String typeName = psiType.getCanonicalText(); if (typeName.startsWith("java.util.List")) { String genericTypeName = typeName.replaceAll("java.util.List<", ""); genericTypeName = genericTypeName.replaceAll(">", ""); return new ListPrimitiveSerializer(genericTypeName); } return null; }
@Override public TypeGenerator getGenerator(PsiType psiType) { for (TypeGeneratorFactory factory : factories) { TypeGenerator generator = factory.getGenerator(psiType); if (generator != null) { return generator; } } return new UnknownTypeGenerator(psiType.getCanonicalText()); }
/** * Sets the basic element information from the given type. * * @param element the element to set information from the type * @param factory * @param type the type * @param modifiers modifier list * @since 2.15 */ private static void setElementInfo( AbstractElement element, PsiElementFactory factory, PsiType type, PsiModifierList modifiers) { // type names element.setTypeName(PsiAdapter.getTypeClassName(type)); element.setTypeQualifiedName(PsiAdapter.getTypeQualifiedClassName(type)); element.setType(type.getCanonicalText()); // arrays, collections and maps types if (PsiAdapter.isObjectArrayType(type)) { element.setObjectArray(true); element.setArray(true); // additional specify if the element is a string array if (PsiAdapter.isStringArrayType(type)) element.setStringArray(true); } else if (PsiAdapter.isPrimitiveArrayType(type)) { element.setPrimitiveArray(true); element.setArray(true); } if (PsiAdapter.isCollectionType(factory, type)) element.setCollection(true); if (PsiAdapter.isListType(factory, type)) element.setList(true); if (PsiAdapter.isSetType(factory, type)) element.setSet(true); if (PsiAdapter.isMapType(factory, type)) element.setMap(true); // other types if (PsiAdapter.isPrimitiveType(type)) element.setPrimitive(true); if (PsiAdapter.isObjectType(factory, type)) element.setObject(true); if (PsiAdapter.isStringType(factory, type)) element.setString(true); if (PsiAdapter.isNumericType(factory, type)) element.setNumeric(true); if (PsiAdapter.isDateType(factory, type)) element.setDate(true); if (PsiAdapter.isCalendarType(factory, type)) element.setCalendar(true); if (PsiAdapter.isBooleanType(factory, type)) element.setBoolean(true); if (PsiType.VOID.equals(type)) element.setVoid(true); if (PsiType.LONG.equals(type)) element.setLong(true); if (PsiType.FLOAT.equals(type)) element.setFloat(true); if (PsiType.DOUBLE.equals(type)) element.setDouble(true); if (PsiType.BYTE.equals(type)) element.setByte(true); if (PsiType.CHAR.equals(type)) element.setChar(true); if (PsiType.SHORT.equals(type)) element.setShort(true); element.setNestedArray(PsiAdapter.isNestedArray(type)); // modifiers if (modifiers != null) { if (modifiers.hasModifierProperty(PsiModifier.STATIC)) element.setModifierStatic(true); if (modifiers.hasModifierProperty(PsiModifier.FINAL)) element.setModifierFinal(true); if (modifiers.hasModifierProperty(PsiModifier.PUBLIC)) { element.setModifierPublic(true); } else if (modifiers.hasModifierProperty(PsiModifier.PROTECTED)) { element.setModifierProtected(true); } else if (modifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) { element.setModifierPackageLocal(true); } else if (modifiers.hasModifierProperty(PsiModifier.PRIVATE)) element.setModifierPrivate(true); } }
private void addPrimitives() { for (PsiType type : PRIMITIVE_TYPES) { if (type.getCanonicalText().startsWith(_prefixMatcher.getPrefix())) { addCompletion(new PrimitiveCompletionProposal(type), _javaCtx); } } if ("block".startsWith(_prefixMatcher.getPrefix())) { addCompletion(new RawCompletionProposal("block")); } }
public ChangeFieldTypeFix(GuiEditor uiEditor, PsiField field, PsiType uiComponentType) { super( uiEditor, MessageFormat.format( UIDesignerBundle.message("action.change.field.type"), field.getName(), field.getType().getCanonicalText(), uiComponentType.getCanonicalText()), null); myField = field; myNewType = uiComponentType; }
@Override public TypeGenerator getGenerator(PsiType psiType) { PsiType[] superTypes = psiType.getSuperTypes(); for (PsiType superType : superTypes) { String canonicalText = superType.getCanonicalText(); if ("java.io.Serializable".equals(canonicalText)) { return mSerializer; } } return null; }
@Override public void doFix(Project project, ProblemDescriptor descriptor) { final PsiExpression expression = (PsiExpression) descriptor.getPsiElement(); final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false); if (expectedType == null) { return; } final String expectedTypeText = expectedType.getCanonicalText(); final String classToConstruct; if (s_boxingClasses.containsValue(expectedTypeText)) { classToConstruct = expectedTypeText; } else { final PsiType type = expression.getType(); if (type == null) { return; } final String expressionTypeText = type.getCanonicalText(); classToConstruct = s_boxingClasses.get(expressionTypeText); } if (shortcutReplace(expression, classToConstruct)) { return; } final PsiExpression strippedExpression = ParenthesesUtils.stripParentheses(expression); if (strippedExpression == null) { return; } @NonNls final String expressionText = strippedExpression.getText(); @NonNls final String newExpression; if ("true".equals(expressionText)) { newExpression = "java.lang.Boolean.TRUE"; } else if ("false".equals(expressionText)) { newExpression = "java.lang.Boolean.FALSE"; } else { newExpression = classToConstruct + ".valueOf(" + expressionText + ')'; } replaceExpression(expression, newExpression); }