amaranth-lang / amaranth

A modern hardware definition language and toolchain based on Python
https://amaranth-lang.org/docs/amaranth/
BSD 2-Clause "Simplified" License
1.56k stars 174 forks source link

Allow accessing argument-less predicates on enum views without defining a custom view class #1419

Open whitequark opened 3 months ago

whitequark commented 3 months ago

For example, this:

class SPIMode(amaranth.lib.enum.Enum, shape=2):
    Dummy = 0b00
    Swap  = 0b11
    Put   = 0b01
    Get   = 0b10

    @property
    def has_output(self):
        return self in (SPIMode.Swap, SPIMode.Put)

    @property
    def has_input(self):
        return self in (SPIMode.Swap, SPIMode.Get)

could have a default view class that acts as-if it was defined like this:

class SPIMode_View(...):
    @property
    def has_output(self):
        return Array(x.has_output for x in SPIMode)[self]

    @property
    def has_input(self):
        return Array(x.has_input  for x in SPIMode)[self]

(An actual implementation would use __getattr__, of course. This also means that a custom view class can override it easily.)

To avoid any ambiguity in types of arguments or unwanted combinational explosion, this would only occur for functions marked with @property. For all other functions a diagnostic would be shown indicating that a custom view class must be defined.

whitequark commented 3 months ago

The big question for this proposal, besides "should we do this", is "what happens to values which don't have associated enum elements"?