PsiExpression (PsiFile containingFile, PsiVariable psiVariable, PsiElementFactory elementFactory, RangeMarker marker, String exprText) { if (exprText == null) return null; if (psiVariable == null || !psiVariable.isValid()) return null; final PsiElement refVariableElement = containingFile.findElementAt(marker.getStartOffset()); final PsiElement refVariableElementParent = refVariableElement != null ? refVariableElement.getParent() : null; PsiElement expression = refVariableElement instanceof PsiKeyword && refVariableElementParent instanceof PsiNewExpression ? (PsiNewExpression)refVariableElementParent : refVariableElementParent instanceof PsiParenthesizedExpression ? ((PsiParenthesizedExpression)refVariableElementParent).getExpression() : PsiTreeUtil.getParentOfType(refVariableElement, PsiJavaCodeReferenceElement.class); if (expression instanceof PsiJavaCodeReferenceElement && !(expression.getParent() instanceof PsiMethodCallExpression)) { final String referenceName = ((PsiJavaCodeReferenceElement)expression).getReferenceName(); if (((PsiJavaCodeReferenceElement)expression).resolve() == psiVariable || Comparing.strEqual(psiVariable.getName(), referenceName) || Comparing.strEqual(exprText, referenceName)) { return (PsiExpression)expression.replace(elementFactory.createExpressionFromText(exprText, psiVariable)); } } if (expression == null) { expression = PsiTreeUtil.getParentOfType(refVariableElement, PsiExpression.class); } while (expression instanceof PsiReferenceExpression || expression instanceof PsiMethodCallExpression) { final PsiElement parent = expression.getParent(); if (parent instanceof PsiMethodCallExpression) { if (parent.getText().equals(exprText)) return (PsiExpression)parent; } if (parent instanceof PsiExpression) { expression = parent; if (expression.getText().equals(exprText)) { return (PsiExpression)expression; } } else if (expression instanceof PsiReferenceExpression) { return null; } else { break; } } if (expression instanceof PsiExpression && expression.isValid() && expression.getText().equals(exprText)) { return (PsiExpression)expression; } if (refVariableElementParent instanceof PsiExpression && refVariableElementParent.getText().equals(exprText)) { return (PsiExpression)refVariableElementParent; } if (expression == null && refVariableElement instanceof PsiIdentifier && refVariableElementParent instanceof PsiJavaCodeReferenceElement && refVariableElement.getText().equals(psiVariable.getName())) { // E.g. "this.x y = z;" is parsed as two expression statements // but "a.x y = z;" is parsed as declaration of variable y of type a.x, // so 'a' is not a reference to the variable 'a' but a type reference return (PsiExpression)refVariableElementParent.replace(elementFactory.createExpressionFromText(exprText, psiVariable)); } return null; }