public static @NotNull TextRange getReferenceRange(@NotNull PsiReference reference, @NotNull PsiElement inElement) {
    TextRange rangeInElement = reference.getRangeInElement();
    PsiElement refElement = reference.getElement();
    PsiElement element = refElement;
    while (element != inElement) {
      int start = element.getStartOffsetInParent();
      if (start + rangeInElement.getStartOffset() < 0) {
        throw new IllegalArgumentException("Inconsistent reference range in #" + inElement.getLanguage().getID() + ":" +
                                           "ref of " + reference.getClass() +
                                           " on " + classAndRange(refElement) +
                                           " with range " + reference.getRangeInElement() + ", " +
                                           "requested range in PSI of " + classAndRange(inElement));
      }
      rangeInElement = rangeInElement.shiftRight(start);
      element = element.getParent();
      if (element instanceof PsiFile) break;
    }
    return rangeInElement;
  }
public static @NotNull TextRange getReferenceRange(@NotNull PsiReference reference, @NotNull PsiElement inElement)