@Nullable
  @Override
  public PsiElement getElementByReference(@NotNull PsiReference ref, int flags) {
    if ((flags & TargetElementUtilBase.ELEMENT_NAME_ACCEPTED) == 0) {
      return null;
    }

    final PsiElement element = ref.getElement();
    final var resolveContext =
      PyResolveContext.defaultContext(TypeEvalContext.codeAnalysis(element.getProject(), element.getContainingFile()));

    PsiElement result = PyResolveUtil.resolveDeclaration(ref, resolveContext);
    Set<PsiElement> visited = new HashSet<>();
    visited.add(result);
    while (result instanceof PyReferenceExpression || result instanceof PyTargetExpression) {
      PsiElement nextResult = PyResolveUtil.resolveDeclaration(((PyReferenceOwner)result).getReference(resolveContext), resolveContext);
      if (nextResult != null && !visited.contains(nextResult) &&
          PsiTreeUtil.getParentOfType(element, ScopeOwner.class) == PsiTreeUtil.getParentOfType(result, ScopeOwner.class) &&
          (nextResult instanceof PyReferenceExpression || nextResult instanceof PyTargetExpression || nextResult instanceof PyParameter)) {
        visited.add(nextResult);
        result = nextResult;
      }
      else {
        break;
      }
    }
    return result;
  }
@Nullable
  @Override
  public PsiElement getElementByReference(@NotNull PsiReference ref, int flags)