\chapter{Introduction}

All types in a programming language must have a set of constants, and these constants have \Newterm{primary names}, \eg integral types have constants @-1@, @17@, @0xff@, floating-point types have constants @5.3@, @2.3E-5@, @0xff.ffp0@, character types have constants @'a'@, @"abc\n"@, \mbox{\lstinline{u8"}\texttt{\guillemotleft{na\"{i}ve}\guillemotright}\lstinline{"}}, \etc.
Con\-stants can be overloaded among types, \eg @0@ is a null pointer for all pointer types, and the value zero for integral and floating-point types.
(In \CFA, the primary constants @0@ and @1@ can be overloaded for any type.)
Hence, each primary constant has a symbolic name referring to its internal representation, and these names are dictated by language syntax related to types.
In theory, there are an infinite set of primary names per type.

\Newterm{Secondary naming} is a common practice in mathematics, engineering and computer science, \eg $\pi$, $\tau$ (2$\pi$), $\phi$ (golden ratio), MB (mega byte, 1E6), and in general situations, \eg specific times (noon, New Years), cities (Big Apple), flowers (Lily), \etc.
Many programming languages capture this important software-engineering capability through a mechanism called \Newterm{constant} or \Newterm{literal} naming, where a secondary name is aliased to a primary name.
Its common purpose is to eliminate duplication of the primary constant throughout a program.
For example, the secondary name replaces its primary name, thereafter changing the binding of the secondary to primary name automatically distributes the rebinding throughout the program.
In some cases, secondary naming is \Newterm{opaque}, where the matching internal representation can be chosen arbitrarily, and only equality operations are available, \eg @O_RDONLY@, @O_WRONLY@, @O_CREAT@, @O_TRUNC@, @O_APPEND@.
Because a secondary name is a constant, it cannot appear in a mutable context, \eg \mbox{$\pi$ \lstinline{= 42}} is meaningless, and a constant has no address, \ie it is an \Newterm{rvalue}\footnote{
The term rvalue defines an expression that can only appear on the right-hand side of an assignment expression.}.

Secondary names can form an (ordered) set, \eg days of the week, months of a year, floors of a building (basement, ground, 1st), colours in a rainbow, \etc.
Many programming languages capture these groupings through a mechanism called an \Newterm{enumeration}.
\begin{quote}
enumerate (verb, transitive).
To count, ascertain the number of;
more usually, to mention (a number of things or persons) separately, as if for the purpose of counting;
to specify as in a list or catalogue.~\cite{OEDenumerate}
\end{quote}
Within an enumeration set, the enumeration names must be unique, and instances of an enumerated type are \emph{often} restricted to hold only the secondary names.
It is possible to enumerate among set names without having an ordering among the set elements.
For example, the week, the weekdays, the weekend, and every second day of the week.
\begin{cfa}[morekeywords={in}]
for ( cursor in Mon, Tue, Wed, Thu, Fri, Sat, Sun } ... $\C[3.75in]{// week}$
for ( cursor in Mon, Tue, Wed, Thu, Fri } ...	$\C{// weekday}$
for ( cursor in Sat, Sun } ...					$\C{// weekend}$
for ( cursor in Mon, Wed, Fri, Sun } ...		$\C{// every second day of week}\CRT$
\end{cfa}
This independence from internal representation allows multiple names to have the same representation (eighth note, quaver), giving synonyms.
A set can have a partial or total ordering, making it possible to compare set elements, \eg Monday is before Friday and Friday is after.
Ordering allows iterating among the enumeration set using relational operators and advancement, \eg
\begin{cfa}
for ( cursor = Monday; cursor @<=@ Friday; cursor = @succ@( cursor ) ) ...
\end{cfa}
Here the internal representations for the secondary names are logically \emph{generated} rather than listing a subset of names.

Hence, the fundamental aspects of an enumeration are:
\begin{enumerate}
\item
It defines a type from which instants can be generated.
\item
The type lists a finite set of secondary names, which become its primary constants.
This differentiates an enumeration from general types with an infinite number of primary constants.
\item
An enumeration's secondary names represent constants, which follows from their binding (aliasing) to primary names, which are constants.
\item
For safety, an enumeration instance is restricted to hold only its type's secondary names.
\item
There is a mechanism for \emph{enumerating} over the secondary names, where the ordering can be implicit from the type, explicitly listed, or generated arithmetically.
\end{enumerate}


\section{Terminology}
\label{s:Terminology}

The term \Newterm{enumeration} defines a type with a set of secondary names, and the term \Newterm{enumerator} represents an arbitrary secondary name \see{\VRef{s:CEnumeration}}.
As well, an enumerated type has three fundamental properties, \Newterm{label}, \Newterm{order}, and \Newterm{value}.
\begin{cquote}
\sf\setlength{\tabcolsep}{3pt}
\begin{tabular}{rcccccccr}
\it\color{red}enumeration	& \multicolumn{8}{c}{\it\color{red}enumerators}	\\
$\downarrow$\hspace*{25pt}	& \multicolumn{8}{c}{$\downarrow$}				\\
@enum@ Week \{				& Mon,	& Tue,	& Wed,	& Thu,	& Fri, 	& Sat,	& Sun = 42	& \};	\\
\it\color{red}label			& Mon	& Tue	& Wed	& Thu	& Fri 	& Sat	& Sun		&		\\
\it\color{red}order			& 0		& 1		& 2		& 3		& 4		& 5		& 6	 		&		\\
\it\color{red}value			& 0		& 1		& 2		& 3		& 4		& 5		& 42 		&
\end{tabular}
\end{cquote}
Here, the enumeration @Week@ defines the enumerator labels @Mon@, @Tue@, @Wed@, @Thu@, @Fri@, @Sat@ and @Sun@.
The implicit ordering implies the successor of @Tue@ is @Mon@ and the predecessor of @Tue@ is @Wed@, independent of any associated enumerator values.
The value is the constant represented by the secondary name, which can be implicitly or explicitly set.

Specifying complex ordering is possible:
\begin{cfa}
enum E1 { $\color{red}[\(_1\)$ {A, B}, $\color{blue}[\(_2\)$ C $\color{red}]\(_1\)$, {D, E} $\color{blue}]\(_2\)$ }; $\C{// overlapping square brackets}$
enum E2 { {A, {B, C} }, { {D, E}, F };	$\C{// nesting}$
\end{cfa}
For @E1@, there is the partial ordering among @A@, @B@ and @C@, and @C@, @D@ and @E@, but not among @A@, @B@ and @D@, @E@.
For @E2@, there is the total ordering @A@ $<$ @{B, C}@ $<$ @{D, E}@ $<$ @F@.
Only flat total-ordering among enumerators is considered in this work.


\section{Motivation}

Some programming languages only provide direct secondary renaming.
\begin{cfa}
const Size = 20, Pi = 3.14159, Name = "Jane";
\end{cfa}
Here, it is possible to compare the secondary names, \eg @Size < Pi@, if that is meaningful.

Secondary renaming can simulate an enumeration, but with extra effort.
\begin{cfa}
const Mon = 1, Tue = 2, Wed = 3, Thu = 4, Fri = 5, Sat = 6, Sun = 7;
\end{cfa}
Any reordering of the enumerators requires manual renumbering.
\begin{cfa}
const Sun = 1, Mon = 2, Tue = 3, Wed = 4, Thu = 5, Fri = 6, Sat = 7;
\end{cfa}
Finally, there is no type to create a type-checked instance or iterator cursor.
Hence, there is only a weak equivalence between secondary naming and enumerations, justifying a seperate enumeration type in a programming language.

A variant (algebraic) type is often promoted as a kind of enumeration, \ie a variant type can simulate an enumeration.
Fundamentally, a variant type is a tagged-union, where the tag is normally opaque and the types are usually heterogeneous.
\begin{cfa}[morekeywords={variant}]
@variant@ Variant {
	@int tag;@  // optional/implicit: 0 => int, 1 => double, 2 => S
	@union {@ // implicit
		case int i;
		case double d;
		case struct S { int i, j; } s;
	@};@
};
\end{cfa}
Crucially, the union implies instance storage is shared by all the variant types, and therefore, before a variant type can be used in a statically-typed expression, it must be dynamically discriminated to its current contained type.
Hence, knowing which type is in a variant instance is crucial for correctness.
Occasionally, it is possible to statically determine all regions where each variant type is used, so a tag and runtime checking is unnecessary.
Otherwise, a tag is required to denote the particular type in the variant, and the tag is discriminated at runtime using some form of type pattern-matching, after which the value can be used in a statically-typed expression.

A less frequent variant case is multiple variants with the same type, which normally requires explicit naming of the tag to disambiguate among the common types.
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
\begin{cfa}[morekeywords={variant}]
variant VariantCT {
	case @car@: int i;  // explicitly typed
	case @boat@: int i;
	case @bridge@: int i;
};
\end{cfa}
&
\begin{cfa}[morekeywords={variant}]
variant VariantCU {
	case @car@: ;  // empty or unit type
	case @boat@: ;
	case @bridge@: ;
};
\end{cfa}
\end{tabular}
\end{cquote}
Here, the explicit tag name is used to give different meaning to the values in the common @int@ type, \eg the value 3 has different interpretations depending on the tag name.
It is even possible to remove the type or use the empty @unit@ type (@struct unit {}@).
It is this tag naming that is used to simulate an enumeration.

Normally, the variant tag is implicitly set by the compiler based on type, but with common types, a tag name is required to resolve type ambiguity.
\begin{cfa}
Variant v = 3;							$\C{// implicitly set tag to 0 based on type of 3}$
VariantCT ve = boats.3;					$\C{// explicitly set tag to 1 using tag name}$
\end{cfa}
Type pattern-matching is then used to dynamically test the tag and branch to a section of statically-typed code to safely manipulate the value, \eg:
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
\begin{cfa}[morekeywords={match}]
@match@( v ) { // know type implicitly or test tag
	case int { /* only access i field */ }
	case double { /* only access d field */ }
	case S { /* only access s field */ }
}
\end{cfa}
&
\begin{cfa}[morekeywords={match}]
@match@( ve ) {
	case car: int { /* car interpretation */ }
	case boat: int { /* boat interpretation */ }
	case bridge: int { /* bridge interpretation */ }
}
\end{cfa}
\end{tabular}
\end{cquote}
For safety, some languages require all variant types to be listed or a @default@ case with no field accesses.

To further strengthen the simulate for an enumeration with different values, each variant type can be a @const@ type or the tag becomes non-opaque, possibly taking advantage of the opaque auto-numbering.
\begin{cquote}
\begin{tabular}{@{}l@{\hspace{30pt}}l@{}}
\begin{cfa}
variant Week {
	case Mon: const int = 0;
	...
	case Sat: const int = 5;
	case Sun: const int = 10;
};
\end{cfa}
&
\begin{cfa}
variant Week {
	case Mon: ;  // tag auto-numbering
	...
	case Sat: ;
	case @Sun = 10@: ; // directly set tag value
};
\end{cfa}
\end{tabular}
\end{cquote}
Directly setting the tag implies restrictions, like unique values.
In both cases, instances of @Week@ are @const@ (immutable).
However, usage between these two types becomes complex.
\begin{cfa}
Week day = Week.Mon;  // sets value or tag depending on type
if ( day == Week.Mon )   // dereference value or tag ?
\end{cfa}
Here, the dereference of @day@ should return the value of the type stored in the variant, never the tag.
If it does return the tag, some special meaning must be given to the empty/unit type, especially if a variant contains both regular and unit types.


In general, the enumeration simulation and the variant extensions to support it, are deviating from the normal use of a variant (union) type.
As well, the enumeration operations are limited to the available tag operations, \eg pattern matching.
While enumerating among tag names is possible:
\begin{cfa}[morekeywords={in}]
for ( cursor in Week.Mon, Week.Wed, Week.Fri, Week.Sun ) ...
\end{cfa}
what is the type of @cursor@?
If it the tag type (@int@), how is this value used?
If it is the variant type, where is the instance variable, which only contains one value.
Hence, either enumerating with a variant enumeration is disallowed or some unusual typing rule must be invented to make it work but only in restricted contexts.

While functional programming systems regularly re-purposing variant types into enumeration types, this process seems contrived and confusing.
A variant tag is not an enumeration, it is a discriminant among a restricted set of types stored in a storage block.
Hence, there is only a weak equivalence between an enumeration and variant type, justifying a seperate enumeration type in a programming language.


\section{Contributions}

The goal of this work is to to extend the simple and unsafe enumeration type in the C programming-language into a sophisticated and safe type in the \CFA programming-language, while maintain backwards compatibility with C.
On the surface, enumerations seem like a simple type.
However, when extended with advanced features, enumerations become complex for both the type system and the runtime implementation.

\begin{enumerate}
\item
overloading
\item
scoping
\item
typing
\item
subset
\item
inheritance
\end{enumerate}
