@Nullable
  private static AstScopeOwner calculateScopeOwnerByAST(@Nullable PsiElement element) {
    final AstScopeOwner firstOwner = getParentOfType(element, AstScopeOwner.class);
    if (firstOwner == null) {
      return null;
    }
    final AstScopeOwner nextOwner = getParentOfType(firstOwner, AstScopeOwner.class);
    // References in decorator expressions are resolved outside of the function (if the lambda is not inside the decorator)
    final PyAstElement decoratorAncestor = getParentOfType(element, PyAstDecorator.class);
    if (decoratorAncestor != null && !isAncestor(decoratorAncestor, firstOwner, true)) {
      return nextOwner;
    }
    /*
     * References in default values are resolved outside of the function (if the lambda is not inside the default value).
     * Annotations of parameters are resolved outside of the function if the function doesn't have type parameters list
     */
    final PyAstNamedParameter parameterAncestor = getParentOfType(element, PyAstNamedParameter.class);
    if (parameterAncestor != null && !isAncestor(parameterAncestor, firstOwner, true)) {
      final PyAstExpression defaultValue = parameterAncestor.getDefaultValue();
      final PyAstAnnotation annotation = parameterAncestor.getAnnotation();
      if (firstOwner instanceof PyAstFunction function) {
        PyAstTypeParameterList typeParameterList = function.getTypeParameterList();
        if ((typeParameterList == null && isAncestor(annotation, element, false))
            || (isAncestor(defaultValue, element, false))) {
          return nextOwner;
        }
      }
    }
    // Superclasses are resolved outside of the class if the class doesn't have type parameters list
    final PyAstClass containingClass = getParentOfType(element, PyAstClass.class);
    if (containingClass != null && isAncestor(containingClass.getSuperClassExpressionList(), element, false) && containingClass.getTypeParameterList() == null) {
      return nextOwner;
    }
    // Function return annotations and type comments are resolved outside of the function if the function doesn't have type parameters list
    if (firstOwner instanceof PyAstFunction function) {
      PyAstTypeParameterList typeParameterList = function.getTypeParameterList();
      if ((typeParameterList == null && isAncestor(function.getAnnotation(), element, false)
           || isAncestor(function.getTypeComment(), element, false))) {
        return nextOwner;
      }
    }
    return firstOwner;
  }
@Nullable
  private static AstScopeOwner calculateScopeOwnerByAST(@Nullable PsiElement element)