source: doc/proposals/enum.tex@ a55ebcc

Last change on this file since a55ebcc was 2989d6f, checked in by Peter A. Buhr <pabuhr@…>, 20 months ago

started some related work

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