11.15. Enumeration traits

The ENUM_TRAIT module provides reflection utilities for enumerations: iterating over all values, converting between enum values and strings, and building lookup tables. The [string_to_enum] annotation generates a string constructor for the annotated enum type.

All functions and symbols are in “enum_trait” module, use require to get access to it.

require daslib/enum_trait

Example:

require daslib/enum_trait

enum Color {
    red
    green
    blue
}

[export]
def main() {
    print("{Color.green}\n")
    let c = to_enum(type<Color>, "blue")
    print("{c}\n")
    let bad = to_enum(type<Color>, "purple", Color.red)
    print("fallback = {bad}\n")
}
// output:
// green
// blue
// fallback = red

11.15.1. Typeinfo macros

enum_length

Implements typeinfo enum_length(EnumOrEnumType) which returns total number of elements in enumeration.

enum_names

Implements typeinfo enum_names(EnumOrEnumType) which returns array of strings with enumValue names.

11.15.2. Handled enumerations

string_to_enum

Enumeration annotation which implements string constructor for enumeration.

11.15.3. Enumeration iteration

each(tt: auto(TT) ): iterator<TT>

Returns an iterator over all values of the given enumeration type.

Arguments:
  • tt : auto(TT)

11.15.4. Enumeration conversion

auto!(arg: auto ): bool

True when the enum value’s underlying integer is zero. Lets flag-op enums (registered via addEnumFlagOps) read like bitfields: if (!(flags & MASK)) { /* no bits set */ }

Width-safe via int64 cast: all 8 enum backings (int8/uint8 .. int64/uint64) sign- or zero-extend correctly, so high-bit uint64 members like 1ul << 63 are still detected as non-zero.

Arguments:
  • arg : auto

bool(arg: auto ): bool

True when the enum value’s underlying integer is non-zero. Lets flag-op enums read like bitfields: if (bool(flags & MASK)) { /* at least one bit set */ }

Width-safe — see the operator ! note above.

Arguments:
  • arg : auto

enum_to_table(ent: auto(EnumT) ): table<string, EnumT>
converts enum type to a table of name => value pairs

usage: let t = enum_to_table(type<EnumType>)

Arguments:
  • ent : auto(EnumT)

string(arg: auto ): auto
converts enum value to string

usage: let s = string(EnumValue)

Arguments:
  • arg : auto

11.15.4.1. to_enum

to_enum(ent: auto(EnumT); name: string ): EnumT
converts string to enum value, panics if not found

usage: let e = to_enum(type<EnumType>,”EnumValueName”)

Arguments:
  • ent : auto(EnumT)

  • name : string

to_enum(ent: auto(EnumT); name: string; defaultValue: EnumT ): EnumT