use of com.intellij.util.Function in project go-lang-idea-plugin by go-lang-plugin-org.
the class GoDocumentationProvider method getTypePresentation.
@NotNull
public static String getTypePresentation(@Nullable PsiElement element, @NotNull Function<PsiElement, String> presentationFunction) {
if (element instanceof GoType) {
GoType type = (GoType) element;
if (type instanceof GoMapType) {
GoType keyType = ((GoMapType) type).getKeyType();
GoType valueType = ((GoMapType) type).getValueType();
return "map[" + getTypePresentation(keyType, presentationFunction) + "]" + getTypePresentation(valueType, presentationFunction);
}
if (type instanceof GoChannelType) {
ASTNode typeNode = type.getNode();
GoType innerType = ((GoChannelType) type).getType();
ASTNode innerTypeNode = innerType != null ? innerType.getNode() : null;
if (typeNode != null && innerTypeNode != null) {
StringBuilder result = new StringBuilder();
for (ASTNode node : typeNode.getChildren(null)) {
if (node.equals(innerTypeNode)) {
break;
}
if (node.getElementType() != TokenType.WHITE_SPACE) {
result.append(XmlStringUtil.escapeString(node.getText()));
}
}
result.append(" ").append(getTypePresentation(innerType, presentationFunction));
return result.toString();
}
}
if (type instanceof GoParType) {
return "(" + getTypePresentation(((GoParType) type).getActualType(), presentationFunction) + ")";
}
if (type instanceof GoArrayOrSliceType) {
return "[]" + getTypePresentation(((GoArrayOrSliceType) type).getType(), presentationFunction);
}
if (type instanceof GoPointerType) {
GoType inner = ((GoPointerType) type).getType();
return inner instanceof GoSpecType ? getTypePresentation(inner, presentationFunction) : "*" + getTypePresentation(inner, presentationFunction);
}
if (type instanceof GoTypeList) {
return "(" + StringUtil.join(((GoTypeList) type).getTypeList(), element1 -> getTypePresentation(element1, presentationFunction), ", ") + ")";
}
if (type instanceof GoFunctionType) {
return getSignatureOwnerTypePresentation((GoFunctionType) type, presentationFunction);
}
if (type instanceof GoSpecType) {
return getTypePresentation(GoPsiImplUtil.getTypeSpecSafe(type), presentationFunction);
}
if (type instanceof GoCType) {
return "C";
}
if (type instanceof GoLightType) {
LOG.error("Cannot build presentable text for type: " + type.getClass().getSimpleName() + " - " + type.getText());
return "";
}
if (type instanceof GoStructType) {
StringBuilder result = new StringBuilder("struct {");
result.append(StringUtil.join(((GoStructType) type).getFieldDeclarationList(), declaration -> {
GoAnonymousFieldDefinition anon = declaration.getAnonymousFieldDefinition();
String fieldString = anon != null ? getTypePresentation(anon.getGoTypeInner(null), presentationFunction) : StringUtil.join(declaration.getFieldDefinitionList(), PsiElement::getText, ", ") + " " + getTypePresentation(declaration.getType(), presentationFunction);
GoTag tag = declaration.getTag();
return fieldString + (tag != null ? tag.getText() : "");
}, "; "));
return result.append("}").toString();
}
GoTypeReferenceExpression typeRef = GoPsiImplUtil.getTypeReference(type);
if (typeRef != null) {
PsiElement resolve = typeRef.resolve();
if (resolve != null) {
return getTypePresentation(resolve, presentationFunction);
}
}
}
return presentationFunction.fun(element);
}
use of com.intellij.util.Function in project intellij-elixir by KronicDeth.
the class Import method onlyCallDefinitionClauseCallFilter.
@NotNull
private static Function<Call, Boolean> onlyCallDefinitionClauseCallFilter(PsiElement element) {
final Map<String, List<Integer>> aritiesByName = aritiesByNameFromNameByArityKeywordList(element);
return new Function<Call, Boolean>() {
@Override
public Boolean fun(Call call) {
Pair<String, IntRange> callNameArityRange = nameArityRange(call);
boolean include = false;
if (callNameArityRange != null) {
String callName = callNameArityRange.first;
if (callName != null) {
List<Integer> arities = aritiesByName.get(callName);
if (arities != null) {
IntRange callArityRange = callNameArityRange.second;
for (int arity : arities) {
if (callArityRange.containsInteger(arity)) {
include = true;
break;
}
}
}
}
}
return include;
}
};
}
use of com.intellij.util.Function in project intellij-elixir by KronicDeth.
the class CallDefinitionClause method implicitImports.
private boolean implicitImports(@NotNull PsiElement element, @NotNull ResolveState state) {
Project project = element.getProject();
boolean keepProcessing = org.elixir_lang.reference.Module.forEachNavigationElement(project, KERNEL, new Function<PsiElement, Boolean>() {
@Override
public Boolean fun(PsiElement navigationElement) {
boolean keepProcessingNavigationElements = true;
if (navigationElement instanceof Call) {
Call modular = (Call) navigationElement;
keepProcessingNavigationElements = Modular.callDefinitionClauseCallWhile(modular, new Function<Call, Boolean>() {
@Override
public Boolean fun(Call callDefinitionClause) {
return executeOnCallDefinitionClause(callDefinitionClause, state);
}
});
}
return keepProcessingNavigationElements;
}
});
// the implicit `import Kernel.SpecialForms`
if (keepProcessing) {
ResolveState modularCanonicalNameState = state.put(MODULAR_CANONICAL_NAME, KERNEL_SPECIAL_FORMS);
keepProcessing = org.elixir_lang.reference.Module.forEachNavigationElement(project, KERNEL_SPECIAL_FORMS, new Function<PsiElement, Boolean>() {
@Override
public Boolean fun(PsiElement navigationElement) {
boolean keepProcessingNavigationElements = true;
if (navigationElement instanceof Call) {
Call modular = (Call) navigationElement;
keepProcessingNavigationElements = Modular.callDefinitionClauseCallWhile(modular, new Function<Call, Boolean>() {
@Override
public Boolean fun(Call callDefinitionClause) {
return executeOnCallDefinitionClause(callDefinitionClause, modularCanonicalNameState);
}
});
}
return keepProcessingNavigationElements;
}
});
}
return keepProcessing;
}
use of com.intellij.util.Function in project intellij-community by JetBrains.
the class CheckedExceptionCompatibilityConstraint method reduce.
@Override
public boolean reduce(final InferenceSession session, List<ConstraintFormula> constraints) {
if (!PsiPolyExpressionUtil.isPolyExpression(myExpression)) {
return true;
}
if (myExpression instanceof PsiParenthesizedExpression) {
constraints.add(new CheckedExceptionCompatibilityConstraint(((PsiParenthesizedExpression) myExpression).getExpression(), myT));
return true;
}
if (myExpression instanceof PsiConditionalExpression) {
final PsiExpression thenExpression = ((PsiConditionalExpression) myExpression).getThenExpression();
if (thenExpression != null) {
constraints.add(new CheckedExceptionCompatibilityConstraint(thenExpression, myT));
}
final PsiExpression elseExpression = ((PsiConditionalExpression) myExpression).getElseExpression();
if (elseExpression != null) {
constraints.add(new CheckedExceptionCompatibilityConstraint(elseExpression, myT));
}
return true;
}
if (myExpression instanceof PsiLambdaExpression || myExpression instanceof PsiMethodReferenceExpression) {
if (!LambdaUtil.isFunctionalType(myT)) {
session.registerIncompatibleErrorMessage(session.getPresentableText(myT) + " is not a functional interface");
return false;
}
final PsiType groundTargetType = myExpression instanceof PsiLambdaExpression ? FunctionalInterfaceParameterizationUtil.getGroundTargetType(myT, (PsiLambdaExpression) myExpression, false) : FunctionalInterfaceParameterizationUtil.getGroundTargetType(myT);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(groundTargetType);
if (interfaceMethod == null) {
session.registerIncompatibleErrorMessage("No valid function type can be found for " + session.getPresentableText(myT));
return false;
}
final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, PsiUtil.resolveGenericsClassInType(myT));
if (myExpression instanceof PsiLambdaExpression && !((PsiLambdaExpression) myExpression).hasFormalParameterTypes() || myExpression instanceof PsiMethodReferenceExpression && !((PsiMethodReferenceExpression) myExpression).isExact()) {
for (PsiParameter parameter : interfaceMethod.getParameterList().getParameters()) {
final PsiType type = substitutor.substitute(parameter.getType());
if (!session.isProperType(type)) {
session.registerIncompatibleErrorMessage("Parameter type is not yet inferred: " + session.getPresentableText(type));
return false;
}
}
}
final PsiType returnType = interfaceMethod.getReturnType();
if (myExpression instanceof PsiLambdaExpression || !((PsiMethodReferenceExpression) myExpression).isExact()) {
final PsiType type = substitutor.substitute(returnType);
if (!session.isProperType(type)) {
session.registerIncompatibleErrorMessage("Return type is not yet inferred: " + session.getPresentableText(type));
return false;
}
}
final List<PsiType> expectedThrownTypes = ContainerUtil.map(interfaceMethod.getThrowsList().getReferencedTypes(), (Function<PsiType, PsiType>) type -> session.substituteWithInferenceVariables(substitutor.substitute(type)));
final List<PsiType> expectedNonProperThrownTypes = new ArrayList<>();
for (PsiType type : expectedThrownTypes) {
if (!session.isProperType(type)) {
expectedNonProperThrownTypes.add(type);
}
}
final List<PsiType> thrownTypes = new ArrayList<>();
final PsiElement body = myExpression instanceof PsiLambdaExpression ? ((PsiLambdaExpression) myExpression).getBody() : myExpression;
if (body != null) {
final List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(new PsiElement[] { body });
if (exceptions != null) {
thrownTypes.addAll(ContainerUtil.filter(exceptions, type -> !ExceptionUtil.isUncheckedException(type)));
}
}
if (expectedNonProperThrownTypes.isEmpty()) {
for (PsiType thrownType : thrownTypes) {
if (!isAddressed(expectedThrownTypes, thrownType)) {
session.registerIncompatibleErrorMessage("Unhandled exception: " + session.getPresentableText(thrownType));
return false;
}
}
} else {
final ArrayList<PsiType> expectedProperTypes = new ArrayList<>(expectedThrownTypes);
expectedProperTypes.removeAll(expectedNonProperThrownTypes);
for (PsiType thrownType : thrownTypes) {
if (!isAddressed(expectedProperTypes, thrownType)) {
for (PsiType expectedNonProperThrownType : expectedNonProperThrownTypes) {
constraints.add(new StrictSubtypingConstraint(expectedNonProperThrownType, thrownType));
}
}
}
for (PsiType expectedNonProperThrownType : expectedNonProperThrownTypes) {
final InferenceVariable variable = session.getInferenceVariable(expectedNonProperThrownType);
//could be null for invalid code
if (variable != null) {
variable.setThrownBound();
}
}
}
}
return true;
}
use of com.intellij.util.Function in project intellij-community by JetBrains.
the class LambdaRefactoringUtil method createLambdaWithoutFormalParameters.
private static String createLambdaWithoutFormalParameters(PsiMethodReferenceExpression referenceExpression) {
PsiType functionalInterfaceType = referenceExpression.getFunctionalInterfaceType();
final PsiElement resolve = referenceExpression.resolve();
if (resolve == null) {
return null;
}
final PsiClassType.ClassResolveResult functionalInterfaceResolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(functionalInterfaceType);
if (interfaceMethod == null) {
return null;
}
final PsiSubstitutor psiSubstitutor = LambdaUtil.getSubstitutor(interfaceMethod, functionalInterfaceResolveResult);
final MethodSignature signature = interfaceMethod.getSignature(psiSubstitutor);
final boolean isReceiver;
if (resolve instanceof PsiMethod) {
final PsiMethod method = (PsiMethod) resolve;
isReceiver = PsiMethodReferenceUtil.isResolvedBySecondSearch(referenceExpression, signature, method.isVarArgs(), method.hasModifierProperty(PsiModifier.STATIC), method.getParameterList().getParametersCount());
} else {
isReceiver = false;
}
final PsiParameter[] psiParameters = resolve instanceof PsiMethod ? ((PsiMethod) resolve).getParameterList().getParameters() : null;
final PsiParameterList parameterList = interfaceMethod.getParameterList();
final PsiParameter[] parameters = parameterList.getParameters();
final Map<PsiParameter, String> map = new HashMap<>();
final UniqueNameGenerator nameGenerator = new UniqueNameGenerator();
final JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(referenceExpression.getProject());
Function<PsiParameter, String> paramPresentationFunction = parameter -> {
final int parameterIndex = parameterList.getParameterIndex(parameter);
String baseName;
if (isReceiver && parameterIndex == 0) {
final SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
baseName = nameInfo.names.length > 0 ? nameInfo.names[0] : parameter.getName();
} else {
String initialName;
if (psiParameters != null) {
final int idx = parameterIndex - (isReceiver ? 1 : 0);
initialName = psiParameters.length > 0 ? psiParameters[idx < psiParameters.length ? idx : psiParameters.length - 1].getName() : parameter.getName();
} else {
initialName = parameter.getName();
}
LOG.assertTrue(initialName != null);
if ("_".equals(initialName)) {
SuggestedNameInfo nameInfo = codeStyleManager.suggestVariableName(VariableKind.PARAMETER, null, null, psiSubstitutor.substitute(parameter.getType()));
if (nameInfo.names.length > 0) {
initialName = nameInfo.names[0];
}
}
baseName = codeStyleManager.variableNameToPropertyName(initialName, VariableKind.PARAMETER);
}
if (baseName != null) {
String parameterName = nameGenerator.generateUniqueName(codeStyleManager.suggestUniqueVariableName(baseName, referenceExpression, true));
map.put(parameter, parameterName);
return parameterName;
}
return "";
};
StringBuilder buf = new StringBuilder();
if (parameters.length == 1) {
buf.append(paramPresentationFunction.fun(parameters[0]));
} else {
buf.append("(").append(StringUtil.join(parameters, paramPresentationFunction, ", ")).append(")");
}
buf.append(" -> ");
final JavaResolveResult resolveResult = referenceExpression.advancedResolve(false);
final PsiElement resolveElement = resolveResult.getElement();
if (resolveElement instanceof PsiMember) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(referenceExpression.getProject());
buf.append("{");
if (!PsiType.VOID.equals(interfaceMethod.getReturnType())) {
buf.append("return ");
}
final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(referenceExpression);
final PsiElement qualifier = referenceExpression.getQualifier();
PsiClass containingClass = qualifierResolveResult.getContainingClass();
final boolean onArrayRef = elementFactory.getArrayClass(PsiUtil.getLanguageLevel(referenceExpression)) == containingClass;
final PsiElement referenceNameElement = referenceExpression.getReferenceNameElement();
if (isReceiver) {
buf.append(map.get(parameters[0])).append(".");
} else {
if (!(referenceNameElement instanceof PsiKeyword)) {
if (qualifier instanceof PsiTypeElement) {
final PsiJavaCodeReferenceElement referenceElement = ((PsiTypeElement) qualifier).getInnermostComponentReferenceElement();
LOG.assertTrue(referenceElement != null);
if (!PsiTreeUtil.isAncestor(containingClass, referenceExpression, false)) {
buf.append(referenceElement.getReferenceName()).append(".");
}
} else if (qualifier != null && !isQualifierUnnecessary(qualifier, containingClass)) {
buf.append(qualifier.getText()).append(".");
}
}
}
//new or method name
buf.append(referenceExpression.getReferenceName());
if (referenceNameElement instanceof PsiKeyword) {
//class name
buf.append(" ");
if (onArrayRef) {
if (qualifier instanceof PsiTypeElement) {
final PsiType type = ((PsiTypeElement) qualifier).getType();
int dim = type.getArrayDimensions();
buf.append(type.getDeepComponentType().getCanonicalText());
buf.append("[");
buf.append(map.get(parameters[0]));
buf.append("]");
while (--dim > 0) {
buf.append("[]");
}
}
} else {
buf.append(((PsiMember) resolveElement).getName());
final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
LOG.assertTrue(containingClass != null);
if (containingClass.hasTypeParameters() && !PsiUtil.isRawSubstitutor(containingClass, substitutor)) {
buf.append("<").append(StringUtil.join(containingClass.getTypeParameters(), parameter -> {
final PsiType psiType = substitutor.substitute(parameter);
LOG.assertTrue(psiType != null);
return psiType.getCanonicalText();
}, ", ")).append(">");
}
}
}
if (!onArrayRef || isReceiver) {
//param list
buf.append("(");
boolean first = true;
for (int i = isReceiver ? 1 : 0; i < parameters.length; i++) {
PsiParameter parameter = parameters[i];
if (!first) {
buf.append(", ");
} else {
first = false;
}
buf.append(map.get(parameter));
}
buf.append(")");
}
buf.append(";}");
}
return buf.toString();
}
Aggregations