public static @Nullable PsiElement getElementVariableReferencedFrom(@NotNull PsiVariable variable, @NotNull PsiElement context) {
    PsiElement[] scope;
    if (variable instanceof PsiResourceVariable resourceVariable) {
      scope = resourceVariable.getDeclarationScope();
    }
    else if (variable instanceof PsiLocalVariable) {
      PsiElement parent = variable.getParent();
      scope = new PsiElement[]{parent != null ? parent.getParent() : null}; // code block or for statement
    }
    else if (variable instanceof PsiParameter parameter) {
      scope = new PsiElement[]{parameter.getDeclarationScope()};
    }
    else {
      scope = new PsiElement[]{variable.getParent()};
    }
    if (scope.length < 1 || scope[0] == null || scope[0].getContainingFile() != context.getContainingFile()) return null;
    PsiElement parent = context.getParent();
    PsiElement prevParent = context;
    outer:
    while (parent != null) {
      for (PsiElement scopeElement : scope) {
        if (parent.equals(scopeElement)) break outer;
      }
      if (parent instanceof PsiClass && !(prevParent instanceof PsiExpressionList && parent instanceof PsiAnonymousClass)) {
        return parent;
      }
      if (parent instanceof PsiLambdaExpression) {
        return parent;
      }
      if (parent instanceof PsiSwitchLabelStatementBase label && label.getGuardExpression() == prevParent) {
        return parent;
      }
      prevParent = parent;
      parent = parent.getParent();
    }
    return null;
  }
public static @Nullable PsiElement getElementVariableReferencedFrom(@NotNull PsiVariable variable, @NotNull PsiElement context)