source: doc/proposals/enum.tex @ d1551a5

Last change on this file since d1551a5 was 367725d, checked in by JiadaL <j82liang@…>, 6 months ago

Update enum.tex

  • Property mode set to 100644
File size: 41.4 KB
Line 
1\documentclass[12pt]{article}
2\usepackage{fullpage,times}
3\usepackage{pslatex}                    % reduce size of san serif font
4\usepackage{xcolor}
5\usepackage{listings}
6%\usepackage{array}
7\usepackage{graphics}
8\usepackage{xspace}
9
10\makeatletter
11\renewcommand\section{\@startsection{section}{1}{\z@}{-3.0ex \@plus -1ex \@minus -.2ex}{1.5ex \@plus .2ex}{\normalfont\large\bfseries}}
12\renewcommand\subsection{\@startsection{subsection}{2}{\z@}{-2.75ex \@plus -1ex \@minus -.2ex}{1.25ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
13\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}{-2.5ex \@plus -1ex \@minus -.2ex}{1.0ex \@plus .2ex}{\normalfont\normalsize\bfseries}}
14\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}{-2.0ex \@plus -1ex \@minus -.2ex}{-1em}{\normalfont\normalsize\bfseries}}
15\renewcommand\subparagraph{\@startsection{subparagraph}{4}{\z@}{-1.5ex \@plus -1ex \@minus -.2ex}{-1em}{\normalfont\normalsize\bfseries\itshape}}
16
17% Denote newterms in particular font and index them without particular font and in lowercase, e.g., \newterm{abc}.
18% The option parameter provides an index term different from the new term, e.g., \newterm[\texttt{abc}]{abc}
19% The star version does not lowercase the index information, e.g., \newterm*{IBM}.
20\newcommand{\newtermFontInline}{\emph}
21\newcommand{\newterm}{\protect\@ifstar\@snewterm\@newterm}
22\newcommand{\@newterm}[2][\@empty]{\lowercase{\def\temp{#2}}{\newtermFontInline{#2}}\ifx#1\@empty\index{\temp}\else\index{#1@{\protect#2}}\fi}
23\newcommand{\@snewterm}[2][\@empty]{{\newtermFontInline{#2}}\ifx#1\@empty\index{#2}\else\index{#1@{\protect#2}}\fi}
24\makeatother
25
26\usepackage[ignoredisplayed]{enumitem}  % do not affect trivlist
27\setlist{labelsep=1ex}% global
28\setlist[itemize]{topsep=0.5ex,parsep=0.25ex,itemsep=0.25ex,listparindent=\parindent,leftmargin=\parindent}% global
29\setlist[itemize,1]{label=\textbullet}% local
30%\renewcommand{\labelitemi}{{\raisebox{0.25ex}{\footnotesize$\bullet$}}}
31\setlist[enumerate]{topsep=0.5ex,parsep=0.25ex,itemsep=0.25ex,listparindent=\parindent}% global
32\setlist[enumerate,2]{leftmargin=\parindent,labelsep=*,align=parleft,label=\alph*.}% local
33\setlist[description]{topsep=0.5ex,itemsep=0pt,listparindent=\parindent,leftmargin=\parindent,labelsep=1.5ex}
34
35\newenvironment{cquote}{%
36        \list{}{\lstset{resetmargins=true,aboveskip=0pt,belowskip=0pt}\topsep=4pt\parsep=0pt\leftmargin=\parindent\rightmargin\leftmargin}%
37        \item\relax
38}{%
39        \endlist
40}% cquote
41
42\setlength{\topmargin}{-0.45in}                                                 % move running title into header
43\setlength{\headsep}{0.25in}
44\setlength{\textheight}{9.0in}
45
46\newcommand{\CFAIcon}{\textsf{C\raisebox{\depth}{\rotatebox{180}A}}} % Cforall icon
47\newcommand{\CFA}{\protect\CFAIcon\xspace}                              % CFA symbolic name
48\newcommand{\CCIcon}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}} % C++ icon
49\newcommand{\CC}[1][]{\protect\CCIcon{#1}\xspace}               % C++ symbolic name
50\newcommand{\PAB}[1]{{\color{red}PAB: #1}}
51
52% \definecolor{mGreen}{rgb}{0,0.6,0}
53% \definecolor{mGray}{rgb}{0.5,0.5,0.5}
54% \definecolor{mPurple}{rgb}{0.58,0,0.82}
55% \definecolor{backgroundColour}{rgb}{0.95,0.95,0.92}
56
57\lstdefinestyle{CStyle}{
58%    backgroundcolor=\color{backgroundColour},   
59%    commentstyle=\color{mGreen},
60%    keywordstyle=\color{magenta},
61        stringstyle=\small\tt,                                  % use typewriter font
62%    stringstyle=\color{mPurple},
63    columns=fullflexible,
64    basicstyle=\small\linespread{0.9}\sf,       % reduce line spacing and use sanserif font
65%   basicstyle=\footnotesize,
66    breakatwhitespace=false,         
67%    breaklines=true,                 
68    captionpos=b,                   
69    keepspaces=true,                 
70        escapechar=\$,                                                  % LaTeX escape in CFA code
71%    numbers=left,                   
72%    numbersep=5pt,                 
73%    numberstyle=\tiny\color{mGray},
74%    showspaces=false,               
75    showstringspaces=false,
76%    showtabs=false,                 
77        showlines=true,                                                 % show blank lines at end of code
78    tabsize=5,
79    language=C,
80        aboveskip=4pt,                                                  % spacing above/below code block
81        belowskip=2pt,
82        xleftmargin=\parindent,                 % indent code to paragraph indentation
83}
84\lstset{style=CStyle,moredelim=**[is][\color{red}]{@}{@}}
85\lstMakeShortInline@                            % single-character for \lstinline
86
87\begin{document}
88
89\title{\vspace*{-0.5in}Enumeration in \CFA}
90\author{Jiada Liang}
91
92\maketitle
93
94\begin{abstract}
95An enumeration is a type that defines a list of named constant values in C (and other languages).
96C and \CC use an integral type as the underlying representation of an enumeration.
97\CFA extends C enumerations to allow all basic and custom types for the inner representation.
98\end{abstract}
99
100\section{C-Style Enum}
101
102\CFA supports the C-Style enumeration using the same syntax and semantics.
103\begin{lstlisting}[label=lst:weekday]
104enum Weekday { Monday, Tuesday, Wednesday, Thursday=10, Friday, Saturday, Sunday };
105                $\(\uparrow\)$                                                                      $\(\uparrow\)$
106    ${\rm \newterm{enumeration name}}$                                        ${\rm \newterm{enumerator names}}
107\end{lstlisting}
108The example defines an enumeration type @Weekday@ with ordered enumerators @Monday@, @Tuesday@, @Wednesday@, @Thursday@, @Friday@, @Saturday@ and @Sunday@.
109The successor of @Tuesday@ is @Monday@ and the predecessor of @Tuesday@ is @Wednesday@.
110A 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.
111For 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.
112
113There are 3 attributes for an enumeration: \newterm{position}, \newterm{label}, and \newterm{value}:
114\begin{cquote}
115\small\sf\setlength{\tabcolsep}{3pt}
116\begin{tabular}{rccccccccccc}
117@enum@ Weekday \{       & Monday,       & Tuesday,      & Wednesday,    & Thursday=10,  & Friday,       & Saturday,     & Sunday \}; \\
118\it position            & 0                     & 1                     & 2                             & 3                             & 4                     & 5                     & 6                     \\
119\it label                       & Monday        & Tuesday       & Wednesday             & Thursday              & Friday        & Saturday      & Sunday        \\
120\it value                       & 0                     & 1                     & 2                             & 10                    & 11            & 12            & 13
121\end{tabular}
122\end{cquote}
123
124The enumerators of an enumeration are unscoped, i.e., enumerators declared inside of an @enum@ are visible in the enclosing scope of the @enum@ type.
125\begin{lstlisting}[label=lst:enum_scope]
126{
127        enum Weekday { ... };   // enumerators implicitly projected into local scope
128        Weekday weekday = Monday;
129        weekday = Friday;
130        int i = Sunday  // i == 13
131}
132int j = Wednesday; // ERROR! Wednesday is not declared in this scope
133\end{lstlisting}
134
135\section{\CFA-Style Enum}
136
137A \CFA enumeration is parameterized by a type specifying each enumerator's type.
138\CFA allows any object type for the enumerators, and values assigned to enumerators must be from the declared type.
139\begin{lstlisting}[label=lst:color]
140enum Colour( @char *@ ) { Red = "R", Green = "G", Blue = "B"  };
141\end{lstlisting}
142The type of @Colour@ is @char *@ and each enumerator is initialized with a C string.
143Only types with a defined ordering can be automatically initialized (see Section~\ref{s:AutoInitializable}).
144
145% An instance of \CFA-enum (denoted as @<enum_instance>@) is a label for the defined enum name.
146% The label can be retrieved by calling the function @label( <enum_instance> )@.
147% Similarly, the @value()@ function returns the value used to initialize the \CFA-enum.
148
149\subsection{Enumerator Scoping}
150
151A \CFA-enum can be scoped, meaning the enumerator constants are not projected into the enclosing scope.
152\begin{lstlisting}
153enum Colour( char * ) @!@ { ... };
154\end{lstlisting}
155where the @'!'@ implies the enumerators are \emph{not} projected.
156The enumerators of a scoped enumeration are accessed using qualifications, like the fields of an aggregate.
157% The syntax of $qualified\_expression$ for \CFA-enum is the following:
158% $$<qualified\_expression> := <enum\_type>.<enumerator>$$
159\begin{lstlisting}
160Colour colour = @Colour.@Red;   // qualification
161colour = @Colour.@Blue;
162\end{lstlisting}
163
164\section{Enumeration Pseudo-functions}
165Pseudo-functions are function-like operators that do not result in any run-time computations, i.e., like @sizeof@. Instead, the call to functions will be substituted into other expressions in compilation time.
166
167\subsection{Enumerator Attributes}
168The attributes of an enumerator are accessed by pseudo-functions @position@, @value@, and @label@.
169\begin{lstlisting}
170int green_pos = @position@( Colour.Green );     // 1
171char * green_value = @value@( Colour.Green ); / "G"
172char * green_label = @label@( Colour.Green ); // "Green"
173\end{lstlisting}
174
175\subsection{enumerate()}
176\begin{lstlisting}[label=lst:c_switch]
177enum(int) C_ENUM { First, Second, Third = First, Fourth };
178int v(C_ENUM e) { 
179    switch( e ) {
180        case First: return 0; break;
181        case Second: return 1; break;
182        // case Thrid: return 2; break;
183        // case Fourth: return 3; break;
184    };
185};
186\end{lstlisting}
187In the @C_ENUM@ example, @Third@ is an alias of @First@ and @Fourth@ is an alias of @Second@. Programmers cannot make case branches for @Third@ and @Fourth@ because the switch statement matches cases by the enumerator's value. Case First and Third, or Second and Fourth, has duplicate case values.
188
189@enumerate()@ is a pseudo-function that makes the switch statement match by an enumerator instead.
190\begin{lstlisting}[label=lst:c_switch_enumerate]
191enum(double) C_ENUM { First, Second, Third = First, Fourth };
192C_ENUM variable_a = First, variable_b = Second, variable_c = Thrid, variable_d = Fourth;
193int v(C_ENUM e) { 
194    switch( enumeratate( e ) ) {
195        case First: return e; break;
196        case Second: return value( e ); break;
197        case Thrid: return label( e ); break;
198        case Fourth: return position( e ); break;
199    };
200};
201p(variable_a); // 0
202p(variable_b); // 1
203p(variable_c); // "Third"
204p(variable_d); // 3
205\end{lstlisting}
206
207\section{Enumeration Storage}
208
209\subsection{Enumeration Variable}
210
211Although \CFA enumeration captures three different attributes, an enumeration instance does not store all this information.
212The @sizeof@ a \CFA enumeration instance is always 4 bytes, the same size as a C enumeration instance (@sizeof( int )@).
213It comes from the fact that:
214\begin{enumerate}
215\item
216a \CFA enumeration is always statically typed;
217\item
218it is always resolved as one of its attributes regarding real usage.
219\end{enumerate}
220When creating an enumeration instance @colour@ and assigning it with the enumerator @Color.Green@, the compiler allocates an integer variable and stores the position 1.
221The invocations of $positions()$, $value()$, and $label()$ turn into calls to special functions defined in the prelude:
222\begin{lstlisting}[label=lst:companion_call]
223position( green );
224>>> position( Colour, 1 ) -> int
225value( green );
226>>> value( Colour, 1 ) -> T
227label( green );
228>>> label( Colour, 1) -> char *
229\end{lstlisting}
230@T@ represents the type declared in the \CFA enumeration defined and @char *@ in the example.
231These generated functions are $Companion Functions$, they take an $companion$ object and the position as parameters.
232
233\subsection{Enumeration Data}
234\begin{lstlisting}[label=lst:enumeration_backing_data]
235enum(T) E { ... };
236// backing data
237T* E_values;
238char** E_labels;
239\end{lstlisting}
240Storing values and labels as arrays can sometimes help support enumeration features. However, the data structures are the overhead for the programs. We want to reduce the memory usage for enumeration support by:
241\begin{itemize}
242    \item Only generates the data array if necessary
243    \item The compilation units share the data structures. No extra overhead if the data structures are requested multiple times.
244\end{itemize}
245
246
247\
248\section{Unification}
249
250\subsection{Enumeration as Value}
251\label{section:enumeration_as_value}
252An \CFA enumeration with base type T can be used seamlessly as T, without explicitly calling the pseudo-function value.
253\begin{lstlisting}[label=lst:implicit_conversion]
254char * green_value = Colour.Green; // "G"
255// Is equivalent to
256// char * green_value = value( Color.Green ); "G"
257\end{lstlisting}
258
259\subsection{Unification Distance}
260\begin{lstlisting}[label=lst:unification_distance_example]
261T_2 Foo(T1);
262\end{lstlisting}
263The @Foo@ function expects a parameter with type @T1@. In C, only a value with the exact type T1 can be used as a parameter for @Foo@. In \CFA, @Foo@ accepts value with some type @T3@ as long as @distance(T1, T3)@ is not @Infinite@.
264
265@path(A, B)@ is a compiler concept that returns one of the following:
266\begin{itemize}
267    \item Zero or 0, if and only if $A == B$.
268    \item Safe, if B can be used as A without losing its precision, or B is a subtype of A.
269    \item Unsafe, if B loses its precision when used as A, or A is a subtype of B.
270    \item Infinite, if B cannot be used as A. A is not a subtype of B and B is not a subtype of A.
271\end{itemize}
272
273For example, @path(int, int)==Zero@, @path(int, char)==Safe@, @path(int, double)==Unsafe@, @path(int, struct S)@ is @Infinite@ for @struct S{}@.
274@distance(A, C)@ is the minimum sum of paths from A to C. For example, if @path(A, B)==i@, @path(B, C)==j@, and @path(A, C)=k@, then $$distance(A,C)==min(path(A,B), path(B,C))==i+j$$.
275
276(Skip over the distance matrix here because it is mostly irrelevant for enumeration discussion. In the actual implementation, distance( E, T ) is 1.)
277
278The arithmetic of distance is the following:
279\begin{itemize}
280    \item $Zero + v= v$, for some value v.
281    \item $Safe * k <  Unsafe$, for finite k.
282    \item $Unsafe * k < Infinite$, for finite k.
283    \item $Infinite + v = Infinite$, for some value v.
284\end{itemize}
285
286For @enum(T) E@, @path(T, E)==Safe@ and @path(E,T)==Infinite@. In other words, enumeration type E can be @safely@ used as type T, but type T cannot be used when the resolution context expects a variable with enumeration type @E@.
287
288
289\subsection{Variable Overloading and Parameter Unification}
290\CFA allows variable names to be overloaded. It is possible to overload a variable that has type T and an enumeration with type T.
291\begin{lstlisting}[label=lst:variable_overload]
292char * green = "Green";
293Colour green = Colour.Green; // "G"
294
295void bar(char * s) { return s; }
296void foo(Colour c) { return value( c ); }
297
298foo( green ); // "G"
299bar( green ); // "Green"
300\end{lstlisting}
301\CFA's conversion distance helps disambiguation in this overloading. For the function @bar@ which expects the parameter s to have type @char *@, $distance(char *,char *) == Zero$ while $distance(char *, Colour) == Safe$, the path from @char *@ to the enumeration with based type @char *@, \CFA chooses the @green@ with type @char *@ unambiguously. On the other hand, for the function @foo@, @distance(Colour, char *)@ is @Infinite@, @foo@ picks the @green@ with type @char *@.
302
303\subsection{Function Overloading}
304Similarly, functions can be overloaded with different signatures. \CFA picks the correct function entity based on the distance between parameter types and the arguments.
305\begin{lstlisting}[label=lst:function_overload]
306Colour green = Colour.Green;
307void foo(Colour c) { sout | "It is an enum"; } // First foo
308void foo(char * s) { sout | "It is a string"; } // Second foo
309foo( green ); // "It is an enum"
310\end{lstlisting}
311Because @distance(Colour, Colour)@ is @Zero@ and @distance(char *, Colour)@ is @Safe@, \CFA determines the @foo( green )@ is a call to the first foo.
312
313\subsection{Attributes Functions}
314The pseudo-function @value()@ "unboxes" the enumeration and the type of the expression is the underlying type. Therefore, in the section~\ref{section:enumeration_as_value} when assigning @Colour.Green@ to variable typed @char *@, the resolution distance is @Safe@, while assigning @value(Color.Green) to @char *) has resolution distance @Zero@.
315
316\begin{lstlisting}[label=lst:declaration_code]
317int s1;
318\end{lstlisting}
319The generated code for an enumeration instance is simply an int. It is to hold the position of an enumeration. And usage of variable @s1@ will be converted to return one of its attributes: label, value, or position, concerning the @Unification@ rule
320
321% \subsection{Unification and Resolution (this implementation will probably not be used, safe as reference for now)}
322
323% \begin{lstlisting}
324% enum Colour( char * ) { Red = "R", Green = "G", Blue = "B"  };
325% \end{lstlisting}
326% The @EnumInstType@ is convertible to other types.
327% A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
328% The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context.
329
330% \begin{lstlisting}[caption={Null Context}, label=lst:null_context]
331% {
332%       Colour.Green;
333% }
334% \end{lstlisting}
335% In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
336% In this case, any of the attributes is resolvable.
337% According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
338% The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
339% When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
340% \begin{lstlisting}[caption={Null Context Generated Code}, label=lst:null_context]
341% {
342%       "G";
343% }
344% \end{lstlisting}
345% \begin{lstlisting}[caption={int Context}, label=lst:int_context]
346% {
347%       int g = Colour.Green;
348% }
349% \end{lstlisting}
350% The assignment expression gives a context for the EnumInstType resolution.
351% The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
352% The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
353% In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
354% $$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
355% \begin{lstlisting}[label=lst:attr_resolution_1]
356% {
357%       Unify( int, char * ); // unify with the type of value
358%       Unify( int, int ); // unify with the type of position
359%       Unify( int, char * ); // unify with the type of label
360% }
361% \end{lstlisting}
362% \begin{lstlisting}[label=lst:attr_resolution_precedence]
363% {
364%       Unification( T1, EnumInstType<T2> ) {
365%               if ( Unify( T1, T2 ) ) return T2;
366%               if ( Unify( T1, int ) ) return int;
367%               if ( Unify( T1, char * ) ) return char *;
368%               Error: Cannot Unify T1 with EnumInstType<T2>;
369%       }
370% }
371% \end{lstlisting}
372% After the unification, @EnumInstType@ is replaced by its attributes.
373
374% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
375% {
376%       T2 foo ( T1 ); // function take variable with T1 as a parameter
377%       foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
378%       >>>> Unification( T1, EnumInstType<T3> )
379% }
380% \end{lstlisting}
381% % The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType.
382% Backward conversion:
383% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
384% {
385%       enum Colour colour = 1;
386% }
387% \end{lstlisting}
388
389% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
390% {
391%    Unification( EnumInstType<Colour>, int ) >>> label
392% }
393% \end{lstlisting}
394% @int@ can be unified with the label of Colour.
395% @5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into
396% \begin{lstlisting}
397% {
398%    enum Colour colour = Colour.Green;
399% }
400% \end{lstlisting}
401% Steps:
402% \begin{enumerate}
403% \item
404% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
405% \item
406% @unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
407% \item
408% return the enumeration constant at position 1
409% \end{enumerate}
410% \begin{lstlisting}
411% {
412%       enum T (int) { ... } // Declaration
413%       enum T t = 1;
414% }
415% \end{lstlisting}
416% Steps:
417% \begin{enumerate}
418% \item
419% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
420% \item
421% @unification( EnumInstType<Colour>, int )@: @value( EnumInstType< Colour > )@
422% \item
423% return the FIRST enumeration constant that has the value 1, by searching through the values array
424% \end{enumerate}
425% 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
426
427% \subsection{Casting}
428% Casting an EnumInstType to some other type T works similarly to unify the EnumInstType with T. For example:
429% \begin{lstlisting}
430% enum( int ) Foo { A = 10, B = 100, C = 1000 };
431% (int) Foo.A;
432% \end{lstlisting}
433% The \CFA-compiler unifies @EnumInstType<int>@ with int, with returns @value( Foo.A )@, which has statically known value 10. In other words, \CFA-compiler is aware of a cast expression, and it forms the context for EnumInstType resolution. The expression with type @EnumInstType<int>@ can be replaced by the compile with a constant expression 10, and optionally discard the cast expression.
434
435% \subsection{Value Conversion}
436% As discussed in section~\ref{lst:var_declaration}, \CFA only saves @position@ as the necessary information. It is necessary for \CFA to generate intermediate code to retrieve other attributes.
437
438% \begin{lstlisting}
439% Foo a; // int a;
440% int j = a;
441% char * s = a;
442% \end{lstlisting}
443% Assume stores a value x, which cannot be statically determined. When assigning a to j in line 2, the compiler @Unify@ j with a, and returns @value( a )@. The generated code for the second line will be
444% \begin{lstlisting}
445% int j = value( Foo, a )
446% \end{lstlisting}
447% Similarly, the generated code for the third line is
448% \begin{lstlisting}
449% char * j = label( Foo, a )
450% \end{lstlisting}
451
452
453\section{Enumerator Initialization}
454An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
455
456\subsection{C Enumeration Rule}
457A C enumeration has an integral type. If not initialized, the first enumerator implicitly has the integral value 0, and other enumerators have a value equal to its $predecessor + 1$.
458
459\subsection{Auto Initializable}
460\label{s:AutoInitializable}
461
462
463\CFA enumerations have the same rule in enumeration constant initialization.
464However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA.
465
466Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@:
467\begin{lstlisting}
468forall(T)
469trait AutoInitializable {
470        void ?()( T & t, zero_t );
471        S ?++( T & t);
472};
473\end{lstlisting}
474An example of a user-defined @AutoInitializable@ is:
475\begin{lstlisting}[label=lst:sample_auto_Initializable]
476struct Odd { int i; };
477void ?()( Odd & t, zero_t ) { t.i = 1; };
478Odd ?++( Odd t1 ) { return Odd( t1.i + 2); };
479\end{lstlisting}
480When the type of an enumeration is @AutoInitializable@, implicit initialization is available.
481\begin{lstlisting}[label=lst:sample_auto_Initializable_usage]
482enum AutoInitUsage(Odd) {
483        A, B, C = 7, D
484};
485\end{lstlisting}
486In the example, no initializer is specified for the first enumeration constant @A@, so \CFA initializes it with the value of @zero_t@, which is 1.
487@B@ and @D@ have the values of their $predecessor++$, where @one_t@ has the value 2.
488Therefore, the enumeration is initialized as follows:
489\begin{lstlisting}[label=lst:sample_auto_Initializable_usage_gen]
490enum AutoInitUsage(Odd) {
491        A = 1, B = 3, C = 7, D = 9
492};
493\end{lstlisting}
494Note that there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@.
495
496In \CFA, character, integral, float, and imaginary types are all @AutoInitialiable@.
497\begin{lstlisting}[label=lst:letter]
498enum Alphabet( int ) {
499        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,
500        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
501};
502print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.z );
503>>> F, o, z
504\end{lstlisting}
505\section{Enumeration Features}
506\subsection{Iteration and Range}
507
508It is convenient to iterate over a \CFA enumeration value, e.g.:
509\begin{lstlisting}[label=lst:range_functions]
510for ( Alphabet alph; Alphabet ) { sout | alph; }
511>>> A B C ... D
512\end{lstlisting}
513The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
514@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
515
516\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
517\begin{lstlisting}[label=lst:range_functions]
518for ( Alphabet alph ) { sout | alph; }
519>>> A B C ... D
520\end{lstlisting}
521
522The following are examples for constructing for-control using an enumeration. Note that the type declaration of the iterating variable is optional, because \CFA can infer the type as EnumInstType based on the range expression, and possibly convert it to one of its attribute types.
523
524\textbullet\ H is implicit up-to exclusive range [0, H).
525\begin{lstlisting}[label=lst:range_function_1]
526for ( alph; Alphabet.D ) { sout | alph; }
527>>> A B C
528\end{lstlisting}
529
530\textbullet\ ~= H is implicit up-to inclusive range [0,H].
531\begin{lstlisting}[label=lst:range_function_2]
532for ( alph; ~= Alphabet.D ) { sout | alph; }
533>>> A B C D
534\end{lstlisting}
535
536\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
537\begin{lstlisting}[label=lst:range_function_3]
538for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
539// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
540>>> B C
541\end{lstlisting}
542
543\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
544\begin{lstlisting}[label=lst:range_function_4]
545for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
546>>> B C D
547\end{lstlisting}
548
549\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
550\begin{lstlisting}[label=lst:range_function_5]
551for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
552>>> D C
553\end{lstlisting}
554
555\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
556\begin{lstlisting}[label=lst:range_function_6]
557for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
558>>> D C B
559\end{lstlisting}
560
561A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
562\begin{lstlisting}[label=lst:range_function_stepping]
563enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
564for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
565>>> 10 12 14 16 18
566for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
567>>> 10 11 12 13 14 15 16 17 18
568\end{lstlisting}
569The first syntax is stepping to the next enumeration constant, which is the default stepping scheme if not explicitly specified. The second syntax, on the other hand, is to call @operator+=@ @one_type@ on the @value( s )@. Therefore, the second syntax is equivalent to
570\begin{lstlisting}[label=lst:range_function_stepping_converted]
571for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
572>>> 10 11 12 13 14 15 16 17 18
573\end{lstlisting}
574
575% \PAB{Explain what each loop does.}
576
577It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
578\begin{lstlisting}[label=lst:range_functions_label_implicit]
579for ( char * alph; Alphabet )
580\end{lstlisting}
581This 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.
582If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
583\begin{lstlisting}[label=lst:range_functions_label_implicit]
584for ( char * ch; labels( Alphabet ) )
585\end{lstlisting}
586
587
588% \subsection{Non-uniform Type}
589% TODO: Working in Progress, might need to change other sections. Conflict with the resolution right now.
590
591% \begin{lstlisting}
592% enum T( int, char * ) {
593%     a=42, b="Hello World"
594% };
595% \end{lstlisting}
596% The enum T declares two different types: int and char *. The enumerators of T hold values of one of the declared types.
597
598\subsection{Enumeration Inheritance}
599
600\begin{lstlisting}[label=lst:EnumInline]
601enum( char * ) Name { Jack = "Jack", Jill = "Jill" };
602enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
603\end{lstlisting}
604\lstinline{Inline} allows Enumeration Name2 to inherit enumerators from Name1 by containment, and a Name enumeration is a subtype of enumeration Name2. An enumeration instance of type Name can be used where an instance of Name2 is expected.
605\begin{lstlisting}[label=lst:EnumInline]
606Name Fred;
607void f( Name2 );
608f( Fred );
609\end{lstlisting}
610If enumeration A declares @inline B@ in its enumeration body, enumeration A is the "inlining enum" and enumeration B is the "inlined enum".
611
612An enumeration can inline at most one other enumeration. The inline declaration must be placed before the first enumerator of the inlining enum. The inlining enum has all the enumerators from the inlined enum, with the same labels, values, and position.
613\begin{lstlisting}[label=lst:EnumInline]
614enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
615// is equivalent to enum Name2 { Jack = "Jack", Jill="Jill", Sue = "Sue", Tom = "Tom" };
616\end{lstlisting}
617Name.Jack is equivalent to Name2.Jack. Their attributes are all identical. Opening both Name and Name2 in the same scope will not introduce ambiguity.
618\begin{lstlisting}[label=lst:EnumInline]
619with( Name, Name2 ) { Jack; } // Name.Jack and Name2.Jack are equivalent. No ambiguity
620\end{lstlisting}
621
622\section{Implementation}
623
624\subsection{Static Attribute Expression}
625\begin{lstlisting}[label=lst:static_attr]
626enum( char * ) Colour {
627    Red = "red", Blue = "blue", Green = "green" 
628};
629\end{lstlisting}
630An enumerator expression returns its enumerator value as a constant expression with no runtime cost. For example, @Colour.Red@ is equivalent to the constant expression "red", and \CFA finishes the expression evaluation before generating the corresponding C code. Applying a pseudo-function to a constant enumerator expression results in a constant expression as well. @value( Colour.Red )@, @position( Colour. Red )@, and @label( Colour.Red )@ are equivalent to constant expression with char * value "red", int value 0, and char * value "Red", respectively.
631
632\subsection{Runtime Attribute Expression and Weak Referenced Data}
633\begin{lstlisting}[label=lst:dynamic_attr]
634Colour c;
635...
636value( c ); // or c
637\end{lstlisting}
638An enumeration variable c is equivalent to an integer variable with the value of @position( c )@ In Example~\ref{lst:dynamic_attr}, the value of enumeration variable c is unknown at compile time. In this case, the pseudo-function calls are reduced to expression that returns the enumerator values at runtime.
639
640\CFA stores the variables and labels in const arrays to provide runtime lookup for enumeration information.
641
642\begin{lstlisting}[label=lst:attr_array]
643const char * Colour_labels [3] = { "Red", "Blue", "Green" };
644const char * Colour_values [3] = { "red", "blue", "green" };
645\end{lstlisting}
646The \CFA compiles transforms the attribute expressions into array access.
647\begin{lstlisting}[label=lst:attr_array_access]
648position( c ) // c; an integer
649value( c ); // Colour_values[c]
650label( c ); // Colour_labels[c]
651\end{lstlisting}
652
653To avoid unnecessary memory usage, the labels and values array are only generated as needed, and only generate once across all compilation units. By default, \CFA defers the declaration of the label and value arrays until an call to attribute function with a dynamic value. If an attribute function is never called on a dynamic value of an enumerator, the array will never be allocated. Once the arrays are created, all compilation units share a weak reference to the allocation array.
654
655\subsection{Enum Prelude}
656
657\begin{lstlisting}[label=lst:enum_func_dec]
658forall( T ) {
659    unsigned position( unsigned );
660    T value( unsigned );
661    char * label( unsigned );
662}
663\end{lstlisting}
664\CFA loads the declaration of enumeration function from the enum.hfa.
665
666\subsection{Internal Representation}
667
668The definition of an enumeration is represented by an internal type called @EnumDecl@. At the minimum, it stores all the information needed to construct the companion object. Therefore, an @EnumDecl@ can be represented as the following:
669\begin{lstlisting}[label=lst:EnumDecl]
670forall(T)
671class EnumDecl {
672    T* values;
673    char** label;
674};
675\end{lstlisting}
676
677The internal representation of an enumeration constant is @EnumInstType@.
678An @EnumInstType@ has a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
679\begin{lstlisting}[label=lst:EnumInstType]
680class EnumInstType {
681    EnumDecl enumDecl;
682    int position;
683};
684\end{lstlisting}
685In the later discussion, we will use @EnumDecl<T>@ to symbolize a @EnumDecl@ parameterized by type T, and @EnumInstType<T>@ is a declared instance of @EnumDecl<T>@.
686
687\begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_data]
688const T * const values;
689const char * label;
690int length;
691\end{lstlisting}
692Companion data are necessary information to represent an enumeration. They are stored as standalone pieces, rather than a structure. Those data will be loaded "on demand".
693Companion data are needed only if the according pseudo-functions are called. For example, the value of the enumeration Workday is loaded only if there is at least one compilation that has call $value(Workday)$. Once the values are loaded, all compilations share these values array to reduce memory usage.
694
695
696% \subsection{(Rework) Companion Object and Companion Function}
697
698% \begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
699% forall( T )
700% struct Companion {
701%       const T * const values;
702%         const char * label;
703%       int length;
704% };
705% \end{lstlisting}
706% \CFA generates companion objects, an instance of structure that encloses @necessary@ data to represent an enumeration. The size of the companion is unknown at the compilation time, and it "grows" in size to compensate for the @usage@.
707
708% The companion object is singleton across the compilation (investigation). 
709
710% \CFA generates the definition of companion functions.
711% Because \CFA implicitly stores an enumeration instance as its position, the companion function @position@ does nothing but return the position it is passed.
712% Companions function @value@ and @label@ return the array item at the given position of @values@ and @labels@, respectively.
713% \begin{lstlisting}[label=lst:companion_definition]
714% int position( Companion o, int pos ) { return pos; }
715% T value( Companion o, int pos ) { return o.values[ pos ]; }
716% char * label( Companion o, int pos ) { return o.labels[ pos ]; }
717% \end{lstlisting}
718% Notably, the @Companion@ structure definition, and all companion objects, are visible to users.
719% 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@
720% \begin{lstlisting}[label=lst:companion_definition_values_labels]
721% Colour.values; // read the Companion's values
722% values( Colour ); // same as Colour.values
723% \end{lstlisting}
724
725\subsection{Companion Traits (experimental)}
726Not sure its semantics yet, and it might replace a companion object.
727\begin{lstlisting}[label=lst:companion_trait]
728forall(T1) {
729    trait Companion(otype T2<otype T1>) {
730        T1 value((otype T2<otype T1> const &);
731        int position(otype T2<otype T1> const &);
732        char * label(otype T2<otype T1> const &);
733    }
734}
735\end{lstlisting}
736All enumerations implicitly implement the Companion trait, an interface to access attributes. The Companion can be a data type because it fulfills to requirements to have concrete instances, which are:
737
738\begin{enumerate}
739  \item The instance of enumeration has a single polymorphic type.
740  \item Each assertion should use the type once as a parameter.
741\end{enumerate}
742
743\begin{lstlisting}
744enum(int) Weekday {
745    Monday=10, Tuesday, ...
746};
747
748T value( enum Weekday<T> & this);
749int position( enum Weekday<T> & this )
750char * label( enum Weekday<T> & this )
751
752trait Companion obj = (enum(int)) Workday.Weekday;
753value(obj); // 10
754\end{lstlisting}
755The enumeration comes with default implementation to the Companion traits functions. The usage of Companion functions would make \CFA allocates and initializes the necessary companion arrays, and return the data at the position represented by the enumeration.
756(...)
757
758\subsection{User Define Enumeration Functions}
759
760Companion objects make extending features for \CFA enumeration easy.
761\begin{lstlisting}[label=lst:companion_user_definition]
762char * charastic_string( Companion o, int position ) { 
763        return sprintf( "Label: %s; Value: %s", label( o, position ), value( o, position) );
764}
765printf( charactic_string ( Color, 1 ) );
766>>> Label: Green; Value: G
767\end{lstlisting}
768Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.
769
770The \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.
771Therefore, a user can use the syntax with a user-defined enumeration function call:
772\begin{lstlisting}[label=lst:companion_user_definition]
773charactic_string( Color.Green ); // equivalent to charactic_string( Color, 1 )
774>>> Label: Green; Value: G
775\end{lstlisting}
776Similarly, the user can work with the enumeration type itself: (see section ref...)
777\begin{lstlisting}[ label=lst:companion_user_definition]
778void print_enumerators ( Companion o ) { 
779        for ( c : Companion o ) {
780                sout | label (c) | value( c ) ;
781        } 
782}
783print_enumerators( Colour );
784\end{lstlisting}
785
786
787\subsection{Declaration}
788
789The qualified enumeration syntax is dedicated to \CFA enumeration.
790\begin{lstlisting}[label=lst:range_functions]
791enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
792\end{lstlisting}
793A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
794During the $Validation$ pass, the compiler links the type declaration to the type's definition.
795It 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.
796If the declared type is not @AutoInitializable@, \CFA rejects the enumeration definition.
797Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section)
798
799\begin{lstlisting}[label=lst:init]
800struct T { ... };
801void ?{}( T & t, zero_t ) { ... };
802void ?{}( T & t, one_t ) { ... };
803T ?+?( T & lhs, T & rhs ) { ... };
804
805enum (T) Sample { 
806        Zero: 0 /* zero_t */,
807        One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
808};
809\end{lstlisting}
810Challenge: \\
811The value of an enumerator, or the initializer, requires @const_expr@.
812While 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.
813Might not be able to implement a \emph{correct} static check.
814
815\CFA $autogens$ a Companion object for the declared enumeration.
816\begin{lstlisting}[label=lst:companion]
817Companion( T ) Sample {
818        .values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
819        .labels: { "Zero", "One", "Two", "Three", ...},
820        .length: /* number of enumerators */
821};
822\end{lstlisting}
823\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
824But the result is computed at run time, and the compiler ensures the @values@ are not changed.
825
826\subsection{Qualified Expression}
827
828\CFA uses qualified expression to address the scoping of \CFA-enumeration.
829\begin{lstlisting}[label=lst:qualified_expression]
830aggregation_name.field;
831\end{lstlisting}
832The qualified expression is not dedicated to \CFA enumeration.
833It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
834When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
835\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
836If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.
837
838\subsection{\lstinline{with} Clause/Statement}
839Instead of qualifying an enumeration expression every time, the @with@ can be used to expose enumerators to the current scope, making them directly accessible.
840\begin{lstlisting}[label=lst:declaration]
841enum Color( char * ) { Red="R", Green="G", Blue="B" };
842enum Animal( int ) { Cat=10, Dog=20 };
843with ( Color, Animal ) {
844    char * red_string = Red; // value( Color.Red )
845    int cat = Cat; // value( Animal.Cat )
846}
847\end{lstlisting}
848The \lstinline{with} might introduce ambiguity to a scope. Consider the example:
849\begin{lstlisting}[label=lst:declaration]
850enum Color( char * ) { Red="R", Green="G", Blue="B" };
851enum RGB( int ) { Red=0, Green=1, Blue=2 };
852with ( Color, RGB ) {
853    // int red = Red;
854}
855\end{lstlisting}
856\CFA will not try to resolve the expression with ambiguity. It would report an error. In this case, it is necessary to qualify @Red@ even inside of the \lstinline{with} clause.
857
858\subsection{Instance Declaration}
859
860
861\begin{lstlisting}[label=lst:var_declaration]
862enum Sample s1;
863\end{lstlisting}
864
865The declaration \CFA-enumeration variable has the same syntax as the C-enumeration. Internally, such a variable will be represented as an EnumInstType.
866
867
868\end{document}
869
870% Local Variables: %
871% tab-width: 4 %
872% compile-command: "pdflatex enum.tex" %
873% End: %
Note: See TracBrowser for help on using the repository browser.