# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""Unified type system in the project."""

import tvm_ffi

from tvm.runtime import Scriptable

from . import _ffi_api
from .base import Node


@tvm_ffi.register_object("ir.Type")
class Type(Node, Scriptable):
    """The base class of all types."""

    @staticmethod
    def missing():
        """Return the sentinel for missing type information."""
        return _ffi_api.TypeMissing()

    @staticmethod
    def Missing():
        """Return the sentinel for missing type information."""
        return _ffi_api.TypeMissing()

    def is_missing(self):
        """Return whether this is the missing-type sentinel."""
        return _ffi_api.TypeIsMissing(self)

    def __eq__(self, other):
        """Compare two types for structural equivalence."""
        return bool(tvm_ffi.structural_equal(self, other))

    def __ne__(self, other):
        return not self.__eq__(other)

    def same_as(self, other):
        """Compares two TVM types by referential equality."""
        return self.is_(other)


@tvm_ffi.register_object("ir.PrimType")
class PrimType(Type):
    """Primitive data type in the low level IR

    Parameters
    ----------
    dtype : str
        The runtime data type relates to the primtype.
    """

    def __init__(self, dtype):
        self.__init_handle_by_constructor__(_ffi_api.PrimType, dtype)

    def __eq__(self, other):
        if isinstance(other, str):
            return self.dtype == other
        return super().__eq__(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        dtype = self.dtype
        return hash((dtype.type_code, dtype.bits, dtype.lanes))

    def __str__(self):
        return str(self.dtype)

    def matches_code(self, *codes) -> bool:
        """Return whether this type has any of the given DLPack dtype codes."""
        type_code = self.dtype.type_code
        return any(type_code == int(code) for code in codes)

    def matches_element_type(self, code, bits: int) -> bool:
        """Return whether this type has the given scalar element code and bits."""
        dtype = self.dtype
        return dtype.type_code == int(code) and dtype.bits == bits

    def is_scalar(self) -> bool:
        """Return whether this type has exactly one fixed lane."""
        return self.dtype.lanes == 1


@tvm_ffi.register_object("ir.PointerType")
class PointerType(Type):
    """PointerType used in the low-level TIR.

    Parameters
    ----------
    element_type : tvm.ir.Type
        The type of pointer's element.

    storage_scope : str
        The storage scope into which the pointer addresses.
    """

    def __init__(self, element_type, storage_scope=""):
        self.__init_handle_by_constructor__(_ffi_api.PointerType, element_type, storage_scope)


@tvm_ffi.register_object("ir.TupleType")
class TupleType(Type):
    """The type of tuple values.

    Parameters
    ----------
    fields : List[Type]
        The fields in the tuple
    """

    def __init__(self, fields, span=None):
        self.__init_handle_by_constructor__(_ffi_api.TupleType, fields, span)


@tvm_ffi.register_object("ir.FuncType")
class FuncType(Type):
    """Function type.

    A function type consists of a list of type parameters to enable
    the definition of generic functions,
    a set of type constraints which we omit for the time being,
    a sequence of argument types, and a return type.

    Parameters
    ----------
    arg_types : List[tvm.ir.Type]
        The argument types

    ret_type : tvm.ir.Type
        The return type.
    """

    def __init__(self, arg_types, ret_type):
        self.__init_handle_by_constructor__(
            _ffi_api.FuncType,
            arg_types,
            ret_type,
        )


@tvm_ffi.register_object("ir.TensorMapType")
class TensorMapType(Type):
    """TensorMapType used in the low-level TIR.

    Parameters
    ----------
    span : tvm.ir.Span
        The span information.
    """

    def __init__(self, span=None):
        self.__init_handle_by_constructor__(
            _ffi_api.TensorMapType,
            span,  # pylint: disable=no-member
        )
