PsiElement (@NotNull PsiElement element, @NotNull PsiElement replacement) { final PsiElement parent = element.getParent(); if (parent instanceof PsiPolyadicExpression parentPolyadic && replacement instanceof PsiPolyadicExpression childPolyadic) { // flatten nested polyadic expressions IElementType parentTokenType = parentPolyadic.getOperationTokenType(); IElementType childTokenType = childPolyadic.getOperationTokenType(); if (PsiPrecedenceUtil.getPrecedenceForOperator(parentTokenType) == PsiPrecedenceUtil.getPrecedenceForOperator(childTokenType) && !PsiPrecedenceUtil.areParenthesesNeeded(childPolyadic, parentPolyadic, false)) { PsiElement[] children = parentPolyadic.getChildren(); int idx = ArrayUtil.indexOf(children, element); if (idx > 0 || (idx == 0 && parentTokenType == childTokenType)) { StringBuilder text = new StringBuilder(); for (int i = 0; i < children.length; i++) { PsiElement child = children[i]; text.append(text((i == idx) ? replacement : child)); } replacement = JavaPsiFacade.getElementFactory(parent.getProject()).createExpressionFromText(text.toString(), parent); element = parent; } } } markUnchanged(replacement); grabComments(element); return element.replace(replacement); }