\chapter{\CFA-Style Enum}


\CFA supports C-Style enumeration using the same syntax and semantics for backwards compatibility.
\CFA also extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.


\section{Enumerator Name Resolution}
\label{s:EnumeratorNameResolution}

In C, unscoping of enumerators presents a \Newterm{naming problem} when multiple enumeration types appear in the same scope with duplicate enumerator names.
There is no mechanism in C to resolve these naming conflicts other than renaming of one of the duplicates, which may be impossible.

The \CFA type-system allows extensive overloading, including enumerators.
Furthermore, \CFA uses the left-hand of assignment in type resolution to pinpoint the best overloaded name.
Finally, qualification is provided to disambiguate any ambiguous situations.
\begin{cfa}
enum C1 { First, Second, Third, Fourth };
enum C2 { @Fourth@, @Third@, @Second@, @First@ };
C1 p() { return Third; }				$\C{// correctly resolved duplicate names}$
C2 p() { return Fourth; }
void foo() {
	C1 e1 = First;   C2 e2 = First;
	e1 = Second;   e2 = Second;
	e1 = p();   e2 = p();				$\C{// correctly resolved function call}$
	int i = @C1.@First + @C2.@First;	$\C{// ambiguous without qualification}$
}
\end{cfa}
\CFA overloading allows programmers to use the most meaningful names without fear of unresolvable clashes from included files, which are correctable with qualification.


\section{Enumerator Scoping}

An enumeration can be scoped, so the enumerator constants are not projected into the enclosing scope, using @'!'@.
\begin{cfa}
enum Weekday @!@ { /* as above */ };
enum( char * ) Names @!@ { /* as above */ };
\end{cfa}
Now the enumerators \emph{must} be qualified with the associated enumeration.
\begin{cfa}
Weekday weekday = @Weekday@.Monday;
Names names = @Names.@Fred;
names = @Names.@Jane;
\end{cfa}
It is possible to toggle back to unscoping using the \CFA @with@ clause/statement (see also \CC \lstinline[language=c++]{using enum} in Section~\ref{s:C++RelatedWork}).
\begin{cfa}
Weekday weekday;
with ( @Weekday@, @Names@ ) {			$\C{// type names}$
	 Names names = @Fred@;
	 names = @Jane@;
	 weekday = Saturday;
}
\end{cfa}
As in Section~\ref{s:EnumeratorNameResolution}, opening multiple unscoped enumerations can result in duplicate enumeration names, but \CFA type resolution and falling back to explicit qualification handles name resolution.

\section{Enumerator Typing}

\CFA extends the enumeration declaration by parameterizing with a type (like a generic type), allowing enumerators to be assigned any values from the declared type.
Figure~\ref{f:EumeratorTyping} shows a series of examples illustrating that all \CFA types can be use with an enumeration and each type's constants used to set the enumerator constants.
Note, the synonyms @Liz@ and @Beth@ in the last declaration.

Because enumerators are constants, the enumeration type is implicitly @const@, so all the enumerator types in Figure~\ref{f:EumeratorTyping} are rewritten with @const@.
A typed enumeration has an implicit (safe) conversion to its base type.
\begin{cfa}
char currency = Dollar;
string fred = Fred;						$\C{// implicit conversion from char * to \CFA string type}$
Person student = Beth;
\end{cfa}

% \begin{cfa}
% struct S { int i, j; };
% enum( S ) s { A = { 3,  4 }, B = { 7,  8 } };
% enum( @char@ ) Currency { Dollar = '$\textdollar$', Euro = '$\texteuro$', Pound = '$\textsterling$'  };
% enum( @double@ ) Planet { Venus = 4.87, Earth = 5.97, Mars = 0.642  }; // mass
% enum( @char *@ ) Colour { Red = "red", Green = "green", Blue = "blue"  };
% enum( @Currency@ ) Europe { Euro = '$\texteuro$', Pound = '$\textsterling$' }; // intersection
% \end{cfa}

\begin{figure}
\begin{cfa}
// integral
	enum( @char@ ) Currency { Dollar = '$\textdollar$', Euro = '$\texteuro$', Pound = '$\textsterling$'  };
	enum( @signed char@ ) srgb { Red = -1, Green = 0, Blue = 1 };
	enum( @long long int@ ) BigNum { X = 123_456_789_012_345,  Y = 345_012_789_456_123 };
// non-integral
	enum( @double@ ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 };
	enum( @_Complex@ ) Plane { X = 1.5+3.4i, Y = 7+3i, Z = 0+0.5i };
// pointer
	enum( @char *@ ) Names { Fred = "FRED", Mary = "MARY", Jane = "JANE" };
	int i, j, k;
	enum( @int *@ ) ptr { I = &i,  J = &j,  K = &k };
	enum( @int &@ ) ref { I = i,   J = j,   K = k };
// tuple
	enum( @[int, int]@ ) { T = [ 1, 2 ] }; $\C{// new \CFA type}$
// function
	void f() {...}   void g() {...}
	enum( @void (*)()@ ) funs { F = f,  G = g };
// aggregate
	struct Person { char * name; int age, height; };
@***@enum( @Person@ ) friends { @Liz@ = { "ELIZABETH", 22, 170 }, @Beth@ = Liz, Jon = { "JONATHAN", 35, 190 } };
\end{cfa}
\caption{Enumerator Typing}
\label{f:EumeratorTyping}
\end{figure}

Typed enumerations deals with the \emph{harmonizing} problem between an enumeration and any companion data.
The following example is from the \CFA compiler, written in \CC.
\begin{cfa}
enum integral_types { chr, schar, uschar, sshort, ushort, sint, usint, ..., NO_OF_ITYPES };
char * integral_names[NO_OF_ITYPES] = {
	"char", "signed char", "unsigned char",
	"signed short int", "unsigned short int",
	"signed int", "unsigned int",
	...
};
\end{cfa}
The \emph{harmonizing} problem occurs because the enumeration declaration is in one header file and the names are declared in another translation unit.
It is up to the programmer to ensure changes made in one location are harmonized with the other location (by identifying this requirement within a comment).
The typed enumeration largely solves this problem by combining and managing the two data types.
\begin{cfa}
enum( char * ) integral_types {
	chr = "char", schar = "signed char", uschar = "unsigned char",
	sshort = "signed short int", ushort = "unsigned short int",
	sint = "signed int", usint = "unsigned int",
	...
};
\end{cfa}
Note, the enumeration type can be a structure (see @Person@ in Figure~\ref{f:EumeratorTyping}), so it is possible to have the equivalent of multiple arrays of companion data using an array of structures.

While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are not used to evaluate an enumerator's value.
\CFA enumeration constants are compile-time values (static);
calling constructors happens at runtime (dynamic).


\section{Pure Enumerators}

An empty enumerator type, @enum()@, implies the enumerators are pure symbols without values but set properties;
hence, there is no default conversion to @int@. 

\begin{cfa}
enum() Mode { O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC, O_APPEND };
@***@Mode iomode = O_RDONLY;
bool b = iomode == O_RDONLY || iomode < O_APPEND;
int i = iomode;							$\C{\color{red}// disallowed}$
\end{cfa}

\section{Enumerator Subset}

If follows from enumerator typing that the enumerator type can be another enumerator.
\begin{cfa}
enum( @char@ ) Currency { Dollar = '$\textdollar$', Euro = '$\texteuro$', Pound = '$\textsterling$'  };
enum( @Currency@ ) Europe { Euro = Currency.Euro, Pound = Currency.Pound }; // intersection
enum( char ) Letter { A = 'A',  B = 'B', C = 'C', ..., Z = 'Z' };
enum( @Letter@ ) Greek { Alph = A, Beta = B, ..., Zeta = Z }; // intersection
\end{cfa}
Subset enumerations may have more or less enumerators than their typed enumeration, but the enumerator values must be from the typed enumeration.
For example, @Greek@ enumerators are a subset of type @Letter@ and are type compatible with enumeration @Letter@, but @Letter@ enumerators are not type compatible with enumeration @Greek@. 
\begin{cfa}
Letter letter = A;
@***@Greak greek = Beta;
letter = Beta;							$\C{// allowed, letter == B}$
greek = A;								$\C{\color{red}// disallowed}$
\end{cfa}


\section{Enumeration Inheritance}

\CFA Plan-9 inheritance may be used with enumerations, where Plan-9 inheritance is containment inheritance with implicit unscoping (like a nested unnamed @struct@/@union@ in C).
\begin{cfa}
enum( char * ) Names { /* as above */ };
enum( char * ) Names2 { @inline Names@, Jack = "JACK", Jill = "JILL" };
@***@enum /* inferred */ Names3 { @inline Names2@, Sue = "SUE", Tom = "TOM" };
\end{cfa}
Enumeration @Name2@ inherits all the enumerators and their values from enumeration @Names@ by containment, and a @Names@ enumeration is a subtype of enumeration @Name2@.
Note, enumerators must be unique in inheritance but enumerator values may be repeated.

The enumeration type for the inheriting type must be the same as the inherited type;
hence the enumeration type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for @Name3@.
% When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
Specifically, the inheritance relationship for @Names@ is:
\begin{cfa}
Names $\(\subset\)$ Names2 $\(\subset\)$ Names3 $\(\subset\)$ const char * $\C{// enum type of Names}$
\end{cfa}
For the given function prototypes, the following calls are valid.
\begin{cquote}
\begin{tabular}{ll}
\begin{cfa}
void f( Names );
void g( Names2 );
void h( Names3 );
void j( const char * );
\end{cfa}
&
\begin{cfa}
f( Fred );
g( Fred );   g( Jill );
h( Fred );   h( Jill );   h( Sue );
j( Fred );   j( Jill );   j( Sue );   j( "WILL" );
\end{cfa}
\end{tabular}
\end{cquote}
Note, the validity of calls is the same for call-by-reference as for call-by-value, and @const@ restrictions are the same as for other types.


\section{Enumeration Pseudo-functions}

Pseudo-functions are function-like operators that do not result in any run-time computations, \ie like @sizeof@, @offsetof@, @typeof@.
Often a call to a pseudo-function is substituted with information extracted from the symbol table at compilation time, like storage size or alignment associated with the underlying architecture..

The attributes of an enumerator are accessed by pseudo-functions @position@, @value@, and @label@.
\begin{cfa}
@***@int jane_pos = @position@( Names.Jane );   $\C{// 2}$
@***@char * jane_value = @value@( Names.Jane ); $\C{// "JANE"}$
@***@char * jane_label = @label@( Names.Jane ); $\C{// "Jane"}$
sout | @label@( Names.Jane ) | @value@( Names.Jane );
\end{cfa}
Note the ability to print both enumerator label and value.


\section{Enumerator Position or Value}

Enumerators can be used in multiple contexts.
In most programming languages, an enumerator is implicitly converted to its value (like a typed macro substitution).
However, enumerator synonyms and typed enumerations make this implicit conversion to value incorrect in some contexts.
In these contexts, a programmer's initition assumes an implicit conversion to postion.

For example, an intuitive use of enumerations is with the \CFA @switch@/@choose@ statement, where @choose@ performs an implict @break@ rather than a fall-through at the end of a @case@ clause.
\begin{cquote}
\begin{cfa}
enum Count { First, Second, Third, Fourth };
Count e;
\end{cfa}
\begin{tabular}{ll}
\begin{cfa}

choose( e ) {
	case @First@: ...;
	case @Second@: ...;
	case @Third@: ...;
	case @Fourth@: ...;
}
\end{cfa}
&
\begin{cfa}
// rewrite
choose( @value@( e ) ) {
	case @value@( First ): ...;
	case @value@( Second ): ...;
	case @value@( Third ): ...;
	case @value@( Fourth ): ...;
}
\end{cfa}
\end{tabular}
\end{cquote}
Here, the intuitive code on the left is implicitly transformed into the statndard implementation on the right, using the value of the enumeration variable and enumerators.
However, this implementation is fragile, \eg if the enumeration is changed to:
\begin{cfa}
enum Count { First, Second, Third @= First@, Fourth };
\end{cfa}
which make @Third == First@ and @Fourth == Second@, causing a compilation error because of duplicase @case@ clauses.
To better match with programmer intuition, \CFA toggles between value and position semantics depneding on the language context.
For conditional clauses and switch statments, \CFA uses the robust position implementation.
\begin{cfa}
choose( @position@( e ) ) {
	case @position@( First ): ...;
	case @position@( Second ): ...;
	case @position@( Third ): ...;
	case @position@( Fourth ): ...;
}
\end{cfa}

\begin{cfa}
Count variable_a = First, variable_b = Second, variable_c = Third, variable_d = Fourth;
p(variable_a); // 0
p(variable_b); // 1
p(variable_c); // "Third"
p(variable_d); // 3
\end{cfa}
