Skip to content

Constraints

constraints

ParametrizedAttributeT = TypeVar('ParametrizedAttributeT', bound=ParametrizedAttribute) module-attribute

ParametrizedAttributeCovT = TypeVar('ParametrizedAttributeCovT', bound=ParametrizedAttribute, covariant=True) module-attribute

InferenceContext dataclass

Bases: ABC

Stores the assignments of constraint variables without allowing assignment. Used for inference, at which point variables are read-only.

Source code in xdsl/irdl/constraints.py
@dataclass
class InferenceContext(ABC):
    """
    Stores the assignments of constraint variables without allowing assignment.
    Used for inference, at which point variables are read-only.
    """

    _variables: dict[str, Attribute] = field(default_factory=dict[str, Attribute])
    """The assignment of constraint variables."""

    _range_variables: dict[str, tuple[Attribute, ...]] = field(
        default_factory=dict[str, tuple[Attribute, ...]]
    )
    """The assignment of constraint range variables."""

    _int_variables: dict[str, int] = field(default_factory=dict[str, int])
    """The assignment of constraint int variables."""

    def get_variable(self, key: str) -> Attribute | None:
        return self._variables.get(key)

    def get_range_variable(self, key: str) -> tuple[Attribute, ...] | None:
        return self._range_variables.get(key)

    def get_int_variable(self, key: str) -> int | None:
        return self._int_variables.get(key)

    @property
    def attr_variables(self) -> AbstractSet[str]:
        return self._variables.keys()

    @property
    def range_variables(self) -> AbstractSet[str]:
        return self._range_variables.keys()

    @property
    def int_variables(self) -> AbstractSet[str]:
        return self._int_variables.keys()

attr_variables: AbstractSet[str] property

range_variables: AbstractSet[str] property

int_variables: AbstractSet[str] property

__init__(_variables: dict[str, Attribute] = dict[str, Attribute](), _range_variables: dict[str, tuple[Attribute, ...]] = dict[str, tuple[Attribute, ...]](), _int_variables: dict[str, int] = dict[str, int]()) -> None

get_variable(key: str) -> Attribute | None

Source code in xdsl/irdl/constraints.py
def get_variable(self, key: str) -> Attribute | None:
    return self._variables.get(key)

get_range_variable(key: str) -> tuple[Attribute, ...] | None

Source code in xdsl/irdl/constraints.py
def get_range_variable(self, key: str) -> tuple[Attribute, ...] | None:
    return self._range_variables.get(key)

get_int_variable(key: str) -> int | None

Source code in xdsl/irdl/constraints.py
def get_int_variable(self, key: str) -> int | None:
    return self._int_variables.get(key)

VerificationContext dataclass

Bases: InferenceContext

Contains the assignment of constraint variables, allowing assignment.

Source code in xdsl/irdl/constraints.py
@dataclass
class VerificationContext(InferenceContext):
    """
    Contains the assignment of constraint variables, allowing assignment.
    """

    def set_attr_variable(self, key: str, attr: Attribute) -> bool:
        """
        Tries to assign the attribute 'attr' to key 'key'.
        If a different attribute is already assigned to this key, then this function
        throws a VerifyError.

        The return value indicates whether this key was set by this call.
        """
        if (existing := self._variables.get(key)) is not None:
            if existing != attr:
                raise VerifyException(
                    f"attribute {existing} expected from variable "
                    f"'{key}', but got {attr}"
                )
            return False
        self._variables[key] = attr
        return True

    def set_range_variable(self, key: str, attrs: tuple[Attribute, ...]) -> bool:
        """
        Tries to assign the attributes 'attrs' to key 'key'.
        If a different attribute range is already assigned to this key, then this
        function throws a VerifyError.

        The return value indicates whether this key was set by this call.
        """
        if (existing := self._range_variables.get(key)) is not None:
            if existing != attrs:
                raise VerifyException(
                    f"attributes {tuple(str(x) for x in existing)} expected from range variable "
                    f"'{key}', but got {tuple(str(x) for x in attrs)}"
                )
            return False
        self._range_variables[key] = attrs
        return True

    def set_int_variable(self, key: str, i: int) -> bool:
        """
        Tries to assign the integer 'i' to key 'key'.
        If a different integer is already assigned to this key, then this function throws
        a VerifyError.

        The return value indicates whether this key was set by this call.
        """
        if (existing := self._int_variables.get(key)) is not None:
            if existing != i:
                raise VerifyException(
                    f"integer {existing} expected from int variable "
                    f"'{key}', but got {i}"
                )
            return False
        self._int_variables[key] = i
        return True

__init__(_variables: dict[str, Attribute] = dict[str, Attribute](), _range_variables: dict[str, tuple[Attribute, ...]] = dict[str, tuple[Attribute, ...]](), _int_variables: dict[str, int] = dict[str, int]()) -> None

set_attr_variable(key: str, attr: Attribute) -> bool

Tries to assign the attribute 'attr' to key 'key'. If a different attribute is already assigned to this key, then this function throws a VerifyError.

The return value indicates whether this key was set by this call.

Source code in xdsl/irdl/constraints.py
def set_attr_variable(self, key: str, attr: Attribute) -> bool:
    """
    Tries to assign the attribute 'attr' to key 'key'.
    If a different attribute is already assigned to this key, then this function
    throws a VerifyError.

    The return value indicates whether this key was set by this call.
    """
    if (existing := self._variables.get(key)) is not None:
        if existing != attr:
            raise VerifyException(
                f"attribute {existing} expected from variable "
                f"'{key}', but got {attr}"
            )
        return False
    self._variables[key] = attr
    return True

set_range_variable(key: str, attrs: tuple[Attribute, ...]) -> bool

Tries to assign the attributes 'attrs' to key 'key'. If a different attribute range is already assigned to this key, then this function throws a VerifyError.

The return value indicates whether this key was set by this call.

Source code in xdsl/irdl/constraints.py
def set_range_variable(self, key: str, attrs: tuple[Attribute, ...]) -> bool:
    """
    Tries to assign the attributes 'attrs' to key 'key'.
    If a different attribute range is already assigned to this key, then this
    function throws a VerifyError.

    The return value indicates whether this key was set by this call.
    """
    if (existing := self._range_variables.get(key)) is not None:
        if existing != attrs:
            raise VerifyException(
                f"attributes {tuple(str(x) for x in existing)} expected from range variable "
                f"'{key}', but got {tuple(str(x) for x in attrs)}"
            )
        return False
    self._range_variables[key] = attrs
    return True

set_int_variable(key: str, i: int) -> bool

Tries to assign the integer 'i' to key 'key'. If a different integer is already assigned to this key, then this function throws a VerifyError.

The return value indicates whether this key was set by this call.

Source code in xdsl/irdl/constraints.py
def set_int_variable(self, key: str, i: int) -> bool:
    """
    Tries to assign the integer 'i' to key 'key'.
    If a different integer is already assigned to this key, then this function throws
    a VerifyError.

    The return value indicates whether this key was set by this call.
    """
    if (existing := self._int_variables.get(key)) is not None:
        if existing != i:
            raise VerifyException(
                f"integer {existing} expected from int variable "
                f"'{key}', but got {i}"
            )
        return False
    self._int_variables[key] = i
    return True

ConstraintContext dataclass

Bases: VerificationContext

Source code in xdsl/irdl/constraints.py
@deprecated("Please use either VerificationContext or InferenceContext")
class ConstraintContext(VerificationContext):
    pass

AttrConstraint dataclass

Bases: ABC, Generic[AttributeCovT]

Constrain an attribute to a certain value.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AttrConstraint(ABC, Generic[AttributeCovT]):
    """Constrain an attribute to a certain value."""

    @abstractmethod
    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        """
        Check if the attribute satisfies the constraint,
        or raise an exception otherwise.
        """
        ...

    def verifies(self, attr: Attribute) -> TypeGuard[AttributeCovT]:
        """
        A helper method to check whether a given attribute matches `self`.
        """
        try:
            self.verify(attr, VerificationContext())
            return True
        except VerifyException:
            return False

    def variables(self) -> set[str]:
        """
        Returns a set of the variables that can be extracted by this constraint.
        These variables are always expected to be set after running `verify`.
        """
        return set()

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        """
        Check if there is enough information to infer the attribute given the
        constraint variables that are already set.
        """
        # By default, we cannot infer anything.
        return False

    def infer(self, context: InferenceContext) -> AttributeCovT:
        """
        Infer the attribute given the the values for all variables.

        Raises an exception if the attribute cannot be inferred. If `can_infer`
        returns `True` with the given constraint variables, this method should
        not raise an exception.
        """
        raise ValueError(f"Cannot infer attribute from constraint {self}")

    def get_bases(self) -> set[type[Attribute]] | None:
        """
        Get a set of base types that can satisfy this constraint, if there exists
        a finite collection, or None otherwise.
        """
        return None

    def relax_constraint(
        self, other: AttrConstraint[AttributeCovT]
    ) -> AttrConstraint[AttributeCovT] | None:
        """
        Attempt to relax this constraint by merging it with `other`,
        returning the result if successful.
        """
        return self if self == other else None

    def __or__(
        self, value: AttrConstraint[_AttributeCovT], /
    ) -> AttrConstraint[AttributeCovT | _AttributeCovT]:
        if isinstance(value, AnyAttr) or self == value:
            return value  # pyright: ignore[reportReturnType]
        return AnyOf.get(self, value)

    def __and__(self, value: AttrConstraint, /) -> AttrConstraint[AttributeCovT]:
        if isinstance(value, AnyAttr) or self == value:
            return self
        return AllOf((self, value))  # pyright: ignore[reportReturnType]

    @abstractmethod
    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[AttributeCovT]:
        """
        A helper function to make type vars used in attribute definitions concrete when
        creating constraints for new attributes or operations.
        """
        raise NotImplementedError(
            "Custom constraints must map type vars in nested constraints, if any."
        )

__init__() -> None

verify(attr: Attribute, constraint_context: VerificationContext) -> None abstractmethod

Check if the attribute satisfies the constraint, or raise an exception otherwise.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    """
    Check if the attribute satisfies the constraint,
    or raise an exception otherwise.
    """
    ...

verifies(attr: Attribute) -> TypeGuard[AttributeCovT]

A helper method to check whether a given attribute matches self.

Source code in xdsl/irdl/constraints.py
def verifies(self, attr: Attribute) -> TypeGuard[AttributeCovT]:
    """
    A helper method to check whether a given attribute matches `self`.
    """
    try:
        self.verify(attr, VerificationContext())
        return True
    except VerifyException:
        return False

variables() -> set[str]

Returns a set of the variables that can be extracted by this constraint. These variables are always expected to be set after running verify.

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    """
    Returns a set of the variables that can be extracted by this constraint.
    These variables are always expected to be set after running `verify`.
    """
    return set()

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Check if there is enough information to infer the attribute given the constraint variables that are already set.

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    """
    Check if there is enough information to infer the attribute given the
    constraint variables that are already set.
    """
    # By default, we cannot infer anything.
    return False

infer(context: InferenceContext) -> AttributeCovT

Infer the attribute given the the values for all variables.

Raises an exception if the attribute cannot be inferred. If can_infer returns True with the given constraint variables, this method should not raise an exception.

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    """
    Infer the attribute given the the values for all variables.

    Raises an exception if the attribute cannot be inferred. If `can_infer`
    returns `True` with the given constraint variables, this method should
    not raise an exception.
    """
    raise ValueError(f"Cannot infer attribute from constraint {self}")

get_bases() -> set[type[Attribute]] | None

Get a set of base types that can satisfy this constraint, if there exists a finite collection, or None otherwise.

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    """
    Get a set of base types that can satisfy this constraint, if there exists
    a finite collection, or None otherwise.
    """
    return None

relax_constraint(other: AttrConstraint[AttributeCovT]) -> AttrConstraint[AttributeCovT] | None

Attempt to relax this constraint by merging it with other, returning the result if successful.

Source code in xdsl/irdl/constraints.py
def relax_constraint(
    self, other: AttrConstraint[AttributeCovT]
) -> AttrConstraint[AttributeCovT] | None:
    """
    Attempt to relax this constraint by merging it with `other`,
    returning the result if successful.
    """
    return self if self == other else None

__or__(value: AttrConstraint[_AttributeCovT]) -> AttrConstraint[AttributeCovT | _AttributeCovT]

Source code in xdsl/irdl/constraints.py
def __or__(
    self, value: AttrConstraint[_AttributeCovT], /
) -> AttrConstraint[AttributeCovT | _AttributeCovT]:
    if isinstance(value, AnyAttr) or self == value:
        return value  # pyright: ignore[reportReturnType]
    return AnyOf.get(self, value)

__and__(value: AttrConstraint) -> AttrConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def __and__(self, value: AttrConstraint, /) -> AttrConstraint[AttributeCovT]:
    if isinstance(value, AnyAttr) or self == value:
        return self
    return AllOf((self, value))  # pyright: ignore[reportReturnType]

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[AttributeCovT] abstractmethod

A helper function to make type vars used in attribute definitions concrete when creating constraints for new attributes or operations.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[AttributeCovT]:
    """
    A helper function to make type vars used in attribute definitions concrete when
    creating constraints for new attributes or operations.
    """
    raise NotImplementedError(
        "Custom constraints must map type vars in nested constraints, if any."
    )

AnyAttr dataclass

Bases: AttrConstraint

Constraint that is verified by all attributes.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AnyAttr(AttrConstraint):
    """Constraint that is verified by all attributes."""

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        pass

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AnyAttr:
        return self

    def __and__(self, value: AttrConstraint[AttributeCovT], /):
        return value

__init__() -> None

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    pass

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AnyAttr

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AnyAttr:
    return self

__and__(value: AttrConstraint[AttributeCovT])

Source code in xdsl/irdl/constraints.py
def __and__(self, value: AttrConstraint[AttributeCovT], /):
    return value

VarConstraint dataclass

Bases: AttrConstraint[AttributeCovT]

Constrain an attribute with the given constraint, and constrain all occurences of this constraint (i.e, sharing the same name) to be equal.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class VarConstraint(AttrConstraint[AttributeCovT]):
    """
    Constrain an attribute with the given constraint, and constrain all occurences
    of this constraint (i.e, sharing the same name) to be equal.
    """

    name: str
    """The variable name. All uses of that name refer to the same variable."""

    constraint: AttrConstraint[AttributeCovT]
    """The constraint that the variable must satisfy."""

    @staticmethod
    def get(name: str, constraint: IRDLAttrConstraint[AttributeCovT] = AnyAttr()):
        from xdsl.irdl import irdl_to_attr_constraint

        return VarConstraint(name, irdl_to_attr_constraint(constraint))

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        if constraint_context.set_attr_variable(self.name, attr):
            self.constraint.verify(attr, constraint_context)

    def variables(self) -> set[str]:
        return self.constraint.variables() | {self.name}

    def infer(self, context: InferenceContext) -> AttributeCovT:
        v = context.get_variable(self.name)
        if v is None:
            return self.constraint.infer(context)
        return cast(AttributeCovT, v)

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return self.name in var_constraint_names or self.constraint.can_infer(
            var_constraint_names
        )

    def get_bases(self) -> set[type[Attribute]] | None:
        return self.constraint.get_bases()

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> VarConstraint[AttributeCovT]:
        return VarConstraint(
            self.name, self.constraint.mapping_type_vars(type_var_mapping)
        )

name: str instance-attribute

The variable name. All uses of that name refer to the same variable.

constraint: AttrConstraint[AttributeCovT] instance-attribute

The constraint that the variable must satisfy.

__init__(name: str, constraint: AttrConstraint[AttributeCovT]) -> None

get(name: str, constraint: IRDLAttrConstraint[AttributeCovT] = AnyAttr()) staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(name: str, constraint: IRDLAttrConstraint[AttributeCovT] = AnyAttr()):
    from xdsl.irdl import irdl_to_attr_constraint

    return VarConstraint(name, irdl_to_attr_constraint(constraint))

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    if constraint_context.set_attr_variable(self.name, attr):
        self.constraint.verify(attr, constraint_context)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constraint.variables() | {self.name}

infer(context: InferenceContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    v = context.get_variable(self.name)
    if v is None:
        return self.constraint.infer(context)
    return cast(AttributeCovT, v)

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.name in var_constraint_names or self.constraint.can_infer(
        var_constraint_names
    )

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    return self.constraint.get_bases()

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> VarConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> VarConstraint[AttributeCovT]:
    return VarConstraint(
        self.name, self.constraint.mapping_type_vars(type_var_mapping)
    )

TypeVarConstraint dataclass

Bases: AttrConstraint

Stores the TypeVar instance used to define a generic ParametrizedAttribute.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class TypeVarConstraint(AttrConstraint):
    """
    Stores the TypeVar instance used to define a generic ParametrizedAttribute.
    """

    type_var: TypeVar
    """The instance of the TypeVar used in the definition."""

    base_constraint: AttrConstraint
    """Constraint inferred from the base of the TypeVar."""

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        self.base_constraint.verify(attr, constraint_context)

    def get_bases(self) -> set[type[Attribute]] | None:
        return self.base_constraint.get_bases()

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint:
        res = type_var_mapping.get(self.type_var)
        if res is None:
            raise KeyError(f"Mapping value missing for type var {self.type_var}")
        if not isinstance(res, AttrConstraint):
            raise ValueError(f"Unexpected constraint {res} for TypeVar {self.type_var}")
        return res

type_var: TypeVar instance-attribute

The instance of the TypeVar used in the definition.

base_constraint: AttrConstraint instance-attribute

Constraint inferred from the base of the TypeVar.

__init__(type_var: TypeVar, base_constraint: AttrConstraint) -> None

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    self.base_constraint.verify(attr, constraint_context)

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    return self.base_constraint.get_bases()

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint:
    res = type_var_mapping.get(self.type_var)
    if res is None:
        raise KeyError(f"Mapping value missing for type var {self.type_var}")
    if not isinstance(res, AttrConstraint):
        raise ValueError(f"Unexpected constraint {res} for TypeVar {self.type_var}")
    return res

EqAttrConstraint dataclass

Bases: AttrConstraint[AttributeCovT], Generic[AttributeCovT]

Constrain an attribute to be equal to another attribute.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class EqAttrConstraint(AttrConstraint[AttributeCovT], Generic[AttributeCovT]):
    """Constrain an attribute to be equal to another attribute."""

    attr: AttributeCovT
    """The attribute we want to check equality with."""

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        if attr != self.attr:
            raise VerifyException(f"Expected attribute {self.attr} but got {attr}")

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return True

    def infer(self, context: InferenceContext) -> AttributeCovT:
        return self.attr

    def get_bases(self) -> set[type[Attribute]] | None:
        return {type(self.attr)}

    def relax_constraint(
        self, other: AttrConstraint[AttributeCovT]
    ) -> AttrConstraint[AttributeCovT] | None:
        if isinstance(other, AttrSetConstraint):
            return AttrSetConstraint.get(self.attr, *other.values)
        if isinstance(other, EqAttrConstraint):
            return AttrSetConstraint.get(self.attr, other.attr)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[AttributeCovT]:
        return self

attr: AttributeCovT instance-attribute

The attribute we want to check equality with.

__init__(attr: AttributeCovT) -> None

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    if attr != self.attr:
        raise VerifyException(f"Expected attribute {self.attr} but got {attr}")

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: InferenceContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    return self.attr

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    return {type(self.attr)}

relax_constraint(other: AttrConstraint[AttributeCovT]) -> AttrConstraint[AttributeCovT] | None

Source code in xdsl/irdl/constraints.py
def relax_constraint(
    self, other: AttrConstraint[AttributeCovT]
) -> AttrConstraint[AttributeCovT] | None:
    if isinstance(other, AttrSetConstraint):
        return AttrSetConstraint.get(self.attr, *other.values)
    if isinstance(other, EqAttrConstraint):
        return AttrSetConstraint.get(self.attr, other.attr)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[AttributeCovT]:
    return self

AttrSetConstraint dataclass

Bases: AttrConstraint[AttributeCovT], Generic[AttributeCovT]

Constrain an attribute to be one of a set of attributes.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AttrSetConstraint(AttrConstraint[AttributeCovT], Generic[AttributeCovT]):
    """Constrain an attribute to be one of a set of attributes."""

    values: frozenset[AttributeCovT]

    def __repr__(self) -> str:
        values = ", ".join(sorted(repr(value) for value in self.values))
        return f"AttrSetConstraint(frozenset([{values}]))"

    @staticmethod
    def get(*values: AttributeInvT) -> AttrConstraint[AttributeInvT]:
        s = frozenset(values)
        if len(s) == 1:
            return EqAttrConstraint(values[0])
        return AttrSetConstraint(s)

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        if attr not in self.values:
            raise VerifyException(
                f"Expected one of {', '.join(sorted(str(value) for value in self.values))}, but got {attr}"
            )

    def get_bases(self) -> set[type[Attribute]] | None:
        return {type(attr) for attr in self.values}

    def relax_constraint(
        self, other: AttrConstraint[AttributeCovT]
    ) -> AttrConstraint[AttributeCovT] | None:
        if isinstance(other, AttrSetConstraint):
            return AttrSetConstraint.get(*self.values, *other.values)
        if isinstance(other, EqAttrConstraint):
            return AttrSetConstraint.get(*self.values, other.attr)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[AttributeCovT]:
        return self

values: frozenset[AttributeCovT] instance-attribute

__init__(values: frozenset[AttributeCovT]) -> None

__repr__() -> str

Source code in xdsl/irdl/constraints.py
def __repr__(self) -> str:
    values = ", ".join(sorted(repr(value) for value in self.values))
    return f"AttrSetConstraint(frozenset([{values}]))"

get(*values: AttributeInvT) -> AttrConstraint[AttributeInvT] staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(*values: AttributeInvT) -> AttrConstraint[AttributeInvT]:
    s = frozenset(values)
    if len(s) == 1:
        return EqAttrConstraint(values[0])
    return AttrSetConstraint(s)

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    if attr not in self.values:
        raise VerifyException(
            f"Expected one of {', '.join(sorted(str(value) for value in self.values))}, but got {attr}"
        )

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    return {type(attr) for attr in self.values}

relax_constraint(other: AttrConstraint[AttributeCovT]) -> AttrConstraint[AttributeCovT] | None

Source code in xdsl/irdl/constraints.py
def relax_constraint(
    self, other: AttrConstraint[AttributeCovT]
) -> AttrConstraint[AttributeCovT] | None:
    if isinstance(other, AttrSetConstraint):
        return AttrSetConstraint.get(*self.values, *other.values)
    if isinstance(other, EqAttrConstraint):
        return AttrSetConstraint.get(*self.values, other.attr)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[AttributeCovT]:
    return self

BaseAttr dataclass

Bases: AttrConstraint[AttributeCovT], Generic[AttributeCovT]

Constrain an attribute to be of a given base type.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class BaseAttr(AttrConstraint[AttributeCovT], Generic[AttributeCovT]):
    """Constrain an attribute to be of a given base type."""

    attr: type[AttributeCovT]
    """The expected attribute base type."""

    def __repr__(self):
        return f"BaseAttr({self.attr.__name__})"

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        if not isinstance(attr, self.attr):
            if hasattr(self.attr, "name"):
                raise VerifyException(
                    f"{attr} should be of base attribute {self.attr.name}"
                )
            else:
                raise VerifyException(
                    f"{attr} should be of attribute subclassing `{self.attr.__name__}`"
                )

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return (
            is_runtime_final(self.attr)
            and issubclass(self.attr, ParametrizedAttribute)
            and not self.attr.get_irdl_definition().parameters
        )

    def infer(self, context: InferenceContext) -> AttributeCovT:
        assert issubclass(self.attr, ParametrizedAttribute)
        attr = self.attr.new(())
        return attr

    def get_bases(self) -> set[type[Attribute]] | None:
        if is_runtime_final(self.attr):
            return {self.attr}
        return None

    def relax_constraint(
        self, other: AttrConstraint[AttributeCovT]
    ) -> AttrConstraint[AttributeCovT] | None:
        if not isinstance(other, BaseAttr):
            # Trying to match on ParamAttrConstraint does strange things to pyright
            # so we just appeal to symmetry instead.
            return other.relax_constraint(self)
        return super().relax_constraint(other)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[AttributeCovT]:
        return self

attr: type[AttributeCovT] instance-attribute

The expected attribute base type.

__init__(attr: type[AttributeCovT]) -> None

__repr__()

Source code in xdsl/irdl/constraints.py
def __repr__(self):
    return f"BaseAttr({self.attr.__name__})"

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    if not isinstance(attr, self.attr):
        if hasattr(self.attr, "name"):
            raise VerifyException(
                f"{attr} should be of base attribute {self.attr.name}"
            )
        else:
            raise VerifyException(
                f"{attr} should be of attribute subclassing `{self.attr.__name__}`"
            )

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return (
        is_runtime_final(self.attr)
        and issubclass(self.attr, ParametrizedAttribute)
        and not self.attr.get_irdl_definition().parameters
    )

infer(context: InferenceContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    assert issubclass(self.attr, ParametrizedAttribute)
    attr = self.attr.new(())
    return attr

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    if is_runtime_final(self.attr):
        return {self.attr}
    return None

relax_constraint(other: AttrConstraint[AttributeCovT]) -> AttrConstraint[AttributeCovT] | None

Source code in xdsl/irdl/constraints.py
def relax_constraint(
    self, other: AttrConstraint[AttributeCovT]
) -> AttrConstraint[AttributeCovT] | None:
    if not isinstance(other, BaseAttr):
        # Trying to match on ParamAttrConstraint does strange things to pyright
        # so we just appeal to symmetry instead.
        return other.relax_constraint(self)
    return super().relax_constraint(other)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[AttributeCovT]:
    return self

AnyOf dataclass

Bases: AttrConstraint[AttributeCovT], Generic[AttributeCovT]

Ensure that an attribute satisfies one of the given constraints.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True, init=False)
class AnyOf(AttrConstraint[AttributeCovT], Generic[AttributeCovT]):
    """Ensure that an attribute satisfies one of the given constraints."""

    attr_constrs: tuple[AttrConstraint[AttributeCovT], ...]
    """
    The tuple of attribute constraints that are checked by this `AnyOf` constraint.

    At most one constraint may be "abstract": an abstract constraint is a `BaseAttr`
    for an abstract base class which can be inherited by other attribute classes.
    This abstract attribute type is not runtime-final (i.e., does not have the `@irdl_attr_definition` decorator).
    """

    _based_constrs: dict[type[Attribute], AttrConstraint[AttributeCovT]] = field(
        hash=False, repr=False
    )
    _abstr_constr: AttrConstraint[AttributeCovT] | None = field(hash=False, repr=False)

    @staticmethod
    def get(
        *attr_constrs: IRDLAttrConstraint[AttributeInvT],
    ) -> AttrConstraint[AttributeInvT]:
        from xdsl.irdl import irdl_to_attr_constraint

        constrs = list(irdl_to_attr_constraint(c) for c in attr_constrs)
        # Iterate through the constraints looking for optimisations
        i = 0
        while i < len(constrs):
            c = constrs[i]
            if c == AnyAttr():
                return cast(AttrConstraint[AttributeInvT], AnyAttr())
            if isinstance(c, AnyOf):
                constrs = constrs[:i] + list(c.attr_constrs) + constrs[i + 1 :]
                continue

            # This is a quadratic check, but should likely be fine in practice
            merged = False
            for k, c2 in enumerate(constrs[:i]):
                if (v := c2.relax_constraint(c)) is not None:
                    merged = True
                    constrs[k] = v
                    constrs.pop(i)
                    break
            if not merged:
                i += 1

        if len(constrs) == 1:
            return constrs[0]

        return AnyOf(tuple(constrs))

    def __init__(
        self,
        attr_constrs: tuple[AttrConstraint[AttributeCovT], ...],
    ):
        based_constrs = dict[type[Attribute], AttrConstraint[AttributeCovT]]()
        abstr_constr: AttrConstraint[AttributeCovT] | None = None
        for i, c in enumerate(attr_constrs):
            b = c.get_bases()
            if b is None:
                if abstr_constr is not None:
                    raise PyRDLError(
                        f"Cannot form `AnyOf` constraint with both {c} and {abstr_constr}, "
                        "as they cannot be verified as disjoint."
                    )
                if not isinstance(c, BaseAttr) or is_runtime_final(c.attr):
                    raise PyRDLError(
                        f"Constraint in `AnyOf` without bases must be a `BaseAttr` "
                        f"of a non-final abstract attribute class, got {c} instead."
                    )
                abstr_constr = c
                continue

            if not b.isdisjoint(based_constrs.keys()):
                raise PyRDLError(
                    f"Constraint {c} shares a base with a constraint "
                    f"in {set(attr_constrs[0:i])} in `AnyOf` constraint."
                )

            for base in b:
                based_constrs[base] = c

        # check for overlaps with the abstract constraint
        if abstr_constr is not None:
            # bases should not overlap via issubclass
            for base in based_constrs.keys():
                if issubclass(base, abstr_constr.attr):
                    raise PyRDLError(
                        f"Constraint {based_constrs[base]} overlaps with "
                        f"the constraint {abstr_constr} in `AnyOf` constraint."
                    )

        object.__setattr__(
            self,
            "attr_constrs",
            attr_constrs,
        )
        object.__setattr__(
            self,
            "_based_constrs",
            based_constrs,
        )
        object.__setattr__(self, "_abstr_constr", abstr_constr)

    def verify(self, attr: Attribute, constraint_context: VerificationContext) -> None:
        constr = self._based_constrs.get(attr.__class__)
        if constr is not None:
            constr.verify(attr, constraint_context)
            return
        # Try abstract constraint if present
        if self._abstr_constr is not None:
            self._abstr_constr.verify(attr, constraint_context)
            return
        raise VerifyException(f"Unexpected attribute {attr}")

    def variables(self) -> set[str]:
        if not self.attr_constrs:
            return set()
        variables = self.attr_constrs[0].variables()
        for constr in self.attr_constrs[1:]:
            variables &= constr.variables()
        return variables

    def get_bases(self) -> set[type[Attribute]] | None:
        bases = set[type[Attribute]]()
        for constr in self.attr_constrs:
            b = constr.get_bases()
            if b is None:
                return
            bases |= b
        return bases

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[AttributeCovT]:
        return AnyOf.get(
            *(c.mapping_type_vars(type_var_mapping) for c in self.attr_constrs)
        )

attr_constrs: tuple[AttrConstraint[AttributeCovT], ...] instance-attribute

The tuple of attribute constraints that are checked by this AnyOf constraint.

At most one constraint may be "abstract": an abstract constraint is a BaseAttr for an abstract base class which can be inherited by other attribute classes. This abstract attribute type is not runtime-final (i.e., does not have the @irdl_attr_definition decorator).

get(*attr_constrs: IRDLAttrConstraint[AttributeInvT]) -> AttrConstraint[AttributeInvT] staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(
    *attr_constrs: IRDLAttrConstraint[AttributeInvT],
) -> AttrConstraint[AttributeInvT]:
    from xdsl.irdl import irdl_to_attr_constraint

    constrs = list(irdl_to_attr_constraint(c) for c in attr_constrs)
    # Iterate through the constraints looking for optimisations
    i = 0
    while i < len(constrs):
        c = constrs[i]
        if c == AnyAttr():
            return cast(AttrConstraint[AttributeInvT], AnyAttr())
        if isinstance(c, AnyOf):
            constrs = constrs[:i] + list(c.attr_constrs) + constrs[i + 1 :]
            continue

        # This is a quadratic check, but should likely be fine in practice
        merged = False
        for k, c2 in enumerate(constrs[:i]):
            if (v := c2.relax_constraint(c)) is not None:
                merged = True
                constrs[k] = v
                constrs.pop(i)
                break
        if not merged:
            i += 1

    if len(constrs) == 1:
        return constrs[0]

    return AnyOf(tuple(constrs))

__init__(attr_constrs: tuple[AttrConstraint[AttributeCovT], ...])

Source code in xdsl/irdl/constraints.py
def __init__(
    self,
    attr_constrs: tuple[AttrConstraint[AttributeCovT], ...],
):
    based_constrs = dict[type[Attribute], AttrConstraint[AttributeCovT]]()
    abstr_constr: AttrConstraint[AttributeCovT] | None = None
    for i, c in enumerate(attr_constrs):
        b = c.get_bases()
        if b is None:
            if abstr_constr is not None:
                raise PyRDLError(
                    f"Cannot form `AnyOf` constraint with both {c} and {abstr_constr}, "
                    "as they cannot be verified as disjoint."
                )
            if not isinstance(c, BaseAttr) or is_runtime_final(c.attr):
                raise PyRDLError(
                    f"Constraint in `AnyOf` without bases must be a `BaseAttr` "
                    f"of a non-final abstract attribute class, got {c} instead."
                )
            abstr_constr = c
            continue

        if not b.isdisjoint(based_constrs.keys()):
            raise PyRDLError(
                f"Constraint {c} shares a base with a constraint "
                f"in {set(attr_constrs[0:i])} in `AnyOf` constraint."
            )

        for base in b:
            based_constrs[base] = c

    # check for overlaps with the abstract constraint
    if abstr_constr is not None:
        # bases should not overlap via issubclass
        for base in based_constrs.keys():
            if issubclass(base, abstr_constr.attr):
                raise PyRDLError(
                    f"Constraint {based_constrs[base]} overlaps with "
                    f"the constraint {abstr_constr} in `AnyOf` constraint."
                )

    object.__setattr__(
        self,
        "attr_constrs",
        attr_constrs,
    )
    object.__setattr__(
        self,
        "_based_constrs",
        based_constrs,
    )
    object.__setattr__(self, "_abstr_constr", abstr_constr)

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, attr: Attribute, constraint_context: VerificationContext) -> None:
    constr = self._based_constrs.get(attr.__class__)
    if constr is not None:
        constr.verify(attr, constraint_context)
        return
    # Try abstract constraint if present
    if self._abstr_constr is not None:
        self._abstr_constr.verify(attr, constraint_context)
        return
    raise VerifyException(f"Unexpected attribute {attr}")

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    if not self.attr_constrs:
        return set()
    variables = self.attr_constrs[0].variables()
    for constr in self.attr_constrs[1:]:
        variables &= constr.variables()
    return variables

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    bases = set[type[Attribute]]()
    for constr in self.attr_constrs:
        b = constr.get_bases()
        if b is None:
            return
        bases |= b
    return bases

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[AttributeCovT]:
    return AnyOf.get(
        *(c.mapping_type_vars(type_var_mapping) for c in self.attr_constrs)
    )

AllOf dataclass

Bases: AttrConstraint[AttributeCovT]

Ensure that an attribute satisfies all the given constraints.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AllOf(AttrConstraint[AttributeCovT]):
    """Ensure that an attribute satisfies all the given constraints."""

    attr_constrs: tuple[AttrConstraint[AttributeCovT], ...]
    """The list of constraints that are checked."""

    @staticmethod
    def get(
        *attr_constrs: IRDLAttrConstraint[AttributeInvT],
    ) -> AttrConstraint[AttributeInvT]:
        from xdsl.irdl import irdl_to_attr_constraint

        constrs = list(irdl_to_attr_constraint(c) for c in attr_constrs)
        # Iterate through the constraints looking for optimisations
        i = 0
        while i < len(constrs):
            c = constrs[i]
            if c == AnyAttr():
                constrs.pop(i)
                continue
            if isinstance(c, AllOf):
                constrs = constrs[:i] + list(c.attr_constrs) + constrs[i + 1 :]
                continue
            i += 1

        if len(constrs) == 0:
            return cast(AttrConstraint[AttributeInvT], AnyAttr())
        if len(constrs) == 1:
            return constrs[0]

        return AllOf(tuple(constrs))

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        exc_bucket: list[VerifyException] = []

        for attr_constr in self.attr_constrs:
            try:
                attr_constr.verify(attr, constraint_context)
            except VerifyException as e:
                exc_bucket.append(e)

        if len(exc_bucket):
            if len(exc_bucket) == 1:
                raise VerifyException(str(exc_bucket[0])) from exc_bucket[0]
            exc_msg = "The following constraints were not satisfied:\n"
            exc_msg += "\n".join([str(e) for e in exc_bucket])
            raise VerifyException(exc_msg)

    def variables(self) -> set[str]:
        vars = set[str]()
        for constr in self.attr_constrs:
            vars |= constr.variables()
        return vars

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return any(
            constr.can_infer(var_constraint_names) for constr in self.attr_constrs
        )

    def infer(self, context: InferenceContext) -> AttributeCovT:
        for constr in self.attr_constrs:
            if constr.can_infer(context.attr_variables):
                return constr.infer(context)
        raise ValueError("Cannot infer attribute from constraint")

    def get_bases(self) -> set[type[Attribute]] | None:
        bases: set[type[Attribute]] | None = None
        for constr in self.attr_constrs:
            b = constr.get_bases()
            if b is None:
                continue
            if bases is None:
                bases = b
            else:
                bases &= b
        return bases

    def __and__(self, value: AttrConstraint, /) -> AllOf[AttributeCovT]:
        return AllOf((*self.attr_constrs, value))  # pyright: ignore[reportReturnType]

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AllOf[AttributeCovT]:
        return AllOf(
            tuple(c.mapping_type_vars(type_var_mapping) for c in self.attr_constrs)
        )

attr_constrs: tuple[AttrConstraint[AttributeCovT], ...] instance-attribute

The list of constraints that are checked.

__init__(attr_constrs: tuple[AttrConstraint[AttributeCovT], ...]) -> None

get(*attr_constrs: IRDLAttrConstraint[AttributeInvT]) -> AttrConstraint[AttributeInvT] staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(
    *attr_constrs: IRDLAttrConstraint[AttributeInvT],
) -> AttrConstraint[AttributeInvT]:
    from xdsl.irdl import irdl_to_attr_constraint

    constrs = list(irdl_to_attr_constraint(c) for c in attr_constrs)
    # Iterate through the constraints looking for optimisations
    i = 0
    while i < len(constrs):
        c = constrs[i]
        if c == AnyAttr():
            constrs.pop(i)
            continue
        if isinstance(c, AllOf):
            constrs = constrs[:i] + list(c.attr_constrs) + constrs[i + 1 :]
            continue
        i += 1

    if len(constrs) == 0:
        return cast(AttrConstraint[AttributeInvT], AnyAttr())
    if len(constrs) == 1:
        return constrs[0]

    return AllOf(tuple(constrs))

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    exc_bucket: list[VerifyException] = []

    for attr_constr in self.attr_constrs:
        try:
            attr_constr.verify(attr, constraint_context)
        except VerifyException as e:
            exc_bucket.append(e)

    if len(exc_bucket):
        if len(exc_bucket) == 1:
            raise VerifyException(str(exc_bucket[0])) from exc_bucket[0]
        exc_msg = "The following constraints were not satisfied:\n"
        exc_msg += "\n".join([str(e) for e in exc_bucket])
        raise VerifyException(exc_msg)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    vars = set[str]()
    for constr in self.attr_constrs:
        vars |= constr.variables()
    return vars

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return any(
        constr.can_infer(var_constraint_names) for constr in self.attr_constrs
    )

infer(context: InferenceContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    for constr in self.attr_constrs:
        if constr.can_infer(context.attr_variables):
            return constr.infer(context)
    raise ValueError("Cannot infer attribute from constraint")

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    bases: set[type[Attribute]] | None = None
    for constr in self.attr_constrs:
        b = constr.get_bases()
        if b is None:
            continue
        if bases is None:
            bases = b
        else:
            bases &= b
    return bases

__and__(value: AttrConstraint) -> AllOf[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def __and__(self, value: AttrConstraint, /) -> AllOf[AttributeCovT]:
    return AllOf((*self.attr_constrs, value))  # pyright: ignore[reportReturnType]

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AllOf[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AllOf[AttributeCovT]:
    return AllOf(
        tuple(c.mapping_type_vars(type_var_mapping) for c in self.attr_constrs)
    )

ParamAttrConstraint dataclass

Bases: AttrConstraint[ParametrizedAttributeCovT], Generic[ParametrizedAttributeCovT]

Constrain an attribute to be of a given type, and also constrain its parameters with additional constraints.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class ParamAttrConstraint(
    AttrConstraint[ParametrizedAttributeCovT], Generic[ParametrizedAttributeCovT]
):
    """
    Constrain an attribute to be of a given type,
    and also constrain its parameters with additional constraints.
    """

    base_attr: type[ParametrizedAttributeCovT]
    """The base attribute type."""

    param_constrs: tuple[AttrConstraint, ...]
    """The attribute parameter constraints"""

    @staticmethod
    def get(
        base_attr: type[ParametrizedAttributeT],
        *param_constrs: IRDLAttrConstraint | None,
    ) -> AttrConstraint[ParametrizedAttributeT]:
        from xdsl.irdl import irdl_to_attr_constraint

        constrs = tuple(
            irdl_to_attr_constraint(constr) if constr is not None else AnyAttr()
            for constr in param_constrs
        )

        # We don't want to allow instantiated generics here, as they don't get checked
        if get_origin(base_attr) is not None:
            raise PyRDLError(
                f"Argument to ParamAttConstraint {base_attr} should not be an instantiated generic"
            )

        if is_runtime_final(base_attr) and all(
            isinstance(c, EqAttrConstraint) for c in constrs
        ):
            return EqAttrConstraint(
                base_attr.new(tuple(cast(EqAttrConstraint, c).attr for c in constrs))
            )

        if all(c == AnyAttr() for c in constrs):
            return BaseAttr(base_attr)

        return ParamAttrConstraint[ParametrizedAttributeT](base_attr, constrs)

    def __repr__(self):
        return f"ParamAttrConstraint({self.base_attr.__name__}, {self.param_constrs!r})"

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        if not isinstance(attr, self.base_attr):
            raise VerifyException(
                f"{attr} should be of base attribute {self.base_attr.name}"
            )
        parameters = attr.parameters
        if len(self.param_constrs) != len(parameters):
            raise VerifyException(
                f"{len(self.param_constrs)} parameters expected, "
                f"but got {len(parameters)}"
            )
        for idx, param_constr in enumerate(self.param_constrs):
            param_constr.verify(parameters[idx], constraint_context)

    def variables(self) -> set[str]:
        vars = set[str]()
        for constr in self.param_constrs:
            vars |= constr.variables()
        return vars

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return is_runtime_final(self.base_attr) and all(
            constr.can_infer(var_constraint_names) for constr in self.param_constrs
        )

    def infer(self, context: InferenceContext) -> ParametrizedAttributeCovT:
        params = tuple(constr.infer(context) for constr in self.param_constrs)
        attr = self.base_attr.new(params)
        return attr

    def get_bases(self) -> set[type[Attribute]] | None:
        if is_runtime_final(self.base_attr):
            return {self.base_attr}
        return None

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint[ParametrizedAttributeCovT]:
        return ParamAttrConstraint.get(
            self.base_attr,
            *(c.mapping_type_vars(type_var_mapping) for c in self.param_constrs),
        )

    def relax_constraint(
        self, other: AttrConstraint[ParametrizedAttributeCovT]
    ) -> AttrConstraint[ParametrizedAttributeCovT] | None:
        if isinstance(other, BaseAttr):
            if self.base_attr == other.attr:
                return other
            return
        if not isinstance(other, ParamAttrConstraint):
            return
        if self.base_attr != other.base_attr:
            return
        seen_difference = False
        new_params: list[AttrConstraint] = []
        for x, y in zip(self.param_constrs, other.param_constrs, strict=True):
            if x == y:
                new_params.append(x)
            elif seen_difference:
                return
            else:
                seen_difference = True
                new_params.append(x | y)

        return ParamAttrConstraint(self.base_attr, tuple(new_params))

base_attr: type[ParametrizedAttributeCovT] instance-attribute

The base attribute type.

param_constrs: tuple[AttrConstraint, ...] instance-attribute

The attribute parameter constraints

__init__(base_attr: type[ParametrizedAttributeCovT], param_constrs: tuple[AttrConstraint, ...]) -> None

get(base_attr: type[ParametrizedAttributeT], *param_constrs: IRDLAttrConstraint | None) -> AttrConstraint[ParametrizedAttributeT] staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(
    base_attr: type[ParametrizedAttributeT],
    *param_constrs: IRDLAttrConstraint | None,
) -> AttrConstraint[ParametrizedAttributeT]:
    from xdsl.irdl import irdl_to_attr_constraint

    constrs = tuple(
        irdl_to_attr_constraint(constr) if constr is not None else AnyAttr()
        for constr in param_constrs
    )

    # We don't want to allow instantiated generics here, as they don't get checked
    if get_origin(base_attr) is not None:
        raise PyRDLError(
            f"Argument to ParamAttConstraint {base_attr} should not be an instantiated generic"
        )

    if is_runtime_final(base_attr) and all(
        isinstance(c, EqAttrConstraint) for c in constrs
    ):
        return EqAttrConstraint(
            base_attr.new(tuple(cast(EqAttrConstraint, c).attr for c in constrs))
        )

    if all(c == AnyAttr() for c in constrs):
        return BaseAttr(base_attr)

    return ParamAttrConstraint[ParametrizedAttributeT](base_attr, constrs)

__repr__()

Source code in xdsl/irdl/constraints.py
def __repr__(self):
    return f"ParamAttrConstraint({self.base_attr.__name__}, {self.param_constrs!r})"

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    if not isinstance(attr, self.base_attr):
        raise VerifyException(
            f"{attr} should be of base attribute {self.base_attr.name}"
        )
    parameters = attr.parameters
    if len(self.param_constrs) != len(parameters):
        raise VerifyException(
            f"{len(self.param_constrs)} parameters expected, "
            f"but got {len(parameters)}"
        )
    for idx, param_constr in enumerate(self.param_constrs):
        param_constr.verify(parameters[idx], constraint_context)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    vars = set[str]()
    for constr in self.param_constrs:
        vars |= constr.variables()
    return vars

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return is_runtime_final(self.base_attr) and all(
        constr.can_infer(var_constraint_names) for constr in self.param_constrs
    )

infer(context: InferenceContext) -> ParametrizedAttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> ParametrizedAttributeCovT:
    params = tuple(constr.infer(context) for constr in self.param_constrs)
    attr = self.base_attr.new(params)
    return attr

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    if is_runtime_final(self.base_attr):
        return {self.base_attr}
    return None

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint[ParametrizedAttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint[ParametrizedAttributeCovT]:
    return ParamAttrConstraint.get(
        self.base_attr,
        *(c.mapping_type_vars(type_var_mapping) for c in self.param_constrs),
    )

relax_constraint(other: AttrConstraint[ParametrizedAttributeCovT]) -> AttrConstraint[ParametrizedAttributeCovT] | None

Source code in xdsl/irdl/constraints.py
def relax_constraint(
    self, other: AttrConstraint[ParametrizedAttributeCovT]
) -> AttrConstraint[ParametrizedAttributeCovT] | None:
    if isinstance(other, BaseAttr):
        if self.base_attr == other.attr:
            return other
        return
    if not isinstance(other, ParamAttrConstraint):
        return
    if self.base_attr != other.base_attr:
        return
    seen_difference = False
    new_params: list[AttrConstraint] = []
    for x, y in zip(self.param_constrs, other.param_constrs, strict=True):
        if x == y:
            new_params.append(x)
        elif seen_difference:
            return
        else:
            seen_difference = True
            new_params.append(x | y)

    return ParamAttrConstraint(self.base_attr, tuple(new_params))

MessageConstraint dataclass

Bases: AttrConstraint[AttributeCovT]

Attach a message to a constraint, to provide more context when the constraint is not satisfied.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True, init=False)
class MessageConstraint(AttrConstraint[AttributeCovT]):
    """
    Attach a message to a constraint, to provide more context when the constraint
    is not satisfied.
    """

    constr: AttrConstraint[AttributeCovT]
    message: str

    def __init__(
        self,
        constr: (AttrConstraint[AttributeCovT] | AttributeCovT | type[AttributeCovT]),
        message: str,
    ):
        from xdsl.irdl import irdl_to_attr_constraint

        object.__setattr__(self, "constr", irdl_to_attr_constraint(constr))
        object.__setattr__(self, "message", message)

    def verify(
        self,
        attr: Attribute,
        constraint_context: VerificationContext,
    ) -> None:
        try:
            return self.constr.verify(attr, constraint_context)
        except VerifyException as e:
            raise VerifyException(
                f"{self.message}\nUnderlying verification failure: {e.args[0]}",
                *e.args[1:],
            )

    def variables(self) -> set[str]:
        return self.constr.variables()

    def get_bases(self) -> set[type[Attribute]] | None:
        return self.constr.get_bases()

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return self.constr.can_infer(var_constraint_names)

    def infer(self, context: InferenceContext) -> AttributeCovT:
        return self.constr.infer(context)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> MessageConstraint[AttributeCovT]:
        return MessageConstraint(
            self.constr.mapping_type_vars(type_var_mapping), self.message
        )

constr: AttrConstraint[AttributeCovT] instance-attribute

message: str instance-attribute

__init__(constr: AttrConstraint[AttributeCovT] | AttributeCovT | type[AttributeCovT], message: str)

Source code in xdsl/irdl/constraints.py
def __init__(
    self,
    constr: (AttrConstraint[AttributeCovT] | AttributeCovT | type[AttributeCovT]),
    message: str,
):
    from xdsl.irdl import irdl_to_attr_constraint

    object.__setattr__(self, "constr", irdl_to_attr_constraint(constr))
    object.__setattr__(self, "message", message)

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attr: Attribute,
    constraint_context: VerificationContext,
) -> None:
    try:
        return self.constr.verify(attr, constraint_context)
    except VerifyException as e:
        raise VerifyException(
            f"{self.message}\nUnderlying verification failure: {e.args[0]}",
            *e.args[1:],
        )

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constr.variables()

get_bases() -> set[type[Attribute]] | None

Source code in xdsl/irdl/constraints.py
def get_bases(self) -> set[type[Attribute]] | None:
    return self.constr.get_bases()

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.constr.can_infer(var_constraint_names)

infer(context: InferenceContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> AttributeCovT:
    return self.constr.infer(context)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> MessageConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> MessageConstraint[AttributeCovT]:
    return MessageConstraint(
        self.constr.mapping_type_vars(type_var_mapping), self.message
    )

IntConstraint dataclass

Bases: ABC

Constrain an integer to certain values.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class IntConstraint(ABC):
    """Constrain an integer to certain values."""

    @abstractmethod
    def verify(
        self,
        i: int,
        constraint_context: VerificationContext,
    ) -> None:
        """
        Check if the integer satisfies the constraint, or raise an exception otherwise.
        """
        ...

    def variables(self) -> set[str]:
        """
        Returns a set of the variables that can be extracted by this constraint.
        These variables are always expected to be set after running `verify`.
        """
        return set()

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        """
        Check if there is enough information to infer the integer given the
        constraint variables that are already set.
        """
        # By default, we cannot infer anything.
        return False

    def infer(self, context: InferenceContext) -> int:
        """
        Infer the attribute given the the values for all variables.

        Raises an exception if the attribute cannot be inferred. If `can_infer`
        returns `True` with the given constraint variables, this method should
        not raise an exception.
        """
        raise ValueError(f"Cannot infer integer from constraint {self}")

    @abstractmethod
    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        """
        A helper function to make type vars used in attribute definitions concrete when
        creating constraints for new attributes or operations.
        """
        raise NotImplementedError(
            "Custom constraints must map type vars in nested constraints, if any."
        )

__init__() -> None

verify(i: int, constraint_context: VerificationContext) -> None abstractmethod

Check if the integer satisfies the constraint, or raise an exception otherwise.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def verify(
    self,
    i: int,
    constraint_context: VerificationContext,
) -> None:
    """
    Check if the integer satisfies the constraint, or raise an exception otherwise.
    """
    ...

variables() -> set[str]

Returns a set of the variables that can be extracted by this constraint. These variables are always expected to be set after running verify.

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    """
    Returns a set of the variables that can be extracted by this constraint.
    These variables are always expected to be set after running `verify`.
    """
    return set()

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Check if there is enough information to infer the integer given the constraint variables that are already set.

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    """
    Check if there is enough information to infer the integer given the
    constraint variables that are already set.
    """
    # By default, we cannot infer anything.
    return False

infer(context: InferenceContext) -> int

Infer the attribute given the the values for all variables.

Raises an exception if the attribute cannot be inferred. If can_infer returns True with the given constraint variables, this method should not raise an exception.

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> int:
    """
    Infer the attribute given the the values for all variables.

    Raises an exception if the attribute cannot be inferred. If `can_infer`
    returns `True` with the given constraint variables, this method should
    not raise an exception.
    """
    raise ValueError(f"Cannot infer integer from constraint {self}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint abstractmethod

A helper function to make type vars used in attribute definitions concrete when creating constraints for new attributes or operations.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    """
    A helper function to make type vars used in attribute definitions concrete when
    creating constraints for new attributes or operations.
    """
    raise NotImplementedError(
        "Custom constraints must map type vars in nested constraints, if any."
    )

AnyInt dataclass

Bases: IntConstraint

Constraint that is verified by all integers.

Source code in xdsl/irdl/constraints.py
class AnyInt(IntConstraint):
    """
    Constraint that is verified by all integers.
    """

    def verify(self, i: int, constraint_context: VerificationContext) -> None:
        pass

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, i: int, constraint_context: VerificationContext) -> None:
    pass

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

EqIntConstraint dataclass

Bases: IntConstraint

Constrain an integer to a value.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class EqIntConstraint(IntConstraint):
    """Constrain an integer to a value."""

    value: int

    def verify(
        self,
        i: int,
        constraint_context: VerificationContext,
    ) -> None:
        if self.value != i:
            raise VerifyException(f"Invalid value {i}, expected {self.value}")

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return True

    def infer(self, context: InferenceContext) -> int:
        return self.value

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

value: int instance-attribute

__init__(value: int) -> None

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    i: int,
    constraint_context: VerificationContext,
) -> None:
    if self.value != i:
        raise VerifyException(f"Invalid value {i}, expected {self.value}")

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: InferenceContext) -> int

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> int:
    return self.value

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

NotEqualIntConstraint dataclass

Bases: IntConstraint

Constrain an integer to not be equal to a given value.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class NotEqualIntConstraint(IntConstraint):
    """Constrain an integer to not be equal to a given value."""

    value: int
    """The value the integer must not be equal to."""

    def verify(self, i: int, constraint_context: VerificationContext) -> None:
        if i == self.value:
            raise VerifyException(f"expected integer != {self.value}")

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

value: int instance-attribute

The value the integer must not be equal to.

__init__(value: int) -> None

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, i: int, constraint_context: VerificationContext) -> None:
    if i == self.value:
        raise VerifyException(f"expected integer != {self.value}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

IntSetConstraint dataclass

Bases: IntConstraint

Constrain an integer to one of a set of integers.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class IntSetConstraint(IntConstraint):
    """Constrain an integer to one of a set of integers."""

    values: frozenset[int]

    def __repr__(self) -> str:
        return f"IntSetConstraint({{{', '.join(str(x) for x in sorted(self.values))}}})"

    @staticmethod
    def get(*values: int) -> IntConstraint:
        unique_values = frozenset(values)
        if len(unique_values) == 1:
            return EqIntConstraint(values[0])
        return IntSetConstraint(unique_values)

    def verify(
        self,
        i: int,
        constraint_context: VerificationContext,
    ) -> None:
        if i not in self.values:
            raise VerifyException(
                f"Invalid value {i}, expected one of {{{', '.join(str(x) for x in sorted(self.values))}}}"
            )

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return len(self.values) == 1

    def infer(self, context: InferenceContext) -> int:
        return next(iter(self.values))

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

values: frozenset[int] instance-attribute

__init__(values: frozenset[int]) -> None

__repr__() -> str

Source code in xdsl/irdl/constraints.py
def __repr__(self) -> str:
    return f"IntSetConstraint({{{', '.join(str(x) for x in sorted(self.values))}}})"

get(*values: int) -> IntConstraint staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(*values: int) -> IntConstraint:
    unique_values = frozenset(values)
    if len(unique_values) == 1:
        return EqIntConstraint(values[0])
    return IntSetConstraint(unique_values)

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    i: int,
    constraint_context: VerificationContext,
) -> None:
    if i not in self.values:
        raise VerifyException(
            f"Invalid value {i}, expected one of {{{', '.join(str(x) for x in sorted(self.values))}}}"
        )

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return len(self.values) == 1

infer(context: InferenceContext) -> int

Source code in xdsl/irdl/constraints.py
def infer(self, context: InferenceContext) -> int:
    return next(iter(self.values))

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

AtLeast dataclass

Bases: IntConstraint

Constrain an integer to be at least a given value.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AtLeast(IntConstraint):
    """Constrain an integer to be at least a given value."""

    bound: int
    """The minimum value the integer can take."""

    def verify(self, i: int, constraint_context: VerificationContext) -> None:
        if i < self.bound:
            raise VerifyException(f"expected integer >= {self.bound}, got {i}")

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

bound: int instance-attribute

The minimum value the integer can take.

__init__(bound: int) -> None

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, i: int, constraint_context: VerificationContext) -> None:
    if i < self.bound:
        raise VerifyException(f"expected integer >= {self.bound}, got {i}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

AtMost dataclass

Bases: IntConstraint

Constrain an integer to be at most a given value.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AtMost(IntConstraint):
    """Constrain an integer to be at most a given value."""

    bound: int
    """The maximum value the integer can take."""

    def verify(self, i: int, constraint_context: VerificationContext) -> None:
        if i > self.bound:
            raise VerifyException(f"Expected integer <= {self.bound}, got {i}")

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return self

bound: int instance-attribute

The maximum value the integer can take.

__init__(bound: int) -> None

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, i: int, constraint_context: VerificationContext) -> None:
    if i > self.bound:
        raise VerifyException(f"Expected integer <= {self.bound}, got {i}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return self

IntVarConstraint dataclass

Bases: IntConstraint

Constrain an integer with the given constraint, and constrain all occurences of this constraint (i.e, sharing the same name) to be equal.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class IntVarConstraint(IntConstraint):
    """
    Constrain an integer with the given constraint, and constrain all occurences
    of this constraint (i.e, sharing the same name) to be equal.
    """

    name: str
    """The variable name. All uses of that name refer to the same variable."""

    constraint: IntConstraint
    """The constraint that the variable must satisfy."""

    @staticmethod
    def get(
        name: str, constraint: int | TypeForm[int] | IntConstraint = AnyInt()
    ) -> IntConstraint:
        if not isinstance(constraint, IntConstraint):
            from xdsl.irdl import get_int_constraint

            constraint = get_int_constraint(constraint)

        return IntVarConstraint(name, constraint)

    def verify(
        self,
        i: int,
        constraint_context: VerificationContext,
    ) -> None:
        if constraint_context.set_int_variable(self.name, i):
            self.constraint.verify(i, constraint_context)

    def variables(self) -> set[str]:
        return self.constraint.variables() | {self.name}

    def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
        return self.name in var_constraint_names or self.constraint.can_infer(
            var_constraint_names
        )

    def infer(
        self,
        context: InferenceContext,
    ) -> int:
        v = context.get_int_variable(self.name)
        if v is None:
            return self.constraint.infer(context)
        return v

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        return IntVarConstraint(
            self.name, self.constraint.mapping_type_vars(type_var_mapping)
        )

name: str instance-attribute

The variable name. All uses of that name refer to the same variable.

constraint: IntConstraint instance-attribute

The constraint that the variable must satisfy.

__init__(name: str, constraint: IntConstraint) -> None

get(name: str, constraint: int | TypeForm[int] | IntConstraint = AnyInt()) -> IntConstraint staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(
    name: str, constraint: int | TypeForm[int] | IntConstraint = AnyInt()
) -> IntConstraint:
    if not isinstance(constraint, IntConstraint):
        from xdsl.irdl import get_int_constraint

        constraint = get_int_constraint(constraint)

    return IntVarConstraint(name, constraint)

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    i: int,
    constraint_context: VerificationContext,
) -> None:
    if constraint_context.set_int_variable(self.name, i):
        self.constraint.verify(i, constraint_context)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constraint.variables() | {self.name}

can_infer(var_constraint_names: AbstractSet[str]) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.name in var_constraint_names or self.constraint.can_infer(
        var_constraint_names
    )

infer(context: InferenceContext) -> int

Source code in xdsl/irdl/constraints.py
def infer(
    self,
    context: InferenceContext,
) -> int:
    v = context.get_int_variable(self.name)
    if v is None:
        return self.constraint.infer(context)
    return v

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    return IntVarConstraint(
        self.name, self.constraint.mapping_type_vars(type_var_mapping)
    )

IntTypeVarConstraint dataclass

Bases: IntConstraint

Stores the TypeVar instance used to define a generic type.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class IntTypeVarConstraint(IntConstraint):
    """
    Stores the TypeVar instance used to define a generic type.
    """

    type_var: TypeVar
    """The instance of the TypeVar used in the definition."""

    base_constraint: IntConstraint
    """Constraint inferred from the base of the TypeVar."""

    def verify(
        self,
        i: int,
        constraint_context: VerificationContext,
    ) -> None:
        self.base_constraint.verify(i, constraint_context)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> IntConstraint:
        res = type_var_mapping.get(self.type_var)
        if res is None:
            raise KeyError(f"Mapping value missing for type var {self.type_var}")
        if not isinstance(res, IntConstraint):
            raise ValueError(f"Unexpected constraint {res} for TypeVar {self.type_var}")
        return res

type_var: TypeVar instance-attribute

The instance of the TypeVar used in the definition.

base_constraint: IntConstraint instance-attribute

Constraint inferred from the base of the TypeVar.

__init__(type_var: TypeVar, base_constraint: IntConstraint) -> None

verify(i: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    i: int,
    constraint_context: VerificationContext,
) -> None:
    self.base_constraint.verify(i, constraint_context)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> IntConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> IntConstraint:
    res = type_var_mapping.get(self.type_var)
    if res is None:
        raise KeyError(f"Mapping value missing for type var {self.type_var}")
    if not isinstance(res, IntConstraint):
        raise ValueError(f"Unexpected constraint {res} for TypeVar {self.type_var}")
    return res

SizedConstraint dataclass

Bases: AttrConstraint

Constraint the length of a sized attribute with an int constraint

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class SizedConstraint(AttrConstraint):
    """
    Constraint the length of a sized attribute with an int constraint
    """

    len_constraint: IntConstraint

    def verify(self, attr: Attribute, constraint_context: VerificationContext) -> None:
        if not isinstance(attr, Sized):
            raise VerifyException(f"Expected {attr} to be sized")
        self.len_constraint.verify(len(attr), constraint_context)

    def variables(self) -> set[str]:
        return self.len_constraint.variables()

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> AttrConstraint:
        return SizedConstraint(self.len_constraint.mapping_type_vars(type_var_mapping))

len_constraint: IntConstraint instance-attribute

__init__(len_constraint: IntConstraint) -> None

verify(attr: Attribute, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(self, attr: Attribute, constraint_context: VerificationContext) -> None:
    if not isinstance(attr, Sized):
        raise VerifyException(f"Expected {attr} to be sized")
    self.len_constraint.verify(len(attr), constraint_context)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.len_constraint.variables()

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> AttrConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AttrConstraint:
    return SizedConstraint(self.len_constraint.mapping_type_vars(type_var_mapping))

RangeConstraint dataclass

Bases: ABC, Generic[AttributeCovT]

Constrain a range of attributes to certain values.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class RangeConstraint(ABC, Generic[AttributeCovT]):
    """Constrain a range of attributes to certain values."""

    @abstractmethod
    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: VerificationContext,
    ) -> None:
        """
        Check if the range satisfies the constraint, or raise an exception otherwise.
        """
        ...

    def verifies(
        self,
        attrs: Sequence[Attribute],
    ) -> TypeGuard[AttributeCovT]:
        """
        A helper method to check whether a given attribute matches `self`.
        """
        try:
            self.verify(attrs, VerificationContext())
            return True
        except VerifyException:
            return False

    @abstractmethod
    def verify_length(
        self, length: int, constraint_context: VerificationContext
    ) -> None:
        """
        Check if the length of the range satisfies the constraint, or raise an exception otherwise.
        """
        ...

    def variables(self) -> set[str]:
        """
        Returns a set of the variables that can be extracted by this constraint.
        These variables are always expected to be set after running `verify`.
        """
        return set()

    def variables_from_length(self) -> set[str]:
        """
        Returns a set of the variables that can be extracted from the range length by this constraint.
        These variables are always expected to be set after running `verify_length`.
        """
        return set()

    def can_infer(
        self, var_constraint_names: AbstractSet[str], *, length_known: bool
    ) -> bool:
        """
        Check if there is enough information to infer the attribute given the
        constraint variables that are already set, and whether the length of the
        range is known in advance.
        """
        # By default, we cannot infer anything.
        return False

    def infer(
        self, context: InferenceContext, *, length: int | None
    ) -> Sequence[AttributeCovT]:
        """
        Infer the attribute given the the values for all variables, and possibly
        the length of the range if known.

        Raises an exception if the attribute cannot be inferred. If `can_infer`
        returns `True` with the given constraint variables, this method should
        not raise an exception.
        """
        raise ValueError(f"Cannot infer range from constraint {self}")

    @abstractmethod
    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeConstraint[AttributeCovT]:
        """
        A helper function to make type vars used in attribute definitions concrete when
        creating constraints for new attributes or operations.
        """
        raise NotImplementedError(
            "Custom constraints must map type vars in nested constraints, if any."
        )

    def of_length(
        self, length_constr: int | TypeForm[int] | IntConstraint
    ) -> RangeLengthConstraint[AttributeCovT]:
        if isinstance(length_constr, IntConstraint):
            return RangeLengthConstraint(self, length_constr)
        from xdsl.irdl import get_int_constraint

        return RangeLengthConstraint(self, get_int_constraint(length_constr))

__init__() -> None

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None abstractmethod

Check if the range satisfies the constraint, or raise an exception otherwise.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: VerificationContext,
) -> None:
    """
    Check if the range satisfies the constraint, or raise an exception otherwise.
    """
    ...

verifies(attrs: Sequence[Attribute]) -> TypeGuard[AttributeCovT]

A helper method to check whether a given attribute matches self.

Source code in xdsl/irdl/constraints.py
def verifies(
    self,
    attrs: Sequence[Attribute],
) -> TypeGuard[AttributeCovT]:
    """
    A helper method to check whether a given attribute matches `self`.
    """
    try:
        self.verify(attrs, VerificationContext())
        return True
    except VerifyException:
        return False

verify_length(length: int, constraint_context: VerificationContext) -> None abstractmethod

Check if the length of the range satisfies the constraint, or raise an exception otherwise.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def verify_length(
    self, length: int, constraint_context: VerificationContext
) -> None:
    """
    Check if the length of the range satisfies the constraint, or raise an exception otherwise.
    """
    ...

variables() -> set[str]

Returns a set of the variables that can be extracted by this constraint. These variables are always expected to be set after running verify.

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    """
    Returns a set of the variables that can be extracted by this constraint.
    These variables are always expected to be set after running `verify`.
    """
    return set()

variables_from_length() -> set[str]

Returns a set of the variables that can be extracted from the range length by this constraint. These variables are always expected to be set after running verify_length.

Source code in xdsl/irdl/constraints.py
def variables_from_length(self) -> set[str]:
    """
    Returns a set of the variables that can be extracted from the range length by this constraint.
    These variables are always expected to be set after running `verify_length`.
    """
    return set()

can_infer(var_constraint_names: AbstractSet[str], *, length_known: bool) -> bool

Check if there is enough information to infer the attribute given the constraint variables that are already set, and whether the length of the range is known in advance.

Source code in xdsl/irdl/constraints.py
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: bool
) -> bool:
    """
    Check if there is enough information to infer the attribute given the
    constraint variables that are already set, and whether the length of the
    range is known in advance.
    """
    # By default, we cannot infer anything.
    return False

infer(context: InferenceContext, *, length: int | None) -> Sequence[AttributeCovT]

Infer the attribute given the the values for all variables, and possibly the length of the range if known.

Raises an exception if the attribute cannot be inferred. If can_infer returns True with the given constraint variables, this method should not raise an exception.

Source code in xdsl/irdl/constraints.py
def infer(
    self, context: InferenceContext, *, length: int | None
) -> Sequence[AttributeCovT]:
    """
    Infer the attribute given the the values for all variables, and possibly
    the length of the range if known.

    Raises an exception if the attribute cannot be inferred. If `can_infer`
    returns `True` with the given constraint variables, this method should
    not raise an exception.
    """
    raise ValueError(f"Cannot infer range from constraint {self}")

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeConstraint[AttributeCovT] abstractmethod

A helper function to make type vars used in attribute definitions concrete when creating constraints for new attributes or operations.

Source code in xdsl/irdl/constraints.py
@abstractmethod
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeConstraint[AttributeCovT]:
    """
    A helper function to make type vars used in attribute definitions concrete when
    creating constraints for new attributes or operations.
    """
    raise NotImplementedError(
        "Custom constraints must map type vars in nested constraints, if any."
    )

of_length(length_constr: int | TypeForm[int] | IntConstraint) -> RangeLengthConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def of_length(
    self, length_constr: int | TypeForm[int] | IntConstraint
) -> RangeLengthConstraint[AttributeCovT]:
    if isinstance(length_constr, IntConstraint):
        return RangeLengthConstraint(self, length_constr)
    from xdsl.irdl import get_int_constraint

    return RangeLengthConstraint(self, get_int_constraint(length_constr))

AnyRange dataclass

Bases: RangeConstraint

A constraint allowing any range.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class AnyRange(RangeConstraint):
    """
    A constraint allowing any range.
    """

    def verify(
        self, attrs: Sequence[Attribute], constraint_context: VerificationContext
    ) -> None:
        return

    def verify_length(
        self, length: int, constraint_context: VerificationContext
    ) -> None:
        return

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeConstraint:
        return self

__init__() -> None

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self, attrs: Sequence[Attribute], constraint_context: VerificationContext
) -> None:
    return

verify_length(length: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify_length(
    self, length: int, constraint_context: VerificationContext
) -> None:
    return

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeConstraint

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeConstraint:
    return self

RangeLengthConstraint dataclass

Bases: RangeConstraint[AttributeCovT]

Constrain an attribute range with the given length.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class RangeLengthConstraint(RangeConstraint[AttributeCovT]):
    """
    Constrain an attribute range with the given length.
    """

    constraint: RangeConstraint[AttributeCovT]
    """The constraint that the variable must satisfy."""

    length: IntConstraint
    """The length that the range must have"""

    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: VerificationContext,
    ) -> None:
        self.verify_length(len(attrs), constraint_context)
        self.constraint.verify(attrs, constraint_context)

    def verify_length(
        self, length: int, constraint_context: VerificationContext
    ) -> None:
        try:
            self.length.verify(length, constraint_context)
        except VerifyException as e:
            raise VerifyException(
                "incorrect length for range variable:\n" + str(e)
            ) from e

    def variables(self) -> set[str]:
        return self.constraint.variables() | self.length.variables()

    def variables_from_length(self) -> set[str]:
        return self.length.variables()

    def can_infer(
        self, var_constraint_names: AbstractSet[str], *, length_known: bool
    ) -> bool:
        # If we can infer length to be 0 without any variables then
        # the range can always be inferred
        if self.length.can_infer(set()) and not self.length.infer(
            VerificationContext()
        ):
            return True
        length_known = length_known or self.length.can_infer(var_constraint_names)
        return self.constraint.can_infer(
            var_constraint_names, length_known=length_known
        )

    def infer(
        self, context: InferenceContext, *, length: int | None
    ) -> Sequence[AttributeCovT]:
        if length is None:
            length = self.length.infer(context)
        if not length:
            return ()
        return self.constraint.infer(context, length=length)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeLengthConstraint[AttributeCovT]:
        return RangeLengthConstraint(
            self.constraint.mapping_type_vars(type_var_mapping),
            self.length.mapping_type_vars(type_var_mapping),
        )

constraint: RangeConstraint[AttributeCovT] instance-attribute

The constraint that the variable must satisfy.

length: IntConstraint instance-attribute

The length that the range must have

__init__(constraint: RangeConstraint[AttributeCovT], length: IntConstraint) -> None

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: VerificationContext,
) -> None:
    self.verify_length(len(attrs), constraint_context)
    self.constraint.verify(attrs, constraint_context)

verify_length(length: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify_length(
    self, length: int, constraint_context: VerificationContext
) -> None:
    try:
        self.length.verify(length, constraint_context)
    except VerifyException as e:
        raise VerifyException(
            "incorrect length for range variable:\n" + str(e)
        ) from e

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constraint.variables() | self.length.variables()

variables_from_length() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables_from_length(self) -> set[str]:
    return self.length.variables()

can_infer(var_constraint_names: AbstractSet[str], *, length_known: bool) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: bool
) -> bool:
    # If we can infer length to be 0 without any variables then
    # the range can always be inferred
    if self.length.can_infer(set()) and not self.length.infer(
        VerificationContext()
    ):
        return True
    length_known = length_known or self.length.can_infer(var_constraint_names)
    return self.constraint.can_infer(
        var_constraint_names, length_known=length_known
    )

infer(context: InferenceContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def infer(
    self, context: InferenceContext, *, length: int | None
) -> Sequence[AttributeCovT]:
    if length is None:
        length = self.length.infer(context)
    if not length:
        return ()
    return self.constraint.infer(context, length=length)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeLengthConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeLengthConstraint[AttributeCovT]:
    return RangeLengthConstraint(
        self.constraint.mapping_type_vars(type_var_mapping),
        self.length.mapping_type_vars(type_var_mapping),
    )

RangeVarConstraint dataclass

Bases: RangeConstraint[AttributeCovT]

Constrain an attribute range with the given constraint, and constrain all occurences of this constraint (i.e, sharing the same name) to be equal.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class RangeVarConstraint(RangeConstraint[AttributeCovT]):
    """
    Constrain an attribute range with the given constraint, and constrain all occurences
    of this constraint (i.e, sharing the same name) to be equal.
    """

    name: str
    """The variable name. All uses of that name refer to the same variable."""

    constraint: RangeConstraint[AttributeCovT]
    """The constraint that the variable must satisfy."""

    @staticmethod
    def get(
        name: str,
        constraint: IRDLAttrConstraint[AttributeInvT]
        | RangeConstraint[AttributeInvT] = AnyRange(),
    ) -> RangeConstraint[AttributeInvT]:
        if not isinstance(constraint, RangeConstraint):
            from xdsl.irdl import irdl_to_attr_constraint

            constraint = RangeOf(irdl_to_attr_constraint(constraint))

        return RangeVarConstraint(
            name, cast(RangeConstraint[AttributeInvT], constraint)
        )

    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: VerificationContext,
    ) -> None:
        if constraint_context.set_range_variable(self.name, tuple(attrs)):
            self.constraint.verify(attrs, constraint_context)

    def verify_length(
        self, length: int, constraint_context: VerificationContext
    ) -> None:
        # It is not possible to fully verify the constraint from just the length, so we don't try.
        pass

    def variables(self) -> set[str]:
        return self.constraint.variables() | {self.name}

    def can_infer(
        self, var_constraint_names: AbstractSet[str], *, length_known: bool
    ) -> bool:
        return self.name in var_constraint_names or self.constraint.can_infer(
            var_constraint_names, length_known=length_known
        )

    def infer(
        self, context: InferenceContext, *, length: int | None
    ) -> Sequence[AttributeCovT]:
        v = context.get_range_variable(self.name)
        if v is None:
            return self.constraint.infer(context, length=length)
        return cast(Sequence[AttributeCovT], v)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeVarConstraint[AttributeCovT]:
        return RangeVarConstraint(
            self.name, self.constraint.mapping_type_vars(type_var_mapping)
        )

name: str instance-attribute

The variable name. All uses of that name refer to the same variable.

constraint: RangeConstraint[AttributeCovT] instance-attribute

The constraint that the variable must satisfy.

__init__(name: str, constraint: RangeConstraint[AttributeCovT]) -> None

get(name: str, constraint: IRDLAttrConstraint[AttributeInvT] | RangeConstraint[AttributeInvT] = AnyRange()) -> RangeConstraint[AttributeInvT] staticmethod

Source code in xdsl/irdl/constraints.py
@staticmethod
def get(
    name: str,
    constraint: IRDLAttrConstraint[AttributeInvT]
    | RangeConstraint[AttributeInvT] = AnyRange(),
) -> RangeConstraint[AttributeInvT]:
    if not isinstance(constraint, RangeConstraint):
        from xdsl.irdl import irdl_to_attr_constraint

        constraint = RangeOf(irdl_to_attr_constraint(constraint))

    return RangeVarConstraint(
        name, cast(RangeConstraint[AttributeInvT], constraint)
    )

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: VerificationContext,
) -> None:
    if constraint_context.set_range_variable(self.name, tuple(attrs)):
        self.constraint.verify(attrs, constraint_context)

verify_length(length: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify_length(
    self, length: int, constraint_context: VerificationContext
) -> None:
    # It is not possible to fully verify the constraint from just the length, so we don't try.
    pass

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constraint.variables() | {self.name}

can_infer(var_constraint_names: AbstractSet[str], *, length_known: bool) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: bool
) -> bool:
    return self.name in var_constraint_names or self.constraint.can_infer(
        var_constraint_names, length_known=length_known
    )

infer(context: InferenceContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def infer(
    self, context: InferenceContext, *, length: int | None
) -> Sequence[AttributeCovT]:
    v = context.get_range_variable(self.name)
    if v is None:
        return self.constraint.infer(context, length=length)
    return cast(Sequence[AttributeCovT], v)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeVarConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeVarConstraint[AttributeCovT]:
    return RangeVarConstraint(
        self.name, self.constraint.mapping_type_vars(type_var_mapping)
    )

RangeOf dataclass

Bases: RangeConstraint[AttributeCovT]

Constrain each element in a range to satisfy a given constraint.

Source code in xdsl/irdl/constraints.py
@dataclass(frozen=True)
class RangeOf(RangeConstraint[AttributeCovT]):
    """
    Constrain each element in a range to satisfy a given constraint.
    """

    constr: AttrConstraint[AttributeCovT]

    def __init__(self, constr: IRDLAttrConstraint[AttributeCovT]):
        from xdsl.irdl import irdl_to_attr_constraint

        object.__setattr__(self, "constr", irdl_to_attr_constraint(constr))

    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: VerificationContext,
    ) -> None:
        for a in attrs:
            self.constr.verify(a, constraint_context)

    def verify_length(self, length: int, constraint_context: VerificationContext): ...

    def variables(self) -> set[str]:
        return self.constr.variables()

    def can_infer(
        self, var_constraint_names: AbstractSet[str], *, length_known: bool
    ) -> bool:
        return length_known and self.constr.can_infer(var_constraint_names)

    def infer(
        self,
        context: InferenceContext,
        *,
        length: int | None,
    ) -> Sequence[AttributeCovT]:
        assert length is not None
        attr = self.constr.infer(context)
        return (attr,) * length

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeOf[AttributeCovT]:
        return RangeOf(self.constr.mapping_type_vars(type_var_mapping))

constr: AttrConstraint[AttributeCovT] instance-attribute

__init__(constr: IRDLAttrConstraint[AttributeCovT])

Source code in xdsl/irdl/constraints.py
def __init__(self, constr: IRDLAttrConstraint[AttributeCovT]):
    from xdsl.irdl import irdl_to_attr_constraint

    object.__setattr__(self, "constr", irdl_to_attr_constraint(constr))

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: VerificationContext,
) -> None:
    for a in attrs:
        self.constr.verify(a, constraint_context)

verify_length(length: int, constraint_context: VerificationContext)

Source code in xdsl/irdl/constraints.py
def verify_length(self, length: int, constraint_context: VerificationContext): ...

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constr.variables()

can_infer(var_constraint_names: AbstractSet[str], *, length_known: bool) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: bool
) -> bool:
    return length_known and self.constr.can_infer(var_constraint_names)

infer(context: InferenceContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def infer(
    self,
    context: InferenceContext,
    *,
    length: int | None,
) -> Sequence[AttributeCovT]:
    assert length is not None
    attr = self.constr.infer(context)
    return (attr,) * length

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeOf[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeOf[AttributeCovT]:
    return RangeOf(self.constr.mapping_type_vars(type_var_mapping))

SingleOf dataclass

Bases: RangeConstraint[AttributeCovT]

Constrain a range to only contain a single element, which should satisfy a given constraint.

Source code in xdsl/irdl/constraints.py
@deprecated("Use `RangeOf(attr).of_length(1)` instead.")
@dataclass(frozen=True)
class SingleOf(RangeConstraint[AttributeCovT]):
    """
    Constrain a range to only contain a single element, which should satisfy a given constraint.
    """

    constr: AttrConstraint[AttributeCovT]

    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: VerificationContext,
    ) -> None:
        if len(attrs) != 1:
            raise VerifyException(f"Expected a single attribute, got {len(attrs)}")
        self.constr.verify(attrs[0], constraint_context)

    def verify_length(
        self, length: int, constraint_context: VerificationContext
    ) -> None:
        if length != 1:
            raise VerifyException(f"Expected a single attribute, got {length}")

    def variables(self) -> set[str]:
        return self.constr.variables()

    def can_infer(
        self, var_constraint_names: AbstractSet[str], *, length_known: int | None
    ) -> bool:
        return self.constr.can_infer(var_constraint_names)

    def infer(
        self, context: InferenceContext, *, length: int | None
    ) -> Sequence[AttributeCovT]:
        return (self.constr.infer(context),)

    def mapping_type_vars(
        self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
    ) -> RangeConstraint[AttributeCovT]:
        return SingleOf(self.constr.mapping_type_vars(type_var_mapping))  # pyright: ignore [reportDeprecated]

constr: AttrConstraint[AttributeCovT] instance-attribute

__init__(constr: AttrConstraint[AttributeCovT]) -> None

verify(attrs: Sequence[Attribute], constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: VerificationContext,
) -> None:
    if len(attrs) != 1:
        raise VerifyException(f"Expected a single attribute, got {len(attrs)}")
    self.constr.verify(attrs[0], constraint_context)

verify_length(length: int, constraint_context: VerificationContext) -> None

Source code in xdsl/irdl/constraints.py
def verify_length(
    self, length: int, constraint_context: VerificationContext
) -> None:
    if length != 1:
        raise VerifyException(f"Expected a single attribute, got {length}")

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
def variables(self) -> set[str]:
    return self.constr.variables()

can_infer(var_constraint_names: AbstractSet[str], *, length_known: int | None) -> bool

Source code in xdsl/irdl/constraints.py
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: int | None
) -> bool:
    return self.constr.can_infer(var_constraint_names)

infer(context: InferenceContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def infer(
    self, context: InferenceContext, *, length: int | None
) -> Sequence[AttributeCovT]:
    return (self.constr.infer(context),)

mapping_type_vars(type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]) -> RangeConstraint[AttributeCovT]

Source code in xdsl/irdl/constraints.py
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> RangeConstraint[AttributeCovT]:
    return SingleOf(self.constr.mapping_type_vars(type_var_mapping))  # pyright: ignore [reportDeprecated]