\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}} % Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}. % The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc} % The star version does not lowercase the index information, e.g., \newterm*{IBM}. \newcommand{\newtermFontInline}{\emph} \newcommand{\newterm}{\protect\@ifstar\@snewterm\@newterm} \newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi} \newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi} \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{\CCIcon}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}} % C++ icon \newcommand{\CC}[1][]{\protect\CCIcon{#1}\xspace} % C++ 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, escapechar=\$, % LaTeX escape in CFA code % 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 and \CC use 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 }; $\(\uparrow\)$ $\(\uparrow\)$ ${\rm \newterm{enumeration name}}$ ${\rm \newterm{enumerator names}} \end{lstlisting} The example defines an enumeration 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 is an integral type, with consecutive enumerator values assigned by the compiler starting at zero or the next explicitly initialized value by the programmer. For example, @Monday@ to @Wednesday@ have values 0--2 implicitly set by the compiler, @Thursday@ is explicitly set to @10@ by the programmer, and @Friday@ to @Sunday@ have values 11--13 implicitly set by the compiler. There are 3 attributes for an enumeration: \newterm{position}, \newterm{label}, and \newterm{value}: \begin{cquote} \small\sf\setlength{\tabcolsep}{3pt} \begin{tabular}{rccccccccccc} @enum@ Weekday \{ & Monday, & Tuesday, & Wednesday, & Thursday=10, & Friday, & Saturday, & Sunday \}; \\ \it position & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\ \it label & Monday & Tuesday & Wednesday & Thursday & Friday & Saturday & Sunday \\ \it value & 0 & 1 & 2 & 10 & 11 & 12 & 13 \end{tabular} \end{cquote} The enumerators of an enumeration are unscoped, i.e., enumerators declared inside of an @enum@ are visible in the enclosing scope of the @enum@ type. \begin{lstlisting}[label=lst:enum_scope] { enum Weekday { ... }; // enumerators implicitly projected into local scope Weekday weekday = Monday; weekday = Friday; int i = Sunday // i == 13 } int j = Wednesday; // ERROR! Wednesday 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 from 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 with a defined ordering can be automatically initialized (see Section~\ref{s:AutoInitializable}). % An instance of \CFA-enum (denoted as @@) is a label for the defined enum name. % The label can be retrieved by calling the function @label( )@. % Similarly, the @value()@ function returns the value used to initialize the \CFA-enum. \subsection{Enumerator Scoping} A \CFA-enum can be scoped, meaning the enumerator constants are not projected into the enclosing scope. \begin{lstlisting} enum Colour( char * ) @!@ { ... }; \end{lstlisting} where the @'!'@ implies the enumerators are \emph{not} projected. The enumerators of a scoped enumeration are accessed using qualification, like the fields of an aggregate. % The syntax of $qualified\_expression$ for \CFA-enum is the following: % $$ := .$$ \begin{lstlisting} Colour colour = @Colour.@Red; // qualification colour = @Colour.@Blue; \end{lstlisting} \subsection{Enumerator Attributes} The attributes of an enumerator are accessed by pseudo-functions @position@, @value@, and @label@, i.e., like @sizeof@. \begin{lstlisting} int green_pos = @position@( Colour.Green ); // 1 char * green_value = @value@( Colour.Green ); // "G" char * green_label = @label@( Colour.Green ); // "Green" \end{lstlisting} There are implicit conversions from an enumerator to its attributes. \begin{lstlisting}[label=lst:enum_inst_assign_int] int green_pos = Colour.Green; // 1 char * green_value = Colour.Green; // ambiguous char * green_label = Colour.Green; // ambiguous \end{lstlisting} where a conversion is ambiguous, if the enumerator's type is same as an attribute's type. For example, @value( Colour.Green )@ and @label( Colour.Green )@ both have type @char *@. Further examples are: \begin{cquote} \begin{tabular}{ll} \begin{lstlisting} int monday_pos = Monday; // ambiguous int monday_value = Monday; // ambiguous char * monday_label = Monday; // "Monday" \end{lstlisting} & \begin{lstlisting} enum(double) Math { PI = 3.14159, E = 2.718 }; int pi_pos = PI; // 0 double pi_value = PI; // 3.14159 char * pi_label = PI; // "PI" \end{lstlisting} \end{tabular} \end{cquote} Here, @position( Monday )@ and @value( Monday )@ both have type @int@, while all attribute types are unique for enumerator @PI@. 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. \PAB{Not sure this is going to work.} \subsection{Enumerator Storage} Although \CFA enumeration captures three different attributes, an enumeration instance does not store all this information. The @sizeof@ a \CFA enumeration instance is always 4 bytes, the same size as a C enumeration instance (@sizeof( int )@). 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 an enumeration instance @colour@ and assigning it with the enumerator @Color.Green@, the compiler allocates an integer variable and stores 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 a @Companion@ object 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 return the position it is passed. 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 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} 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: Green; 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: Green; 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. \PAB{Not sure how useful this feature is.} \section{Enumeration Features} A trait is a collection of constraints in \CFA that 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 next enumeration constant has a value equal to its $predecessor + 1$. \CFA enumerations have the same rule in enumeration constant initialization. However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA. Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@: \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 a user-defined @AutoInitializable@ is: \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 the type of an enumeration is @AutoInitializable@, implicit initialization is available. \begin{lstlisting}[label=lst:sample_auto_Initializable_usage] enum AutoInitUsage(Odd) { A, B, C = 7, D }; \end{lstlisting} In the example, there is no initializer specified for the first enumeration constant @A@, so \CFA initializes it with the value of @zero_t@, which is 1. @B@ and @D@ have the values of their $predecessor + one_t$, where @one_t@ has the value 2. Therefore, the enumeration is initialized as follows: \begin{lstlisting}[label=lst:sample_auto_Initializable_usage_gen] enum AutoInitUsage(Odd) { A = 1, B = 3, C = 7, D = 9 }; \end{lstlisting} Note, there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@. In \CFA, character, integral, float, and imaginary types are all @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.z ); >>> F, o, z \end{lstlisting} \subsection{Iteration and Range} It is convenient to iterate over a \CFA enumeration, e.g.: \begin{lstlisting}[label=lst:range_functions] for ( Alphabet alph; Alphabet ) { printf( "%d ", alph ); } >>> A B C ... \end{lstlisting} The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration. @alph@ is the iterating enumeration object, which 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 alph ) { printf( "%d ", alph ); } >>> A B C ... \end{lstlisting} The following different loop-control syntax is supported: \begin{lstlisting}[label=lst:range_functions] for ( Alphabet.D ) for ( alph; Alphabet.g ~ Alphabet.z ) for ( Alphabet alph; Alphabet.R ~ Alphabet.X ~ 2 ) \end{lstlisting} \PAB{Explain what each loop does.} Notably, the meaning of ``step'' for an 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 * alph; 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 @AutoInitializable@, \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} \emph{Work in Progress} Instead of qualifying an enumeration expression every time, the @with@ can be used to expose enumerators to the current scope, making them 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 )$$ 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 ) { if ( Unify( T1, T2 ) ) return T2; if ( Unify( T1, int ) ) return int; if ( Unify( T1, char * ) ) return char *; Error: Cannot Unify T1 with EnumInstType; } } \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 ); // Call foo with a variable has type EnumInstType >>>> Unification( T1, EnumInstType ) } \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, 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, 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, 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: %