Skip to content

Constraints

constraints

ConstraintVariableType: TypeAlias = Attribute | Sequence[Attribute] | int module-attribute

Possible types that a constraint variable can have.

ConstraintVariableTypeT = TypeVar('ConstraintVariableTypeT', bound=ConstraintVariableType) module-attribute

TypedAttributeCovT = TypeVar('TypedAttributeCovT', bound=TypedAttribute, covariant=True) module-attribute

TypedAttributeT = TypeVar('TypedAttributeT', bound=TypedAttribute) module-attribute

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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@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()

    @deprecated("ConstraintContexts should not be copied")
    def copy(self):
        return ConstraintContext(
            self._variables.copy(),
            self._range_variables.copy(),
            self._int_variables.copy(),
        )

    @deprecated("ConstraintContexts should only be updated by set_* methods")
    def update(self, other: ConstraintContext):
        self._variables.update(other._variables)
        self._range_variables.update(other._range_variables)
        self._int_variables.update(other._int_variables)

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
52
53
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
55
56
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
58
59
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
61
62
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
64
65
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
67
68
def set_int_variable(self, key: str, i: int):
    self._int_variables[key] = i

copy()

Source code in xdsl/irdl/constraints.py
82
83
84
85
86
87
88
@deprecated("ConstraintContexts should not be copied")
def copy(self):
    return ConstraintContext(
        self._variables.copy(),
        self._range_variables.copy(),
        self._int_variables.copy(),
    )

update(other: ConstraintContext)

Source code in xdsl/irdl/constraints.py
90
91
92
93
94
@deprecated("ConstraintContexts should only be updated by set_* methods")
def update(self, other: ConstraintContext):
    self._variables.update(other._variables)
    self._range_variables.update(other._range_variables)
    self._int_variables.update(other._int_variables)

AttrConstraint dataclass

Bases: ABC, Generic[AttributeCovT]

Constrain an attribute to a certain value.

Source code in xdsl/irdl/constraints.py
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
175
176
177
178
179
180
181
182
183
184
185
186
187
@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 __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
111
112
113
114
115
116
117
118
119
120
121
@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
123
124
125
126
127
128
129
130
131
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
133
134
135
136
137
138
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
140
141
142
143
144
145
146
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
148
149
150
151
152
153
154
155
156
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
158
159
160
161
162
163
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

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

Source code in xdsl/irdl/constraints.py
165
166
167
168
169
170
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
172
173
174
175
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
177
178
179
180
181
182
183
184
185
186
187
@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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
@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 __or__(self, value: AttrConstraint[_AttributeCovT], /):
        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
203
204
205
206
207
208
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
210
211
212
213
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> AnyAttr:
    return self

__or__(value: AttrConstraint[_AttributeCovT])

Source code in xdsl/irdl/constraints.py
215
216
def __or__(self, value: AttrConstraint[_AttributeCovT], /):
    return self

__and__(value: AttrConstraint[AttributeCovT])

Source code in xdsl/irdl/constraints.py
218
219
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
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
@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
235
236
237
238
239
@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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
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
257
258
def variables(self) -> set[str]:
    return self.constraint.variables() | {self.name}

infer(context: ConstraintContext) -> AttributeCovT

Source code in xdsl/irdl/constraints.py
260
261
262
263
264
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
266
267
268
269
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
271
272
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
274
275
276
277
278
279
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
@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
294
295
296
297
298
299
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
301
302
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
304
305
306
307
308
309
310
311
312
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
@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 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
322
323
324
325
326
327
328
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
330
331
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: ConstraintContext) -> AttributeCovT

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

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

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

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

Source code in xdsl/irdl/constraints.py
339
340
341
342
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
@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):
            raise VerifyException(
                f"{attr} should be of base attribute {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 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
352
353
def __repr__(self):
    return f"BaseAttr({self.attr.__name__})"

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

Source code in xdsl/irdl/constraints.py
355
356
357
358
359
360
361
362
363
def verify(
    self,
    attr: Attribute,
    constraint_context: ConstraintContext,
) -> None:
    if not isinstance(attr, self.attr):
        raise VerifyException(
            f"{attr} should be of base attribute {self.attr.name}"
        )

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

Source code in xdsl/irdl/constraints.py
365
366
367
368
369
370
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
372
373
374
375
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
377
378
379
380
def get_bases(self) -> set[type[Attribute]] | None:
    if is_runtime_final(self.attr):
        return {self.attr}
    return None

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

Source code in xdsl/irdl/constraints.py
382
383
384
385
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
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
426
427
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
@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).
    """

    _eq_constrs: set[Attribute] = field(hash=False, repr=False)
    _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 = tuple(irdl_to_attr_constraint(c) for c in attr_constrs)

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

        return AnyOf(constrs)

    def __init__(
        self,
        attr_constrs: tuple[AttrConstraint[AttributeCovT], ...],
    ):
        eq_constrs = set[Attribute]()
        based_constrs = dict[type[Attribute], AttrConstraint[AttributeCovT]]()

        bases = set[type[Attribute]]()
        eq_bases = set[type[Attribute]]()
        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(bases):
                raise PyRDLError(
                    f"Constraint {c} shares a base with a non-equality constraint "
                    f"in {set(attr_constrs[0:i])} in `AnyOf` constraint."
                )

            if isinstance(c, EqAttrConstraint):
                eq_constrs.add(c.attr)
                eq_bases |= b
            else:
                if not b.isdisjoint(eq_bases):
                    raise PyRDLError(
                        f"Non-equality 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
                bases |= b

        # check for overlaps with the abstract constraint
        if abstr_constr is not None:
            # equality constraints should not overlap
            for attr in eq_constrs:
                if isinstance(attr, abstr_constr.attr):
                    raise PyRDLError(
                        f"Equality constraint {EqAttrConstraint(attr)} overlaps with the "
                        f"constraint {abstr_constr} in `AnyOf` constraint."
                    )
            # bases should not overlap via issubclass
            for base in bases:
                if issubclass(base, abstr_constr.attr):
                    raise PyRDLError(
                        f"Non-equality constraint {based_constrs[base]} overlaps with "
                        f"the constraint {abstr_constr} in `AnyOf` constraint."
                    )

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

    def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
        if attr in self._eq_constrs:
            return
        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 __or__(
        self, value: AttrConstraint[_AttributeCovT], /
    ) -> AttrConstraint[AttributeCovT | _AttributeCovT]:
        return AnyOf.get(*(*self.attr_constrs, value))

    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
420
421
422
423
424
425
426
427
428
429
430
431
@staticmethod
def get(
    *attr_constrs: IRDLAttrConstraint[AttributeInvT],
) -> AttrConstraint[AttributeInvT]:
    from xdsl.irdl import irdl_to_attr_constraint

    constrs = tuple(irdl_to_attr_constraint(c) for c in attr_constrs)

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

    return AnyOf(constrs)

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

Source code in xdsl/irdl/constraints.py
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
def __init__(
    self,
    attr_constrs: tuple[AttrConstraint[AttributeCovT], ...],
):
    eq_constrs = set[Attribute]()
    based_constrs = dict[type[Attribute], AttrConstraint[AttributeCovT]]()

    bases = set[type[Attribute]]()
    eq_bases = set[type[Attribute]]()
    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(bases):
            raise PyRDLError(
                f"Constraint {c} shares a base with a non-equality constraint "
                f"in {set(attr_constrs[0:i])} in `AnyOf` constraint."
            )

        if isinstance(c, EqAttrConstraint):
            eq_constrs.add(c.attr)
            eq_bases |= b
        else:
            if not b.isdisjoint(eq_bases):
                raise PyRDLError(
                    f"Non-equality 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
            bases |= b

    # check for overlaps with the abstract constraint
    if abstr_constr is not None:
        # equality constraints should not overlap
        for attr in eq_constrs:
            if isinstance(attr, abstr_constr.attr):
                raise PyRDLError(
                    f"Equality constraint {EqAttrConstraint(attr)} overlaps with the "
                    f"constraint {abstr_constr} in `AnyOf` constraint."
                )
        # bases should not overlap via issubclass
        for base in bases:
            if issubclass(base, abstr_constr.attr):
                raise PyRDLError(
                    f"Non-equality constraint {based_constrs[base]} overlaps with "
                    f"the constraint {abstr_constr} in `AnyOf` constraint."
                )

    object.__setattr__(
        self,
        "attr_constrs",
        attr_constrs,
    )
    object.__setattr__(
        self,
        "_eq_constrs",
        eq_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
512
513
514
515
516
517
518
519
520
521
522
523
def verify(self, attr: Attribute, constraint_context: ConstraintContext) -> None:
    if attr in self._eq_constrs:
        return
    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}")

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

Source code in xdsl/irdl/constraints.py
525
526
527
528
def __or__(
    self, value: AttrConstraint[_AttributeCovT], /
) -> AttrConstraint[AttributeCovT | _AttributeCovT]:
    return AnyOf.get(*(*self.attr_constrs, value))

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
530
531
532
533
534
535
536
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
538
539
540
541
542
543
544
545
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
547
548
549
550
551
552
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
555
556
557
558
559
560
561
562
563
564
565
566
567
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
@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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
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
582
583
584
585
586
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
588
589
590
591
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
593
594
595
596
597
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
599
600
601
602
603
604
605
606
607
608
609
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
611
612
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
614
615
616
617
618
619
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
628
629
630
631
632
633
634
635
636
637
638
639
640
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
@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 __or__(self, value: AttrConstraint[_AttributeCovT], /):
        if (
            not isinstance(value, ParamAttrConstraint)
            or self.base_attr is not cast(ParamAttrConstraint[Any], value).base_attr
            or len(self.param_constrs) > 1
        ):
            return super().__or__(value)  # pyright: ignore[reportUnknownArgumentType]
        return ParamAttrConstraint(
            self.base_attr,
            tuple(
                l | r
                for l, r in zip(self.param_constrs, value.param_constrs, strict=True)
            ),
        )

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
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
@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
673
674
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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
694
695
696
697
698
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
700
701
702
703
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
705
706
707
708
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
710
711
712
713
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
715
716
717
718
719
720
721
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),
    )

__or__(value: AttrConstraint[_AttributeCovT])

Source code in xdsl/irdl/constraints.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def __or__(self, value: AttrConstraint[_AttributeCovT], /):
    if (
        not isinstance(value, ParamAttrConstraint)
        or self.base_attr is not cast(ParamAttrConstraint[Any], value).base_attr
        or len(self.param_constrs) > 1
    ):
        return super().__or__(value)  # pyright: ignore[reportUnknownArgumentType]
    return ParamAttrConstraint(
        self.base_attr,
        tuple(
            l | r
            for l, r in zip(self.param_constrs, value.param_constrs, strict=True)
        ),
    )

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
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
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
@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
749
750
751
752
753
754
755
756
757
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
759
760
761
762
763
764
765
766
767
768
769
770
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
772
773
def variables(self) -> set[str]:
    return self.constr.variables()

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

Source code in xdsl/irdl/constraints.py
775
776
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
778
779
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
781
782
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
784
785
786
787
788
789
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
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
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
@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
796
797
798
799
800
801
802
803
804
805
@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
807
808
809
810
811
812
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
814
815
816
817
818
819
820
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
822
823
824
825
826
827
828
829
830
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
832
833
834
835
836
837
838
839
840
841
842
@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
845
846
847
848
849
850
851
852
853
854
855
856
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
850
851
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
853
854
855
856
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
@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
865
866
867
868
869
870
871
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
873
874
def can_infer(self, var_constraint_names: AbstractSet[str]) -> bool:
    return True

infer(context: ConstraintContext) -> int

Source code in xdsl/irdl/constraints.py
876
877
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
879
880
881
882
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
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
@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
892
893
894
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
896
897
898
899
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
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
@dataclass(frozen=True)
class IntSetConstraint(IntConstraint):
    """Constrain an integer to one of a set of integers."""

    values: frozenset[int]

    def verify(
        self,
        i: int,
        constraint_context: ConstraintContext,
    ) -> None:
        if i not in self.values:
            set_str = set(self.values) if self.values else "{}"
            raise VerifyException(f"Invalid value {i}, expected one of {set_str}")

    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

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

Source code in xdsl/irdl/constraints.py
908
909
910
911
912
913
914
915
def verify(
    self,
    i: int,
    constraint_context: ConstraintContext,
) -> None:
    if i not in self.values:
        set_str = set(self.values) if self.values else "{}"
        raise VerifyException(f"Invalid value {i}, expected one of {set_str}")

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

Source code in xdsl/irdl/constraints.py
917
918
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
920
921
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
923
924
925
926
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
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
@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
936
937
938
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
940
941
942
943
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
@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
953
954
955
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
957
958
959
960
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
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 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
@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
976
977
978
979
980
981
982
983
984
985
986
987
988
989
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
991
992
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
994
995
996
997
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
 999
1000
1001
1002
1003
1004
1005
1006
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
1008
1009
1010
1011
1012
1013
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
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
@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
1028
1029
1030
1031
1032
1033
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
1035
1036
1037
1038
1039
1040
1041
1042
1043
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

RangeConstraint dataclass

Bases: ABC, Generic[AttributeCovT]

Constrain a range of attributes to certain values.

Source code in xdsl/irdl/constraints.py
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
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
@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
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
@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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
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
1074
1075
1076
1077
1078
1079
@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
1081
1082
1083
1084
1085
1086
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
1088
1089
1090
1091
1092
1093
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
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
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
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
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
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
@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
1131
1132
1133
1134
1135
1136
1137
1138
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
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
@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
1153
1154
1155
1156
1157
1158
1159
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
1161
1162
1163
1164
1165
1166
1167
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
1169
1170
def variables(self) -> set[str]:
    return self.constraint.variables() | self.length.variables()

variables_from_length() -> set[str]

Source code in xdsl/irdl/constraints.py
1172
1173
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
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
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
1187
1188
1189
1190
1191
1192
1193
1194
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
1196
1197
1198
1199
1200
1201
1202
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
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
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
@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
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
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
1234
1235
1236
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
1238
1239
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
1241
1242
1243
1244
1245
1246
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
1248
1249
1250
1251
1252
1253
1254
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
1256
1257
1258
1259
1260
1261
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
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
@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
1272
1273
1274
1275
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
1277
1278
1279
1280
1281
1282
1283
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
1285
def verify_length(self, length: int, constraint_context: ConstraintContext): ...

variables() -> set[str]

Source code in xdsl/irdl/constraints.py
1287
1288
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
1290
1291
1292
1293
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
1295
1296
1297
1298
1299
1300
1301
1302
1303
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
1305
1306
1307
1308
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
1311
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
@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
1319
1320
1321
1322
1323
1324
1325
1326
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
1328
1329
1330
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
1332
1333
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
1335
1336
1337
1338
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
1340
1341
1342
1343
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
1345
1346
1347
1348
def mapping_type_vars(
    self, type_var_mapping: Mapping[TypeVar, AttrConstraint | IntConstraint]
) -> SingleOf[AttributeCovT]:
    return SingleOf(self.constr.mapping_type_vars(type_var_mapping))

attr_constr_coercion(attr: AttributeCovT | type[AttributeCovT] | AttrConstraint[AttributeCovT]) -> AttrConstraint[AttributeCovT]

Attributes are coerced into EqAttrConstraints, and Attribute types are coerced into BaseAttr.

Source code in xdsl/irdl/constraints.py
388
389
390
391
392
393
394
395
396
397
398
@deprecated("Please use `irdl_to_attr_constraint` instead")
def attr_constr_coercion(
    attr: AttributeCovT | type[AttributeCovT] | AttrConstraint[AttributeCovT],
) -> AttrConstraint[AttributeCovT]:
    """
    Attributes are coerced into EqAttrConstraints,
    and Attribute types are coerced into BaseAttr.
    """
    from xdsl.irdl import irdl_to_attr_constraint

    return irdl_to_attr_constraint(attr)