NEP24 Enumeration Values - ghewgill/neon-lang GitHub Wiki

This proposal introduces a way of attaching a numeric value to enumeration items.

Motivation

There are many situations where it is useful to assign a numeric value to values of an enumeration. For example, when dealing with a hypothetical network protocol, there might be a "command" byte with values such as:

TYPE Command IS ENUM
    query
    response
    status
END ENUM

The network protocol might define query is 1, response is 2, and status is 9. The programmer would have to define an additional function that converted between enumeration items and numeric values.

Proposal

The proposal is to introduce attaching constant numeric values to enumeration items, such as:

TYPE Command IS ENUM
    query := 1
    response := 2
    status := 9
END ENUM

Attaching such numeric values are optional, and default to automatically incrementing with the first value 0. Duplicate value assignments are not permitted.

Given an value of an enumeration type, the .value() method can be used to obtain the associated numeric value:

VAR c := Command.response
TESTCASE c.value() = 2

The .name() method can get the name:

TESTCASE c.name() = "response"

The value and name can also be obtained directly:

TESTCASE Command.response.value() = 2
TESTCASE Command.response.name() = "response"

Given a numeric value, a new enumeration value may be created in the following way:

c := Command(value WITH 2)
TESTCASE c = Command.response

Additionally, values may be created from a name:

c := Command(name WITH "query")
TESTCASE c = Command.query

In the last two cases, attempting to create an enumeration value with a value or name that does not exist causes a runtime panic error. This can be avoided by providing a default:

TESTCASE Command(value WITH 5, default WITH Command.query) = Command.query
TESTCASE Command(name WITH "xyz", default WITH Command.response) = Command.response