xdslproject / xdsl

A Python Compiler Design Toolkit
Other
241 stars 66 forks source link

Add support for referencing "forward-declared" attributes #12

Open math-fehr opened 2 years ago

math-fehr commented 2 years ago

We would like to write something like:

@irdl_attr_definition
class ChocoListTypeData:
    name = "choco.list_type_data"
    # The following is a reference to itself
    type = AttributeDef(AnyOf([ChocoTypeData, ChocoListTypeData]))
K-W-Li commented 2 years ago

If I remember correctly, the following should work:

@irdl_attr_definition
class ChocoListTypeData:
    name = "choco.list_type_data"
    # The following is a reference to itself
    type = AttributeDef(AnyOf([ChocoTypeData, "ChocoListTypeData"]))

But it seems that AttributeDef(AnyOf([ChocoTypeData, ChocoListTypeData])) is not normal python type?

math-fehr commented 1 year ago

Note that it is breaking with the new way to define attributes:

@irdl_attr_definition
class RecursiveAttr(ParametrizedAttribute):
    """An attribute referring itself."""
    name = "test.recursive_attr"

    x: ParameterDef[RecursiveAttr | BoolData]

This is because when we introspect RecursiveAttr, RecursiveAttr is not yet defined, and thus get_type_hints will fail.

superlopuh commented 1 year ago

Does it work with from __future__ import annotations ?

math-fehr commented 1 year ago

Nope, and actually, this is a more general problem than just "recursive attributes". It will fail for any forward-referenced attribute. The problem is that when introspecting the code, forward referenced attributes are not defined yet, so the introspection fails.

One solution could be to delay the verification code creation to "runtime", after all classes have been parsed. This should be doable I think.