\documentclass[12pt]{article}
\usepackage{fullpage,times}
\usepackage{pslatex}			% reduce size of san serif font
\usepackage{xcolor}
\usepackage{listings}
%\usepackage{array}
\usepackage{graphics}
\usepackage{xspace}

\makeatletter
\renewcommand\section{\@startsection{section}{1}{\z@}{-3.0ex \@plus -1ex \@minus -.2ex}{1.5ex \@plus .2ex}{\normalfont\large\bfseries}}
\renewcommand\subsection{\@startsection{subsection}{2}{\z@}{-2.75ex \@plus -1ex \@minus -.2ex}{1.25ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex \@plus -1ex \@minus -.2ex}{1.0ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}{-2.0ex \@plus -1ex \@minus -.2ex}{-1em}{\normalfont\normalsize\bfseries}}
\renewcommand\subparagraph{\@startsection{subparagraph}{4}{\z@}{-1.5ex \@plus -1ex \@minus -.2ex}{-1em}{\normalfont\normalsize\bfseries\itshape}}
\makeatother

\usepackage[ignoredisplayed]{enumitem}	% do not affect trivlist
\setlist{labelsep=1ex}% global
\setlist[itemize]{topsep=0.5ex,parsep=0.25ex,itemsep=0.25ex,listparindent=\parindent,leftmargin=\parindent}% global
\setlist[itemize,1]{label=\textbullet}% local
%\renewcommand{\labelitemi}{{\raisebox{0.25ex}{\footnotesize$\bullet$}}}
\setlist[enumerate]{topsep=0.5ex,parsep=0.25ex,itemsep=0.25ex,listparindent=\parindent}% global
\setlist[enumerate,2]{leftmargin=\parindent,labelsep=*,align=parleft,label=\alph*.}% local
\setlist[description]{topsep=0.5ex,itemsep=0pt,listparindent=\parindent,leftmargin=\parindent,labelsep=1.5ex}

\newenvironment{cquote}{%
	\list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=4pt\parsep=0pt\leftmargin=\parindent\rightmargin\leftmargin}%
	\item\relax
}{%
	\endlist
}% cquote

\setlength{\topmargin}{-0.45in}							% move running title into header
\setlength{\headsep}{0.25in}
\setlength{\textheight}{9.0in}

\newcommand{\CFAIcon}{\textsf{C\raisebox{\depth}{\rotatebox{180}A}}} % Cforall icon
\newcommand{\CFA}{\protect\CFAIcon\xspace}				% CFA symbolic name
\newcommand{\PAB}[1]{{\color{red}PAB: #1}}

% \definecolor{mGreen}{rgb}{0,0.6,0}
% \definecolor{mGray}{rgb}{0.5,0.5,0.5}
% \definecolor{mPurple}{rgb}{0.58,0,0.82}
% \definecolor{backgroundColour}{rgb}{0.95,0.95,0.92}

\lstdefinestyle{CStyle}{
%    backgroundcolor=\color{backgroundColour},   
%    commentstyle=\color{mGreen},
%    keywordstyle=\color{magenta},
	stringstyle=\small\tt,					% use typewriter font
%    stringstyle=\color{mPurple},
    columns=fullflexible,
    basicstyle=\small\linespread{0.9}\sf,	% reduce line spacing and use sanserif font
%   basicstyle=\footnotesize,
    breakatwhitespace=false,         
%    breaklines=true,                 
    captionpos=b,                    
    keepspaces=true,                 
%    numbers=left,                    
%    numbersep=5pt,                  
%    numberstyle=\tiny\color{mGray},
%    showspaces=false,                
    showstringspaces=false,
%    showtabs=false,                  
	showlines=true,							% show blank lines at end of code
    tabsize=5,
    language=C,
	aboveskip=4pt,							% spacing above/below code block
	belowskip=2pt,
	xleftmargin=\parindent,			% indent code to paragraph indentation
}
\lstset{style=CStyle,moredelim=**[is][\color{red}]{@}{@}}
\lstMakeShortInline@				% single-character for \lstinline

\begin{document}

\title{\vspace*{-0.5in}Enumeration in \CFA}
\author{Jiada Liang}

\maketitle

\begin{abstract}
An enumeration is a type that defines a list of named constant values in C (and other languages).
C uses an integral type as the underlying representation of an enumeration.
\CFA extends C enumerations to allow all basic and custom types for the inner representation.
\end{abstract}

\section{C-Style Enum}

\CFA supports the C-Style enumeration using the same syntax and semantics.
\begin{lstlisting}[label=lst:weekday]
enum Weekday { Monday, Tuesday, Wednesday, Thursday=10, Friday, Saturday, Sunday };
\end{lstlisting}
The example defines an @enum@ type @Weekday@ with ordered enumerators @Monday@, @Tuesday@, @Wednesday@, @Thursday@, @Friday@, @Saturday@ and @Sunday@.
The successor of @Tuesday@ is @Monday@ and the predecessor of @Tuesday@ is @Wednesday@.
A C enumeration has an integral type, with consecutive enumerator values assigned by the compiler starting at zero or explicitly initialized by the programmer.
For example, @Monday@ to @Wednesday@ have values 0--2, @Thursday@ is set to @10@, and after it, @Friday@ to @Sunday@ have values 11--13.

There are 3 attributes for an enumeration: position, label, and value:
\begin{cquote}
\small\sf
\begin{tabular}{rccccccccccc}
enum Weekday \{	& Monday,	& Tuesday,	& Wednesday,	& Thursday=10,	& Friday, 	& Saturday,	& Sunday \}; \\
position		& 0			& 1			& 2				& 3				& 4			& 5			& 6			\\
label			& Monday	& Tuesday	& Wednesday		& Thursday		& Friday 	& Saturday	& Sunday	\\
value			& 0			& 1			& 2				& 10			& 11		& 12		& 13
\end{tabular}
\end{cquote}

The enumerators of an enum are unscoped, i.e., enumerators declared inside of an enum are visible in the enclosing scope of the enum class.
\begin{lstlisting}[label=lst:enum_scope]
{
	enum RGB { R, G, B };
	int i = R  // i == 0
}
int j = G; // ERROR! G is not declared in this scope
\end{lstlisting}

\section{\CFA-Style Enum}

A \CFA enumeration is parameterized by a type, which specifies the type for each enumerator.
\CFA allows any object type for the enumerators, and values assigned to enumerators must be in the declared type.
\begin{lstlisting}[label=lst:color]
enum Colour( @char *@ ) { Red = "R", Green = "G", Blue = "B"  };
\end{lstlisting}
The type of @Colour@ is @char *@ and each enumerator is initialized with a C string.
Only types have define an ordering can be automatically initialized (see Section~\ref{s:AutoInitializable}).


% An instance of \CFA-enum (denoted as @<enum_instance>@) is a label for the defined enum name.
% The label can be retrieved by calling the function @label( <enum_instance> )@.
% Similarly, the @value()@ function returns the value used to initialize the \CFA-enum.

A \CFA-enum is scoped: enumeration constants are not automatically exposed to the global scope.
Enumeration constant can be referenced using qualified expressions like an aggregate that supports qualified references to its fields. The syntax of $qualified\_expression$ for \CFA-enum is the following:
$$<qualified\_expression> := <enum\_type>.<enumerator>$$


\subsection{enumeration instance}
\begin{lstlisting}[label=lst:sample_cforall_enum_usage]
Colour green = Colour.Green;
\end{lstlisting}
The ~\ref{lst:sample_cforall_enum_usage} example declares a $enumeration\ instance$ named @red@ and initializes it with $enumeration\ constant$ @Color.Red@.
An enumeration instance is a data structure that captures attributes of an enumeration constant, which can be retrieved by functions $position( enumeration\ instance )$, $value( enumeration\ instance )$, and $label( enumeration\ instance )$. 
\begin{lstlisting}
int green_pos = position( green ); // 1
char * green_value = value( green ); // "G"
char * green_label = label( green ); // "Green"
\end{lstlisting}
An enumeration instance can be assigned to a variable or used as its position with type integer, its value with declared type T, or its label with type char *, and the compiler will resolve the usage as a type fits the context. 
\begin{lstlisting}[label=lst:enum_inst_assign_int]
int green_pos = green; // equivalent to position( green ); 
\end{lstlisting}
A resolution of an enumeration constant is $unambigious$ if only one of the attributes has the resolvable type.
In example~\ref{lst:enum_inst_assign_int}, the right-hand side of the assignment expression expects integer type.
The position of an enumeration is @int@, while the other two cannot be resolved as integers.
The expression unambiguously returns the position of @green@.
\begin{lstlisting}[label=lst:enum_inst_assign_string]
char * green_value = green; // equivalent to value( green ); 
\end{lstlisting}
On the other hand, the resolution of an enumeration constant is $ambigious$ if multiple attributes have the expected type.
In example~\ref{lst:enum_inst_assign_string}, both value and label have the expected type @char *@.
When a resolution is ambiguous, a \textit{resolution precedence} applies: $$value > position > label$$
\CFA uses resolution distance to describe if one type can be used as another. While \CFA calculates the resolution distance between the expected type and types of all three attributes, it would not choose the attribute with the closest distance. Instead, when resolving an enumeration constant, \CFA always chooses value whenever it is a possible resolution (resolution distance is not infinite), followed by position, then label. 
\begin{lstlisting}[label=lst:enum_inst_precedence]
enum(double) Foo { Bar };
int tee = Foo.Bar; // value( Bar );
\end{lstlisting}
In the example~\ref{lst:enum_inst_precedence}, while $position( Bar )$ has the closest resolution among the three attributes, $Foo.Bar$ is resolved as $value( Bar )$ because of the resolution precedence.

Although \CFA enumeration captures three different attributes, an instance of enumeration does not occupy extra memory.
The @sizeof@ \CFA enumeration instance is always 4 bytes, the same amount of memory to store a C enumeration instance.
It comes from the fact that:
\begin{enumerate}
\item
a \CFA enumeration is always statically typed;
\item
it is always resolved as one of its attributes in terms of real usage.
\end{enumerate}
When creating the enumeration instance green and assigns it with the enumeration constant @Color.Green@, the compilers essentially allocate an integer variables and store the position 1.
The invocations of $positions()$, $value()$, and $label()$ turn into calls to special functions defined in the prelude:
\begin{lstlisting}[label=lst:companion_call]
position( green );
>>> position( Colour, 1 ) -> int
value( green );
>>> value( Colour, 1 ) -> T
label( green );
>>> label( Colour, 1) -> char *
\end{lstlisting}
@T@ represents the type declared in the \CFA enumeration defined and @char *@ in the example. 
These generated functions are $Companion Functions$, they take an $companion$ object and the position as parameters.

\subsection{Companion Object and Companion Function}

\begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
forall( T )  {
	struct Companion {
		const T * const values;
		const char** const labels;
			int length;
	};
}
\end{lstlisting}
\CFA creates an object of Companion for every \CFA-enumeration. A companion object has the same name as the enumeration is defined for.
A companion object stores values and labels of enumeration constants, in the order of the constants defined in the enumeration.

\CFA generates the definition of companion functions. Because \CFA implicitly stores enumeration instance as its position, the companion function $position$ does nothing but returns the position it passes it.
Companions function $value$ and $label$ return the array item at the given position of $values$ and $labels$, respectively.
\begin{lstlisting}[label=lst:companion_definition]
int position( Companion o, int pos ) { return pos; }
T value( Companion o, int pos ) { return o.values[ pos ]; }
char * label( Companion o, int pos ) { return o.labels[ pos ]; }
\end{lstlisting}
Notably, the Companion structure definition, and all companion objects, are visible to the users.
A user can retrieve values and labels defined in an enumeration by accessing the values and labels directly, or indirectly by calling Companion functions $values$ and $labels$
\begin{lstlisting}[label=lst:companion_definition_values_labels]
Colour.values; // read the Companion's values
values( Colour ); // Same as Colour.values
\end{lstlisting}

\subsection{User Define Enumeration Functions}

The Companion objects make extending features for \CFA enumeration easy. 

\begin{lstlisting}[label=lst:companion_user_definition]
char * charastic_string( Companion o, int position ) { 
	return sprintf("Label: %s; Value: %s", label( o, position ), value( o, position) ); 
}
printf( charactic_string ( Color, 1 ) );
>>> Label: G; Value: G
\end{lstlisting}
Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.

The \CFA compiler turns a function call that takes an enumeration instance as a parameter into a function call with a companion object plus a position.
Therefore, a user can use the syntax with a user-defined enumeration function call:
\begin{lstlisting}[label=lst:companion_user_definition]
charactic_string ( Color.Green ); // equivalent to charactic_string ( Color, 1 )
>>> Label: G; Value: G
\end{lstlisting}
Similarly, the user can work with the enumeration type itself: (see section ref...)
\begin{lstlisting}[ label=lst:companion_user_definition]
void print_enumerators ( Companion o ) { 
	for ( c : Companion o ) {
		sout | label (c) | value( c ) ;
	} 
}
print_enumerators( Colour );
\end{lstlisting}

\subsection{Runtime Enumeration}

The Companion structure definition is visible to users, and users can create an instance of Companion object themselves, which effectively constructs a \textit{Runtime Enumeration}.
\begin{lstlisting}[ label=lst:runtime_enum ]
const char values[] = { "Hello", "World" };
const char labels[] = { "First", "Second" };
Companion (char *) MyEnum = { .values: values, .labels: labels, .length: 2 };
\end{lstlisting}
A runtime enumeration can be used to call enumeration functions.
\begin{lstlisting}[ label=lst:runtime_enum_usage ]
sout | charatstic_string( MyEnum, 1 );
>>> Label: Second; Value: World
\end{lstlisting}
However, a runtime enumeration cannot create an enumeration instance, and it does not support enum-qualified syntax.
\begin{lstlisting}[ label=lst:runtime_enum_usage ]
MyEnum e = MyEnum.First; // Does not work: cannot create an enumeration instance e, 
			            // and MyEnum.First is not recognizable
\end{lstlisting}
During the compilation, \CFA adds enumeration declarations to an enumeration symbol table and creates specialized function definitions for \CFA enumeration. \CFA does not recognize runtime enumeration during compilation and would not add them to the enumeration symbol table, resulting in a lack of supports for runtime enumeration.

\section{Enumeration Features}

A trait is a collection of constraints in \CFA, which can be used to describe types.
The \CFA standard library defines traits to categorize types with related enumeration features.

\subsection{Auto Initializable}
\label{s:AutoInitializable}

TODO: make the initialization rule a separate section. 

If no explicit initializer is given to an enumeration constant, C initializes the first enumeration constant with value 0, and the other enumeration constant has a value equal to its $predecessor+1$.
\CFA enumerations have the same rule in enumeration constant initialization.
However, not all types can be automatically initialized by \CFA because the meaning of $zero$, $one$, and addition operator may not be well-defined.

A type is auto-Initializable if it has defined @zero_t@, @one_t@, and an addition operator.
\begin{lstlisting}
forall(T)
trait AutoInitializable {
	void ?()( T & t, zero_t );
	void ?()( T & t, one_t );
	S ?+?( T & t, one_t );
};
\end{lstlisting}
An example of user-defined @AutoInitializable@ would look like the following:
\begin{lstlisting}[label=lst:sample_auto_Initializable]
struct Odd { int i; };
void ?()( Odd & t, zero_t ) { t.i = 1; };
void ?()( Odd & t, one_t ) { t.i = 2; };
Odd ?+?( Odd t1, Odd t2 ) 
	{ return Odd( t1.i + t2.i); };
\end{lstlisting}
When an enumeration declares an AutoInitializable as its type, no explicit initialization is necessary. 
\begin{lstlisting}[label=lst:sample_auto_Initializable_usage]
enum AutoInitUsage(Odd) {
	A, B, C = 6, D
};
\end{lstlisting}

In the example~\ref{lst:sample_auto_Initializable_usage_gen}, because no initializer is specified for the first enumeration constant @A@, \CFA initializes it with the value of @zero_t@, which is 1.
@B@ and @D@ have the values of their $predecessor + one_t$, while @one_t@ has the value 2.
Therefore, the enumeration is initialized as the following:
\begin{lstlisting}[label=lst:sample_auto_Initializable_usage_gen]
enum AutoInitUsage(Odd) {
	A=1, B=3, C = 6, D=8
};
\end{lstlisting}
In \CFA, integral types, float types, and imaginary numbers are example types that are AutoInitialiable.
\begin{lstlisting}[label=lst:letter]
enum Alphabet(int) {
	A='A', B, C, D, E, F, G, H, I, J, K, L, M,
	N, O, P, Q, R, S, T, U, V, W, X, Y, Z,
	a='a', b, c, d, e, f, g, h, i, j, k, l, m,
	n, o, p, q, r, s, t, u, v, w, x, y, z
};
print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.o );
>>> F, o, o
\end{lstlisting}

\subsection{Iteration and Range}

It is convenient to iterate over a \CFA enumeration.
Here is the basic usage:
\begin{lstlisting}[label=lst:range_functions]
for ( Alphabet ah; Alphabet; ) {
	printf( "%d ", ah );
}
>>> A B C (...omit the rest)
\end{lstlisting}
The for-loop uses the enumeration type @Alphabet@ as range.
When that happens, \CFA iterates all enumerators in the order they defined in the enumeration.
@'ch'@ is the iterating enumerator, and it returns the value of an Alphabet in this context according to the precedence rule.

\CFA offers a shorthand for iterating all enumeration constants: 
\begin{lstlisting}[label=lst:range_functions]
for ( Alphabet ch ) {
	printf( "%d ", ch );
}
>>> A B C (...omit the rest)
\end{lstlisting}

Enumeration supports the \CFA loop control syntax for for-loop.
\begin{lstlisting}[label=lst:range_functions]
for ( Alphabet.D )
for ( ch; Alphabet.g ~ Alphabet.z )
for ( Alphabet ch; Alphabet.R ~ Alphabet.X ~ 2 )
\end{lstlisting}
Notably, the meaning of "step" of iteration has changed for enumeration.
Consider the following example:
\begin{lstlisting}[label=lst:range_functions]
enum(int) Sequence {
	A = 10, B = 12, C = 14;  
}
for ( s; Sequence.A ~ Sequence.C ) {
	printf( "%d ", s ); 
}

>>> 10 12 14

for ( s; Sequence.A ~ Sequence.A ~ 2 ) {
	printf( "%d ", s ); 
}
>>> 10 14
\end{lstlisting}
The range iteration of enumeration does not return the @current_value++@ until it reaches the upper bound.
The semantics is to return the next enumeration constant.
If a stepping is specified, 2 for example, it returns the 2 enumeration constant after the current one, rather than the @current+2@.

It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
\begin{lstlisting}[label=lst:range_functions_label_implicit]
for ( char * ch; Alphabet )
\end{lstlisting}
This for-loop implicitly iterates every label of the enumeration, because a label is the only valid resolution to the ch with type @char *@ in this case.
If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
\begin{lstlisting}[label=lst:range_functions_label_implicit]
for ( char * ch; labels( Alphabet ) )
\end{lstlisting}

\section{Implementation}

\CFA places the definition of Companion structure and non-parameterized Companion functions in the prelude, visible globally.

\subsection{Declaration}

The qualified enumeration syntax is dedicated to \CFA enumeration.
\begin{lstlisting}[label=lst:range_functions]
enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
\end{lstlisting}
A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
During the $Validation$ pass, the compiler links the type declaration to the type's definition.
It ensures that the name of an enumerator is unique within the enumeration body, and checks if all values of the enumerator have the declaration type.
If the declared type is not @Auto Initializable@, \CFA rejects the enumeration definition.
Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section) 

\begin{lstlisting}[label=lst:init]
struct T { ... };
void ?{}( T & t, zero_t ) { ... };
void ?{}( T & t, one_t ) { ... };
T ?+?( T & lhs, T & rhs ) { ... };

enum (T) Sample { 
	Zero: 0 /* zero_t */, 
	One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
};
\end{lstlisting}
Challenge: \\
The value of an enumerator, or the initializer, requires @const_expr@.
While previously getting around the issue by pushing it to the C compiler, it might not work anymore because of the user-defined types, user-defined @zero_t@, @one_t@, and addition operation.
Might not be able to implement a \emph{correct} static check.

\CFA $autogens$ a Companion object for the declared enumeration.
\begin{lstlisting}[label=lst:companion]
Companion( T ) Sample {
	.values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
	.labels: { "Zero", "One", "Two", "Three", ...},
	.length: /* number of enumerators */
};
\end{lstlisting}
\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
But the result is computed at run time, and the compiler ensures the @values@ are not changed.

\subsection{qualified expression}

\CFA uses qualified expression to address the scoping of \CFA-enumeration. 
\begin{lstlisting}[label=lst:qualified_expression]
aggregation_name.field;
\end{lstlisting}
The qualified expression is not dedicated to \CFA enumeration.
It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.

\subsection{\lstinline{with} statement/statement}

\emph{Work in Progress}

Instead of qualifying an enumeration expression every time, one can use the @with@ to expose enumerators to the current scope so that they are directly accessible.

\subsection{Instance Declaration}

\emph{Work in Progress}

\begin{lstlisting}[label=lst:declaration]
enum Sample s1;
Sample s2;
\end{lstlisting}
A declaration of \CFA enumeration instance that has no difference than a C enumeration or other \CFA aggregation.
The compiler recognizes the type of a variable declaration by searching the name in all possible types.
The @enum@ keyword is not necessary but helps to disambiguate types (questionable).
The generated code for a \CFA enumeration declaration is utterly an integer, which is meant to store the position.
\begin{lstlisting}[label=lst:declaration]
int s1;
int s2;
\end{lstlisting}

\subsection{Compiler Representation}

\emph{Work in Progress}

The internal representation of an enumeration constant is @EnumInstType@.
The minimum information an @EnumInstType@ stores is a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
\begin{lstlisting}[label=lst:EnumInstType]
class EnumInstType {
	EnumDecl enumDecl;
	int position;
};
\end{lstlisting}

\subsection{Unification and Resolution }

\emph{Work in Progress}

\begin{lstlisting}
enum Colour( char * ) { Red = "R", Green = "G", Blue = "B"  };
\end{lstlisting}
The @EnumInstType@ is convertible to other types.
A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context. 

\begin{lstlisting}[caption={Null Context}, label=lst:null_context]
{
	Colour.Green;
}
\end{lstlisting}
In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
In this case, any of the attributes is resolvable.
According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
\begin{lstlisting}[caption={Null Context Generated Code}, label=lst:null_context]
{
	"G";
}
\end{lstlisting}
\begin{lstlisting}[caption={int Context}, label=lst:int_context]
{
	int g = Colour.Green;
}
\end{lstlisting}
The assignment expression gives a context for the EnumInstType resolution.
The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
$$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
\begin{lstlisting}[label=lst:attr_resolution_1]
{
	Unify( int, char * ); // unify with the type of value
	Unify( int, int ); // unify with the type of position
	Unify( int, char * ); // unify with the type of label
}
\end{lstlisting}
\begin{lstlisting}[label=lst:attr_resolution_precedence]
{
	Unification( T1, EnumInstType<T2> ) {
		if ( Unify( T1, T2 ) ) return T2;
		if ( Unify( T1, int ) ) return int;
		if ( Unify( T1, char * ) ) return char *;
		Error: Cannot Unify T1 with EnumInstType<T2>;
	}
}
\end{lstlisting}
After the unification, @EnumInstType@ is replaced by its attributes.

\begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
{
	T2 foo ( T1 ); // function take variable with T1 as a parameter
	foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
	>>>> Unification( T1, EnumInstType<T3> )
}
\end{lstlisting}
% The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType. 
Backward conversion:
\begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
{
	enum Colour colour = 1;
}
\end{lstlisting}

\begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
{
   Unification( EnumInstType<Colour>, int ) >>> label
}
\end{lstlisting}
@int@ can be unified with the label of Colour.
@5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into 
\begin{lstlisting}
{
   enum Colour colour = Colour.Green; 
}
\end{lstlisting}
Steps:
\begin{enumerate}
\item
identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
\item
@unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
\item
return the enumeration constant at the position 1
\end{enumerate}
\begin{lstlisting}
{
	enum T (int) { ... } // Declaration
	enum T t = 1; 
}
\end{lstlisting}
Steps:
\begin{enumerate}
\item
identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
\item
@unification( EnumInstType<Colour>, int )@: @value( EnumInstType< Colour > )@
\item
return the FIRST enumeration constant that has the value 1, by searching through the values array
\end{enumerate}
The downside of the precedence rule: @EnumInstType@ $\Rightarrow$ @int ( value )@ $\Rightarrow$ @EnumInstType@ may return a different @EnumInstType@ because the value can be repeated and there is no way to know which one is expected $\Rightarrow$ want uniqueness 

\end{document}

% Local Variables: %
% tab-width: 4 %
% compile-command: "pdflatex enum.tex" %
% End: %
