source: doc/proposals/enum.tex @ 21ce2c7

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

Change the unification scheme

  • Property mode set to 100644
File size: 38.3 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 Characteristic}
208
209\subsection{Enumerator Storage}
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\section{Unification}
234
235\subsection{Enumeration as Value}
236\label{section:enumeration_as_value}
237An \CFA enumeration with base type T can be used seamlessly as T, without explicitly calling the pseudo-function value.
238\begin{lstlisting}[label=lst:implicit_conversion]
239char * green_value = Colour.Green; // "G"
240// Is equivalent to
241// char * green_value = value( Color.Green ); "G"
242\end{lstlisting}
243
244\subsection{Unification Distance}
245\begin{lstlisting}[label=lst:unification_distance_example]
246T_2 Foo(T1);
247\end{lstlisting}
248The @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@.
249
250@path(A, B)@ is a compiler concept that returns one of the following:
251\begin{itemize}
252    \item Zero or 0, if and only if $A == B$.
253    \item Safe, if B can be used as A without losing its precision, or B is a subtype of A.
254    \item Unsafe, if B loses its precision when used as A, or A is a subtype of B.
255    \item Infinite, if B cannot be used as A. A is not a subtype of B and B is not a subtype of A.
256\end{itemize}
257
258For example, @path(int, int)==Zero@, @path(int, char)==Safe@, @path(int, double)==Unsafe@, @path(int, struct S)@ is @Infinite@ for @struct S{}@.
259@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$$.
260
261(Skip over the distance matrix here because it is mostly irrelevant for enumeration discussion. In the actual implementation, distance( E, T ) is 1.)
262
263The arithmetic of distance is the following:
264\begin{itemize}
265    \item $Zero + v= v$, for some value v.
266    \item $Safe * k <  Unsafe$, for finite k.
267    \item $Unsafe * k < Infinite$, for finite k.
268    \item $Infinite + v = Infinite$, for some value v.
269\end{itemize}
270
271For @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@.
272
273
274\subsection{Variable Overloading and Parameter Unification}
275\CFA allows variable names to be overloaded. It is possible to overload a variable that has type T and an enumeration with type T.
276\begin{lstlisting}[label=lst:variable_overload]
277char * green = "Green";
278Colour green = Colour.Green; // "G"
279
280void bar(char * s) { return s; }
281void foo(Colour c) { return value( c ); }
282
283foo( green ); // "G"
284bar( green ); // "Green"
285\end{lstlisting}
286\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 *@.
287
288\subsection{Function Overloading}
289Similarly, functions can be overloaded with different signatures. \CFA picks the correct function entity based on the distance between parameter types and the arguments.
290\begin{lstlisting}[label=lst:function_overload]
291Colour green = Colour.Green;
292void foo(Colour c) { sout | "It is an enum"; } // First foo
293void foo(char * s) { sout | "It is a string"; } // Second foo
294foo( green ); // "It is an enum"
295\end{lstlisting}
296Because @distance(Colour, Colour)@ is @Zero@ and @distance(char *, Colour)@ is @Safe@, \CFA determines the @foo( green )@ is a call to the first foo.
297
298\subsection{Attributes Functions}
299The 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@.
300
301\begin{lstlisting}[label=lst:declaration_code]
302int s1;
303\end{lstlisting}
304The 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
305
306% \subsection{Unification and Resolution (this implementation will probably not be used, safe as reference for now)}
307
308% \begin{lstlisting}
309% enum Colour( char * ) { Red = "R", Green = "G", Blue = "B"  };
310% \end{lstlisting}
311% The @EnumInstType@ is convertible to other types.
312% A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
313% The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context.
314
315% \begin{lstlisting}[caption={Null Context}, label=lst:null_context]
316% {
317%       Colour.Green;
318% }
319% \end{lstlisting}
320% In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
321% In this case, any of the attributes is resolvable.
322% According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
323% The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
324% When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
325% \begin{lstlisting}[caption={Null Context Generated Code}, label=lst:null_context]
326% {
327%       "G";
328% }
329% \end{lstlisting}
330% \begin{lstlisting}[caption={int Context}, label=lst:int_context]
331% {
332%       int g = Colour.Green;
333% }
334% \end{lstlisting}
335% The assignment expression gives a context for the EnumInstType resolution.
336% The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
337% The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
338% In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
339% $$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
340% \begin{lstlisting}[label=lst:attr_resolution_1]
341% {
342%       Unify( int, char * ); // unify with the type of value
343%       Unify( int, int ); // unify with the type of position
344%       Unify( int, char * ); // unify with the type of label
345% }
346% \end{lstlisting}
347% \begin{lstlisting}[label=lst:attr_resolution_precedence]
348% {
349%       Unification( T1, EnumInstType<T2> ) {
350%               if ( Unify( T1, T2 ) ) return T2;
351%               if ( Unify( T1, int ) ) return int;
352%               if ( Unify( T1, char * ) ) return char *;
353%               Error: Cannot Unify T1 with EnumInstType<T2>;
354%       }
355% }
356% \end{lstlisting}
357% After the unification, @EnumInstType@ is replaced by its attributes.
358
359% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
360% {
361%       T2 foo ( T1 ); // function take variable with T1 as a parameter
362%       foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
363%       >>>> Unification( T1, EnumInstType<T3> )
364% }
365% \end{lstlisting}
366% % The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType.
367% Backward conversion:
368% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
369% {
370%       enum Colour colour = 1;
371% }
372% \end{lstlisting}
373
374% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
375% {
376%    Unification( EnumInstType<Colour>, int ) >>> label
377% }
378% \end{lstlisting}
379% @int@ can be unified with the label of Colour.
380% @5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into
381% \begin{lstlisting}
382% {
383%    enum Colour colour = Colour.Green;
384% }
385% \end{lstlisting}
386% Steps:
387% \begin{enumerate}
388% \item
389% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
390% \item
391% @unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
392% \item
393% return the enumeration constant at position 1
394% \end{enumerate}
395% \begin{lstlisting}
396% {
397%       enum T (int) { ... } // Declaration
398%       enum T t = 1;
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 )@: @value( EnumInstType< Colour > )@
407% \item
408% return the FIRST enumeration constant that has the value 1, by searching through the values array
409% \end{enumerate}
410% 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
411
412% \subsection{Casting}
413% Casting an EnumInstType to some other type T works similarly to unify the EnumInstType with T. For example:
414% \begin{lstlisting}
415% enum( int ) Foo { A = 10, B = 100, C = 1000 };
416% (int) Foo.A;
417% \end{lstlisting}
418% 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.
419
420% \subsection{Value Conversion}
421% 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.
422
423% \begin{lstlisting}
424% Foo a; // int a;
425% int j = a;
426% char * s = a;
427% \end{lstlisting}
428% 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
429% \begin{lstlisting}
430% int j = value( Foo, a )
431% \end{lstlisting}
432% Similarly, the generated code for the third line is
433% \begin{lstlisting}
434% char * j = label( Foo, a )
435% \end{lstlisting}
436
437
438\section{Enumerator Initialization}
439An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
440
441\subsection{C Enumeration Rule}
442A 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$.
443
444\subsection{Auto Initializable}
445\label{s:AutoInitializable}
446
447
448\CFA enumerations have the same rule in enumeration constant initialization.
449However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA.
450
451Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@:
452\begin{lstlisting}
453forall(T)
454trait AutoInitializable {
455        void ?()( T & t, zero_t );
456        S ?++( T & t);
457};
458\end{lstlisting}
459An example of a user-defined @AutoInitializable@ is:
460\begin{lstlisting}[label=lst:sample_auto_Initializable]
461struct Odd { int i; };
462void ?()( Odd & t, zero_t ) { t.i = 1; };
463Odd ?++( Odd t1 ) { return Odd( t1.i + 2); };
464\end{lstlisting}
465When the type of an enumeration is @AutoInitializable@, implicit initialization is available.
466\begin{lstlisting}[label=lst:sample_auto_Initializable_usage]
467enum AutoInitUsage(Odd) {
468        A, B, C = 7, D
469};
470\end{lstlisting}
471In 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.
472@B@ and @D@ have the values of their $predecessor++$, where @one_t@ has the value 2.
473Therefore, the enumeration is initialized as follows:
474\begin{lstlisting}[label=lst:sample_auto_Initializable_usage_gen]
475enum AutoInitUsage(Odd) {
476        A = 1, B = 3, C = 7, D = 9
477};
478\end{lstlisting}
479Note that there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@.
480
481In \CFA, character, integral, float, and imaginary types are all @AutoInitialiable@.
482\begin{lstlisting}[label=lst:letter]
483enum Alphabet( int ) {
484        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,
485        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
486};
487print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.z );
488>>> F, o, z
489\end{lstlisting}
490\section{Enumeration Features}
491\subsection{Iteration and Range}
492
493It is convenient to iterate over a \CFA enumeration value, e.g.:
494\begin{lstlisting}[label=lst:range_functions]
495for ( Alphabet alph; Alphabet ) { sout | alph; }
496>>> A B C ... D
497\end{lstlisting}
498The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
499@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
500
501\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
502\begin{lstlisting}[label=lst:range_functions]
503for ( Alphabet alph ) { sout | alph; }
504>>> A B C ... D
505\end{lstlisting}
506
507The 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.
508
509\textbullet\ H is implicit up-to exclusive range [0, H).
510\begin{lstlisting}[label=lst:range_function_1]
511for ( alph; Alphabet.D ) { sout | alph; }
512>>> A B C
513\end{lstlisting}
514
515\textbullet\ ~= H is implicit up-to inclusive range [0,H].
516\begin{lstlisting}[label=lst:range_function_2]
517for ( alph; ~= Alphabet.D ) { sout | alph; }
518>>> A B C D
519\end{lstlisting}
520
521\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
522\begin{lstlisting}[label=lst:range_function_3]
523for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
524// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
525>>> B C
526\end{lstlisting}
527
528\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
529\begin{lstlisting}[label=lst:range_function_4]
530for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
531>>> B C D
532\end{lstlisting}
533
534\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
535\begin{lstlisting}[label=lst:range_function_5]
536for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
537>>> D C
538\end{lstlisting}
539
540\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
541\begin{lstlisting}[label=lst:range_function_6]
542for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
543>>> D C B
544\end{lstlisting}
545
546A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
547\begin{lstlisting}[label=lst:range_function_stepping]
548enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
549for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
550>>> 10 12 14 16 18
551for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
552>>> 10 11 12 13 14 15 16 17 18
553\end{lstlisting}
554The 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
555\begin{lstlisting}[label=lst:range_function_stepping_converted]
556for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
557>>> 10 11 12 13 14 15 16 17 18
558\end{lstlisting}
559
560% \PAB{Explain what each loop does.}
561
562It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
563\begin{lstlisting}[label=lst:range_functions_label_implicit]
564for ( char * alph; Alphabet )
565\end{lstlisting}
566This 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.
567If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
568\begin{lstlisting}[label=lst:range_functions_label_implicit]
569for ( char * ch; labels( Alphabet ) )
570\end{lstlisting}
571
572
573% \subsection{Non-uniform Type}
574% TODO: Working in Progress, might need to change other sections. Conflict with the resolution right now.
575
576% \begin{lstlisting}
577% enum T( int, char * ) {
578%     a=42, b="Hello World"
579% };
580% \end{lstlisting}
581% The enum T declares two different types: int and char *. The enumerators of T hold values of one of the declared types.
582
583\subsection{Enumeration Inheritance}
584
585\begin{lstlisting}[label=lst:EnumInline]
586enum( char * ) Name { Jack = "Jack", Jill = "Jill" };
587enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
588\end{lstlisting}
589\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.
590\begin{lstlisting}[label=lst:EnumInline]
591Name Fred;
592void f( Name2 );
593f( Fred );
594\end{lstlisting}
595If enumeration A declares @inline B@ in its enumeration body, enumeration A is the "inlining enum" and enumeration B is the "inlined enum".
596
597An 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.
598\begin{lstlisting}[label=lst:EnumInline]
599enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
600// is equivalent to enum Name2 { Jack = "Jack", Jill="Jill", Sue = "Sue", Tom = "Tom" };
601\end{lstlisting}
602Name.Jack is equivalent to Name2.Jack. Their attributes are all identical. Opening both Name and Name2 in the same scope will not introduce ambiguity.
603\begin{lstlisting}[label=lst:EnumInline]
604with( Name, Name2 ) { Jack; } // Name.Jack and Name2.Jack are equivalent. No ambiguity
605\end{lstlisting}
606
607\section{Implementation}
608
609\subsection{Compiler Representation (Reworking)}
610The 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:
611\begin{lstlisting}[label=lst:EnumDecl]
612forall(T)
613class EnumDecl {
614    T* values;
615    char** label;
616};
617\end{lstlisting}
618
619The internal representation of an enumeration constant is @EnumInstType@.
620An @EnumInstType@ has a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
621\begin{lstlisting}[label=lst:EnumInstType]
622class EnumInstType {
623    EnumDecl enumDecl;
624    int position;
625};
626\end{lstlisting}
627In 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>@.
628
629\begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_data]
630const T * const values;
631const char * label;
632int length;
633\end{lstlisting}
634Companion 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".
635Companion 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.
636
637
638\subsection{(Rework) Companion Object and Companion Function}
639
640\begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
641forall( T )
642struct Companion {
643        const T * const values;
644        const char * label;
645        int length;
646};
647\end{lstlisting}
648\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@.
649
650The companion object is singleton across the compilation (investigation). 
651
652\CFA generates the definition of companion functions.
653Because \CFA implicitly stores an enumeration instance as its position, the companion function @position@ does nothing but return the position it is passed.
654Companions function @value@ and @label@ return the array item at the given position of @values@ and @labels@, respectively.
655\begin{lstlisting}[label=lst:companion_definition]
656int position( Companion o, int pos ) { return pos; }
657T value( Companion o, int pos ) { return o.values[ pos ]; }
658char * label( Companion o, int pos ) { return o.labels[ pos ]; }
659\end{lstlisting}
660Notably, the @Companion@ structure definition, and all companion objects, are visible to users.
661A 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@
662\begin{lstlisting}[label=lst:companion_definition_values_labels]
663Colour.values; // read the Companion's values
664values( Colour ); // same as Colour.values
665\end{lstlisting}
666
667\subsection{Companion Traits (experimental)}
668Not sure its semantics yet, and it might replace a companion object.
669\begin{lstlisting}[label=lst:companion_trait]
670forall(T1) {
671    trait Companion(otype T2<otype T1>) {
672        T1 value((otype T2<otype T1> const &);
673        int position(otype T2<otype T1> const &);
674        char * label(otype T2<otype T1> const &);
675    }
676}
677\end{lstlisting}
678All 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:
679
680\begin{enumerate}
681  \item The instance of enumeration has a single polymorphic type.
682  \item Each assertion should use the type once as a parameter.
683\end{enumerate}
684
685\begin{lstlisting}
686enum(int) Weekday {
687    Monday=10, Tuesday, ...
688};
689
690T value( enum Weekday<T> & this);
691int position( enum Weekday<T> & this )
692char * label( enum Weekday<T> & this )
693
694trait Companion obj = (enum(int)) Workday.Weekday;
695value(obj); // 10
696\end{lstlisting}
697The 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.
698(...)
699
700\subsection{User Define Enumeration Functions}
701
702Companion objects make extending features for \CFA enumeration easy.
703\begin{lstlisting}[label=lst:companion_user_definition]
704char * charastic_string( Companion o, int position ) { 
705        return sprintf( "Label: %s; Value: %s", label( o, position ), value( o, position) );
706}
707printf( charactic_string ( Color, 1 ) );
708>>> Label: Green; Value: G
709\end{lstlisting}
710Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.
711
712The \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.
713Therefore, a user can use the syntax with a user-defined enumeration function call:
714\begin{lstlisting}[label=lst:companion_user_definition]
715charactic_string( Color.Green ); // equivalent to charactic_string( Color, 1 )
716>>> Label: Green; Value: G
717\end{lstlisting}
718Similarly, the user can work with the enumeration type itself: (see section ref...)
719\begin{lstlisting}[ label=lst:companion_user_definition]
720void print_enumerators ( Companion o ) { 
721        for ( c : Companion o ) {
722                sout | label (c) | value( c ) ;
723        } 
724}
725print_enumerators( Colour );
726\end{lstlisting}
727
728
729\subsection{Declaration}
730
731The qualified enumeration syntax is dedicated to \CFA enumeration.
732\begin{lstlisting}[label=lst:range_functions]
733enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
734\end{lstlisting}
735A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
736During the $Validation$ pass, the compiler links the type declaration to the type's definition.
737It 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.
738If the declared type is not @AutoInitializable@, \CFA rejects the enumeration definition.
739Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section)
740
741\begin{lstlisting}[label=lst:init]
742struct T { ... };
743void ?{}( T & t, zero_t ) { ... };
744void ?{}( T & t, one_t ) { ... };
745T ?+?( T & lhs, T & rhs ) { ... };
746
747enum (T) Sample { 
748        Zero: 0 /* zero_t */,
749        One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
750};
751\end{lstlisting}
752Challenge: \\
753The value of an enumerator, or the initializer, requires @const_expr@.
754While 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.
755Might not be able to implement a \emph{correct} static check.
756
757\CFA $autogens$ a Companion object for the declared enumeration.
758\begin{lstlisting}[label=lst:companion]
759Companion( T ) Sample {
760        .values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
761        .labels: { "Zero", "One", "Two", "Three", ...},
762        .length: /* number of enumerators */
763};
764\end{lstlisting}
765\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
766But the result is computed at run time, and the compiler ensures the @values@ are not changed.
767
768\subsection{Qualified Expression}
769
770\CFA uses qualified expression to address the scoping of \CFA-enumeration.
771\begin{lstlisting}[label=lst:qualified_expression]
772aggregation_name.field;
773\end{lstlisting}
774The qualified expression is not dedicated to \CFA enumeration.
775It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
776When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
777\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
778If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.
779
780\subsection{\lstinline{with} Clause/Statement}
781Instead of qualifying an enumeration expression every time, the @with@ can be used to expose enumerators to the current scope, making them directly accessible.
782\begin{lstlisting}[label=lst:declaration]
783enum Color( char * ) { Red="R", Green="G", Blue="B" };
784enum Animal( int ) { Cat=10, Dog=20 };
785with ( Color, Animal ) {
786    char * red_string = Red; // value( Color.Red )
787    int cat = Cat; // value( Animal.Cat )
788}
789\end{lstlisting}
790The \lstinline{with} might introduce ambiguity to a scope. Consider the example:
791\begin{lstlisting}[label=lst:declaration]
792enum Color( char * ) { Red="R", Green="G", Blue="B" };
793enum RGB( int ) { Red=0, Green=1, Blue=2 };
794with ( Color, RGB ) {
795    // int red = Red;
796}
797\end{lstlisting}
798\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.
799
800\subsection{Instance Declaration}
801
802
803\begin{lstlisting}[label=lst:var_declaration]
804enum Sample s1;
805\end{lstlisting}
806
807The declaration \CFA-enumeration variable has the same syntax as the C-enumeration. Internally, such a variable will be represented as an EnumInstType.
808
809
810\end{document}
811
812% Local Variables: %
813% tab-width: 4 %
814% compile-command: "pdflatex enum.tex" %
815% End: %
Note: See TracBrowser for help on using the repository browser.