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();
}
use of com.intellij.util.Function in project intellij-community by JetBrains.
the class ResetConfigurationModuleAdapter method tryWithAnotherModule.
public static <T extends ModuleBasedConfiguration<JavaRunConfigurationModule> & CommonJavaRunConfigurationParameters> boolean tryWithAnotherModule(T configuration, boolean isDebug) {
final String packageName = configuration.getPackage();
if (packageName == null)
return false;
final Project project = configuration.getProject();
final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName);
if (aPackage == null)
return false;
final Module module = configuration.getConfigurationModule().getModule();
if (module == null)
return false;
final Set<Module> modulesWithPackage = new HashSet<>();
final PsiDirectory[] directories = aPackage.getDirectories();
for (PsiDirectory directory : directories) {
final Module currentModule = ModuleUtilCore.findModuleForFile(directory.getVirtualFile(), project);
if (module != currentModule && currentModule != null) {
modulesWithPackage.add(currentModule);
}
}
if (!modulesWithPackage.isEmpty()) {
final String testRunDebugId = isDebug ? ToolWindowId.DEBUG : ToolWindowId.RUN;
final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(project);
final Function<Module, String> moduleNameRef = module1 -> {
final String moduleName = module1.getName();
return "<a href=\"" + moduleName + "\">" + moduleName + "</a>";
};
String message = "Tests were not found in module \"" + module.getName() + "\".\n" + "Use ";
if (modulesWithPackage.size() == 1) {
message += "module \"" + moduleNameRef.fun(modulesWithPackage.iterator().next()) + "\" ";
} else {
message += "one of\n" + StringUtil.join(modulesWithPackage, moduleNameRef, "\n") + "\n";
}
message += "instead";
toolWindowManager.notifyByBalloon(testRunDebugId, MessageType.WARNING, message, null, new ResetConfigurationModuleAdapter(configuration, project, isDebug, toolWindowManager, testRunDebugId));
return true;
}
return false;
}
use of com.intellij.util.Function in project intellij-community by JetBrains.
the class TextControl method createMainComponent.
@Override
protected TextPanel createMainComponent(TextPanel boundedComponent, final Project project) {
if (boundedComponent == null) {
boundedComponent = new TextPanel();
}
boundedComponent.removeAll();
final Function<String, Document> factory = s -> PsiDocumentManager.getInstance(project).getDocument(PsiFileFactory.getInstance(project).createFileFromText("a.txt", PlainTextLanguage.INSTANCE, "", true, false));
final TextPanel boundedComponent1 = boundedComponent;
final EditorTextField editorTextField = new EditorTextField(factory.fun(""), project, FileTypes.PLAIN_TEXT) {
@Override
protected EditorEx createEditor() {
final EditorEx editor = super.createEditor();
return boundedComponent1 instanceof MultiLineTextPanel ? makeBigEditor(editor, ((MultiLineTextPanel) boundedComponent1).getRowCount()) : editor;
}
@Override
protected boolean isOneLineMode() {
return false;
}
};
if (boundedComponent instanceof BigTextPanel) {
final ReferenceEditorWithBrowseButton editor = new ReferenceEditorWithBrowseButton(null, editorTextField, factory);
boundedComponent.add(editor);
editor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
EditorTextField textArea = new EditorTextField(editorTextField.getDocument(), project, FileTypes.PLAIN_TEXT) {
@Override
protected EditorEx createEditor() {
final EditorEx editor = super.createEditor();
editor.setEmbeddedIntoDialogWrapper(true);
return makeBigEditor(editor, 5);
}
@Override
protected boolean isOneLineMode() {
return false;
}
};
DialogBuilder builder = new DialogBuilder(project);
builder.setDimensionServiceKey("TextControl");
builder.setCenterPanel(textArea);
builder.setPreferredFocusComponent(textArea);
builder.setTitle(UIBundle.message("big.text.control.window.title"));
builder.addCloseButton();
builder.show();
}
});
return boundedComponent;
}
boundedComponent.add(editorTextField);
return boundedComponent;
}
use of com.intellij.util.Function in project intellij-community by JetBrains.
the class DomConcurrencyStressTest method runThreads.
private static void runThreads(int threadCount, final Runnable runnable) throws Throwable {
for (int i = 0; i < threadCount / 8 + 1; i++) {
final Ref<Throwable> exc = Ref.create(null);
int N = 8;
final CountDownLatch reads = new CountDownLatch(N);
List<Thread> threads = ContainerUtil.map(Collections.nCopies(N, ""), (Function<String, Thread>) s -> new Thread("dom concurrency") {
@Override
public void run() {
try {
runnable.run();
} catch (Throwable e) {
exc.set(e);
} finally {
reads.countDown();
}
}
});
threads.forEach(Thread::start);
reads.await();
if (!exc.isNull()) {
throw exc.get();
}
ConcurrencyUtil.joinAll(threads);
}
}
Aggregations