Skip to content

Constraints

constraints

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

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

ConstraintContext dataclass

Contains the assignment of constraint variables.

Source code in xdsl/irdl/constraints.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
@dataclass
class ConstraintContext:
    """
    Contains the assignment of constraint variables.
    """

    _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)

    def set_attr_variable(self, key: str, attr: Attribute):
        self._variables[key] = attr

    def set_range_variable(self, key: str, attrs: tuple[Attribute, ...]):
        self._range_variables[key] = attrs

    def set_int_variable(self, key: str, i: int):
        self._int_variables[key] = i

    @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
49
50
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
52
53
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
55
56
def get_int_variable(self, key: str) -> int | None:
    return self._int_variables.get(key)

set_attr_variable(key: str, attr: Attribute)

Source code in xdsl/irdl/constraints.py
58
59
def set_attr_variable(self, key: str, attr: Attribute):
    self._variables[key] = attr

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

Source code in xdsl/irdl/constraints.py
61
62
def set_range_variable(self, key: str, attrs: tuple[Attribute, ...]):
    self._range_variables[key] = attrs

set_int_variable(key: str, i: int)

Source code in xdsl/irdl/constraints.py
64
65
def set_int_variable(self, key: str, i: int):
    self._int_variables[key] = i

AttrConstraint dataclass

Bases: ABC, Generic[AttributeCovT]

Constrain an attribute to a certain value.

Source code in xdsl/irdl/constraints.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@dataclass(frozen=True)
class AttrConstraint(ABC, Generic[AttributeCovT]):
    """Constrain an attribute to a certain value."""

    @abstractmethod
    def verify(
        self,
        attr: Attribute,
        constraint_context: ConstraintContext,
    ) -> 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, ConstraintContext())
            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: ConstraintContext) -> 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: ConstraintContext) -> None abstractmethod

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

Source code in xdsl/irdl/constraints.py
89
90
91
92
93
94
95
96
97
98
99
@abstractmethod
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
101
102
103
104
105
106
107
108
109
def verifies(self, attr: Attribute) -> TypeGuard[AttributeCovT]:
    """
    A helper method to check whether a given attribute matches `self`.
    """
    try:
        self.verify(attr, ConstraintContext())
        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
111
112
113
114
115
116
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
118
119
120
121
122
123
124
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: ConstraintContext) -> 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
126
127
128
129
130
131
132
133
134
def infer(self, context: ConstraintContext) -> 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
136
137
138
139
140
141
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
143
144
145
146
147
148
149
150
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
152
153
154
155
156
157
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
159
160
161
162
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
164
165
166
167
168
169
170
171
172
173
174
@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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@dataclass(frozen=True)
class AnyAttr(AttrConstraint):
    """Constraint that is verified by all attributes."""

    def verify(
        self,
        attr: Attribute,
        constraint_context: ConstraintContext,
    ) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
181
182
183
184
185
186
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    pass

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

Source code in xdsl/irdl/constraints.py
188
189
190
191
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
193
194
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
@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: ConstraintContext,
    ) -> None:
        ctx_attr = constraint_context.get_variable(self.name)
        if ctx_attr is not None:
            if attr != ctx_attr:
                raise VerifyException(
                    f"attribute {constraint_context.get_variable(self.name)} expected from variable "
                    f"'{self.name}', but got {attr}"
                )
        else:
            self.constraint.verify(attr, constraint_context)
            constraint_context.set_attr_variable(self.name, attr)

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

    def infer(self, context: ConstraintContext) -> 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
210
211
212
213
214
@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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    ctx_attr = constraint_context.get_variable(self.name)
    if ctx_attr is not None:
        if attr != ctx_attr:
            raise VerifyException(
                f"attribute {constraint_context.get_variable(self.name)} expected from variable "
                f"'{self.name}', but got {attr}"
            )
    else:
        self.constraint.verify(attr, constraint_context)
        constraint_context.set_attr_variable(self.name, attr)

variables() -> set[str]

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

infer(context: ConstraintContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
235
236
237
238
239
def infer(self, context: ConstraintContext) -> 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
241
242
243
244
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
246
247
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
249
250
251
252
253
254
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
269
270
271
272
273
274
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    self.base_constraint.verify(attr, constraint_context)

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

Source code in xdsl/irdl/constraints.py
276
277
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
279
280
281
282
283
284
285
286
287
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
297
298
299
300
301
302
303
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
305
306
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: ConstraintContext) -> AttributeCovT

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

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

Source code in xdsl/irdl/constraints.py
311
312
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
314
315
316
317
318
319
320
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
322
323
324
325
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
@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:
        return f"AttrSetConstraint({{{', '.join(sorted(str(value) for value in self.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: ConstraintContext,
    ) -> 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
334
335
def __repr__(self) -> str:
    return f"AttrSetConstraint({{{', '.join(sorted(str(value) for value in self.values))}}})"

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

Source code in xdsl/irdl/constraints.py
337
338
339
340
341
342
@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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
344
345
346
347
348
349
350
351
352
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
354
355
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
357
358
359
360
361
362
363
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
365
366
367
368
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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
378
379
def __repr__(self):
    return f"BaseAttr({self.attr.__name__})"

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

Source code in xdsl/irdl/constraints.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
396
397
398
399
400
401
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: ConstraintContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
403
404
405
406
def infer(self, context: ConstraintContext) -> 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
408
409
410
411
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
413
414
415
416
417
418
419
420
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
422
423
424
425
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
@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: ConstraintContext) -> 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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
@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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
532
533
534
535
536
537
538
539
540
541
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> 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
543
544
545
546
547
548
549
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
551
552
553
554
555
556
557
558
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
560
561
562
563
564
565
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
@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."""

    def verify(
        self,
        attr: Attribute,
        constraint_context: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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

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

Source code in xdsl/irdl/constraints.py
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
595
596
597
598
599
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
601
602
603
604
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: ConstraintContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
606
607
608
609
610
def infer(self, context: ConstraintContext) -> 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
612
613
614
615
616
617
618
619
620
621
622
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
624
625
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
627
628
629
630
631
632
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
@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
686
687
def __repr__(self):
    return f"ParamAttrConstraint({self.base_attr.__name__}, {self.param_constrs!r})"

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

Source code in xdsl/irdl/constraints.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
707
708
709
710
711
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
713
714
715
716
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: ConstraintContext) -> ParametrizedAttributeCovT

Source code in xdsl/irdl/constraints.py
718
719
720
721
def infer(self, context: ConstraintContext) -> 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
723
724
725
726
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
728
729
730
731
732
733
734
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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
771
772
773
774
775
776
777
778
779
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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
781
782
783
784
785
786
787
788
789
790
791
792
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> 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
794
795
def variables(self) -> set[str]:
    return self.constr.variables()

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

Source code in xdsl/irdl/constraints.py
797
798
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
800
801
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return self.constr.can_infer(var_constraint_names)

infer(context: ConstraintContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
803
804
def infer(self, context: ConstraintContext) -> 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
806
807
808
809
810
811
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@dataclass(frozen=True)
class IntConstraint(ABC):
    """Constrain an integer to certain values."""

    @abstractmethod
    def verify(
        self,
        i: int,
        constraint_context: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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: ConstraintContext) -> None abstractmethod

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

Source code in xdsl/irdl/constraints.py
818
819
820
821
822
823
824
825
826
827
@abstractmethod
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> 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
829
830
831
832
833
834
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
836
837
838
839
840
841
842
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: ConstraintContext) -> 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
844
845
846
847
848
849
850
851
852
def infer(self, context: ConstraintContext) -> 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
854
855
856
857
858
859
860
861
862
863
864
@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
867
868
869
870
871
872
873
874
875
876
877
878
class AnyInt(IntConstraint):
    """
    Constraint that is verified by all integers.
    """

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

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

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

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

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

Source code in xdsl/irdl/constraints.py
875
876
877
878
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
@dataclass(frozen=True)
class EqIntConstraint(IntConstraint):
    """Constrain an integer to a value."""

    value: int

    def verify(
        self,
        i: int,
        constraint_context: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
887
888
889
890
891
892
893
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> 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
895
896
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: ConstraintContext) -> int

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

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

Source code in xdsl/irdl/constraints.py
901
902
903
904
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
@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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
914
915
916
def verify(self, i: int, constraint_context: ConstraintContext) -> 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
918
919
920
921
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
@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))}}})"

    def verify(
        self,
        i: int,
        constraint_context: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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
930
931
def __repr__(self) -> str:
    return f"IntSetConstraint({{{', '.join(str(x) for x in sorted(self.values))}}})"

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

Source code in xdsl/irdl/constraints.py
933
934
935
936
937
938
939
940
941
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> 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
943
944
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return len(self.values) == 1

infer(context: ConstraintContext) -> int

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

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

Source code in xdsl/irdl/constraints.py
949
950
951
952
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
@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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
962
963
964
def verify(self, i: int, constraint_context: ConstraintContext) -> 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
966
967
968
969
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
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
@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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
979
980
981
def verify(self, i: int, constraint_context: ConstraintContext) -> 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
983
984
985
986
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
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
@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."""

    def verify(
        self,
        i: int,
        constraint_context: ConstraintContext,
    ) -> None:
        if self.name in constraint_context.int_variables:
            if i != constraint_context.get_int_variable(self.name):
                raise VerifyException(
                    f"integer {constraint_context.get_int_variable(self.name)} expected from int variable "
                    f"'{self.name}', but got {i}"
                )
        else:
            self.constraint.verify(i, constraint_context)
            constraint_context.set_int_variable(self.name, i)

    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: ConstraintContext,
    ) -> 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

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

Source code in xdsl/irdl/constraints.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> None:
    if self.name in constraint_context.int_variables:
        if i != constraint_context.get_int_variable(self.name):
            raise VerifyException(
                f"integer {constraint_context.get_int_variable(self.name)} expected from int variable "
                f"'{self.name}', but got {i}"
            )
    else:
        self.constraint.verify(i, constraint_context)
        constraint_context.set_int_variable(self.name, i)

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
1017
1018
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
1020
1021
1022
1023
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: ConstraintContext) -> int

Source code in xdsl/irdl/constraints.py
1025
1026
1027
1028
1029
1030
1031
1032
def infer(
    self,
    context: ConstraintContext,
) -> 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
1034
1035
1036
1037
1038
1039
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
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
1054
1055
1056
1057
1058
1059
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> 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
1061
1062
1063
1064
1065
1066
1067
1068
1069
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
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
@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: ConstraintContext) -> 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
1080
1081
1082
1083
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> 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
1085
1086
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
1088
1089
1090
1091
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
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
@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: ConstraintContext,
    ) -> 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, ConstraintContext())
            return True
        except VerifyException:
            return False

    @abstractmethod
    def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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: ConstraintContext, *, 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: ConstraintContext) -> None abstractmethod

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

Source code in xdsl/irdl/constraints.py
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
@abstractmethod
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: ConstraintContext,
) -> 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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
def verifies(
    self,
    attrs: Sequence[Attribute],
) -> TypeGuard[AttributeCovT]:
    """
    A helper method to check whether a given attribute matches `self`.
    """
    try:
        self.verify(attrs, ConstraintContext())
        return True
    except VerifyException:
        return False

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

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

Source code in xdsl/irdl/constraints.py
1122
1123
1124
1125
1126
1127
@abstractmethod
def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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
1129
1130
1131
1132
1133
1134
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
1136
1137
1138
1139
1140
1141
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
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
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: ConstraintContext, *, 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
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
def infer(
    self, context: ConstraintContext, *, 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
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
@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
1179
1180
1181
1182
1183
1184
1185
1186
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))

RangeLengthConstraint dataclass

Bases: RangeConstraint[AttributeCovT]

Constrain an attribute range with the given length.

Source code in xdsl/irdl/constraints.py
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
@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: ConstraintContext,
    ) -> None:
        self.verify_length(len(attrs), constraint_context)
        self.constraint.verify(attrs, constraint_context)

    def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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(ConstraintContext()):
            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: ConstraintContext, *, 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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
1201
1202
1203
1204
1205
1206
1207
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: ConstraintContext,
) -> None:
    self.verify_length(len(attrs), constraint_context)
    self.constraint.verify(attrs, constraint_context)

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

Source code in xdsl/irdl/constraints.py
1209
1210
1211
1212
1213
1214
1215
def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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
1217
1218
def variables(self) -> set[str]:
    return self.constraint.variables() | self.length.variables()

variables_from_length() -> set[str]

Source code in xdsl/irdl/constraints.py
1220
1221
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
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
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(ConstraintContext()):
        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: ConstraintContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
1235
1236
1237
1238
1239
1240
1241
1242
def infer(
    self, context: ConstraintContext, *, 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
1244
1245
1246
1247
1248
1249
1250
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
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
@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."""

    def verify(
        self,
        attrs: Sequence[Attribute],
        constraint_context: ConstraintContext,
    ) -> None:
        ctx_attrs = constraint_context.get_range_variable(self.name)
        if ctx_attrs is not None:
            if tuple(attrs) != ctx_attrs:
                raise VerifyException(
                    f"attributes {tuple(str(x) for x in ctx_attrs)} expected from range variable "
                    f"'{self.name}', but got {tuple(str(x) for x in attrs)}"
                )
        else:
            self.constraint.verify(attrs, constraint_context)
            constraint_context.set_range_variable(self.name, tuple(attrs))

    def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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: ConstraintContext, *, 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

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

Source code in xdsl/irdl/constraints.py
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: ConstraintContext,
) -> None:
    ctx_attrs = constraint_context.get_range_variable(self.name)
    if ctx_attrs is not None:
        if tuple(attrs) != ctx_attrs:
            raise VerifyException(
                f"attributes {tuple(str(x) for x in ctx_attrs)} expected from range variable "
                f"'{self.name}', but got {tuple(str(x) for x in attrs)}"
            )
    else:
        self.constraint.verify(attrs, constraint_context)
        constraint_context.set_range_variable(self.name, tuple(attrs))

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

Source code in xdsl/irdl/constraints.py
1282
1283
1284
def verify_length(self, length: int, constraint_context: ConstraintContext) -> 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
1286
1287
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
1289
1290
1291
1292
1293
1294
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: ConstraintContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
1296
1297
1298
1299
1300
1301
1302
def infer(
    self, context: ConstraintContext, *, 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
1304
1305
1306
1307
1308
1309
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
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
@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: ConstraintContext,
    ) -> None:
        for a in attrs:
            self.constr.verify(a, constraint_context)

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

    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: ConstraintContext,
        *,
        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
1320
1321
1322
1323
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: ConstraintContext) -> None

Source code in xdsl/irdl/constraints.py
1325
1326
1327
1328
1329
1330
1331
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: ConstraintContext,
) -> None:
    for a in attrs:
        self.constr.verify(a, constraint_context)

verify_length(length: int, constraint_context: ConstraintContext)

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

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
1335
1336
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
1338
1339
1340
1341
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: ConstraintContext, *, length: int | None) -> Sequence[AttributeCovT]

Source code in xdsl/irdl/constraints.py
1343
1344
1345
1346
1347
1348
1349
1350
1351
def infer(
    self,
    context: ConstraintContext,
    *,
    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
1353
1354
1355
1356
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
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
@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: ConstraintContext,
    ) -> 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: ConstraintContext) -> 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: ConstraintContext, *, length: int | None
    ) -> Sequence[AttributeCovT]:
        return (self.constr.infer(context),)

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

constr: AttrConstraint[AttributeCovT] instance-attribute

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

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

Source code in xdsl/irdl/constraints.py
1367
1368
1369
1370
1371
1372
1373
1374
def verify(
    self,
    attrs: Sequence[Attribute],
    constraint_context: ConstraintContext,
) -> 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: ConstraintContext) -> None

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

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
1380
1381
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
1383
1384
1385
1386
def can_infer(
    self, var_constraint_names: AbstractSet[str], *, length_known: int | None
) -> bool:
    return self.constr.can_infer(var_constraint_names)

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

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

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

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