source: doc/proposals/enum.tex@ e11cdc0

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

add more material

  • Property mode set to 100644
File size: 62.6 KB
RevLine 
[0030b508]1\documentclass[12pt]{article}
2\usepackage{fullpage,times}
3\usepackage{pslatex} % reduce size of san serif font
[85034ed]4\usepackage{xcolor}
5\usepackage{listings}
[0030b508]6%\usepackage{array}
7\usepackage{graphics}
8\usepackage{xspace}
[2989d6f]9\usepackage{relsize} % must be after change to small or selects old size
[dd1ebb1]10\usepackage{calc} % latex arithmetic
[0030b508]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}}
[66d92e3]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}
[dd1ebb1]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}
[0030b508]41\makeatother
42
[25f2798]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
[0030b508]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
[66d92e3]65\newcommand{\CCIcon}{\textrm{C}\kern-.1em\hbox{+\kern-.25em+}} % C++ icon
66\newcommand{\CC}[1][]{\protect\CCIcon{#1}\xspace} % C++ symbolic name
[2989d6f]67\newcommand{\Csharp}{C\raisebox{-0.7ex}{\relsize{2}$^\sharp$}\xspace} % C# symbolic name
[0030b508]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}
[85034ed]74
75\lstdefinestyle{CStyle}{
[dd1ebb1]76% backgroundcolor=\color{backgroundColour},
[0030b508]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,
[dd1ebb1]84 breakatwhitespace=false,
85% breaklines=true,
86 captionpos=b,
87 keepspaces=true,
[66d92e3]88 escapechar=\$, % LaTeX escape in CFA code
[dd1ebb1]89% numbers=left,
90% numbersep=5pt,
[0030b508]91% numberstyle=\tiny\color{mGray},
[dd1ebb1]92% showspaces=false,
[85034ed]93 showstringspaces=false,
[dd1ebb1]94% showtabs=false,
[0030b508]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
[85034ed]101}
[0030b508]102\lstset{style=CStyle,moredelim=**[is][\color{red}]{@}{@}}
103\lstMakeShortInline@ % single-character for \lstinline
[85034ed]104
105\begin{document}
106
[0030b508]107\title{\vspace*{-0.5in}Enumeration in \CFA}
[85034ed]108\author{Jiada Liang}
109
[0030b508]110\maketitle
[85034ed]111
112\begin{abstract}
[dd1ebb1]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@.
[2989d6f]114C restrict an enumeration type to the integral type @signed int@, which \CC support , meaning enumeration names bind to integer constants.
[dd1ebb1]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.
[85034ed]117\end{abstract}
118
[e11cdc0]119\section{Introduction}
[dd1ebb1]120
121Naming values is a common practice in mathematics and engineering, e.g., $\pi$, $\tau$ (2$\pi$), $\phi$ (golden ratio), MHz (1E6), etc.
[e11cdc0]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), specific times (noon, New Years).
[bd67442]123Many programming languages capture this important software-engineering capability through a mechanism called an \newterm{enumeration}.
[dd1ebb1]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
[bd67442]127Specifically, an enumerated type restricts its values to a fixed set of named constants.
[e11cdc0]128While 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., these values are not named, other than the programming-language supplied constants.
[dd1ebb1]129
[e11cdc0]130Fundamentally, all enumeration systems have an \newterm{enumeration} type with its associated \newterm{enumerator} constants.
131These components have three universal attributes, \newterm{position}, \newterm{label}, and \newterm{value}, as shown by this representative enumeration, where position and value can be different.
[0030b508]132\begin{cquote}
[66d92e3]133\small\sf\setlength{\tabcolsep}{3pt}
[0030b508]134\begin{tabular}{rccccccccccc}
[e11cdc0]135\it\color{red}enumeration & \multicolumn{7}{c}{\it\color{red}enumerators} \\
136$\downarrow$\hspace*{25pt} & \multicolumn{7}{c}{$\downarrow$} \\
137@enum@ Weekday \{ & Monday, & Tuesday, & Wednesday, & Thursday,& Friday, & Saturday, & Sunday \}; \\
138\it\color{red}position & 0 & 1 & 2 & 3 & 4 & 5 & 6 \\
139\it\color{red}label & Monday & Tuesday & Wednesday & Thursday & Friday & Saturday & Sunday \\
140\it\color{red}value & 0 & 1 & 2 & 3 & 4 & 5 & 6
[0030b508]141\end{tabular}
142\end{cquote}
[e11cdc0]143Here, the \newterm{enumeration} @Weekday@ defines the ordered \newterm{enumerator}s @Monday@, @Tuesday@, @Wednesday@, @Thursday@, @Friday@, @Saturday@ and @Sunday@.
144By convention, the successor of @Tuesday@ is @Monday@ and the predecessor of @Tuesday@ is @Wednesday@, independent of the associated enumerator constant values.
145Because an enumerator is a constant, it cannot appear in a mutable context, e.g. @Mon = Sun@ is meaningless, and an enumerator has no address, it is an \newterm{rvalue}\footnote{
146The term rvalue defines an expression that can only appear on the right-hand side of an assignment.}.
147
148
149\section{C-Style Enum}
150
151The C-Style enumeration has the following syntax and semantics.
152\begin{lstlisting}
153enum Weekday { Monday, Tuesday, Wednesday, Thursday@ = 10@, Friday, Saturday, Sunday };
154\end{lstlisting}
155Enumerators without an explicitly designated constant value are \newterm{auto-initialized} by the compiler: from left to right, starting at zero or the next explicitly initialized constant, incrementing by @1@.
156For example, @Monday@ to @Wednesday@ are implicitly assigned with constants @0@--@2@, @Thursday@ is explicitly set to constant @10@, and @Friday@ to @Sunday@ are implicitly assigned with constants @11@--@13@.
157Initialization may occur in any order.
158\begin{lstlisting}
159enum Weekday { Thursday@ = 10@, Friday, Saturday, Sunday, Monday@ = 0@, Tuesday, Wednesday };
160\end{lstlisting}
161Note, the comma in the enumerator list can be a terminator or a separator, allowing the list to end with a dangling comma.
162\begin{lstlisting}
163enum Weekday {
164 Thursday = 10, Friday, Saturday, Sunday,
165 Monday = 0, Tuesday, Wednesday@,@ // terminating comma
166};
167\end{lstlisting}
168This feature allow enumerator lines to be interchanged without moving a comma.\footnote{
169A terminating comma appears in other C syntax, e.g., the initializer list.}
170Finally, C enumerators are \newterm{unscoped}, i.e., enumerators declared inside of an @enum@ are visible (projected) in the enclosing scope of the @enum@ type.
[0030b508]171
[bd67442]172In theory, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerated values.
[e11cdc0]173In practice, since integral constants are used, which have type @int@ (unless qualified with a size suffix), C uses @int@ as the underlying type for enumeration variables.
174Finally, there is an implicit bidirectional conversion between an enumeration and integral types.
[0030b508]175\begin{lstlisting}[label=lst:enum_scope]
176{
[e11cdc0]177 enum Weekday { /* as above */ }; $\C{// enumerators implicitly projected into local scope}$
[bd67442]178 Weekday weekday = Monday; $\C{// weekday == 0}$
[dd1ebb1]179 weekday = Friday; $\C{// weekday == 11}$
[e11cdc0]180 int i = Sunday; $\C{// implicit conversion to int, i == 13}$
[bd67442]181 weekday = 10000; $\C{// UNDEFINED! implicit conversion to Weekday}$
[0030b508]182}
[dd1ebb1]183int j = Wednesday; $\C{// ERROR! Wednesday is not declared in this scope}$
[0030b508]184\end{lstlisting}
[bd67442]185The implicit conversion from @int@ to an enumeration type is an unnecessary source of error.
[85034ed]186
[e11cdc0]187It is common for C programmers to ``believe'' there are 3 equivalent forms of constant enumeration.
188\begin{lstlisting}[label=lst:enum_scope]
189#define Monday 0
190static const int Monday = 0;
191enum { Monday };
192\end{lstlisting}
193For @#define@, the programmer has to play compiler and explicitly manage the enumeration values;
194furthermore, these are independent constants outside of any language type mechanism.
195The same explicit management is true for @const@ declarations, and the @const@ variable cannot appear in constant-expression locations, like @case@ labels, array dimensions,\footnote{
196C allows variable-length array-declarations (VLA), so this case does work, but it fails in \CC, which does not support VLAs, unless it is \lstinline{g++}.} and immediate operands of assembler instructions.
197Only the @enum@ form is managed by the compiler, is part of the language type-system, and works in all C constant-expression locations.
198
199
[0030b508]200\section{\CFA-Style Enum}
[85034ed]201
[dd1ebb1]202\CFA supports C-Style enumeration using the same syntax and semantics for backwards compatibility.
203\CFA also extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.
204
205
[e11cdc0]206\subsection{Enumerator Name Resolution}
207\label{s:EnumeratorNameResolution}
[bd67442]208
[e11cdc0]209In C, unscoping of enumerators presents a \newterm{naming problem} when multiple enumeration types appear in the same scope with duplicate enumerator names.
210There is no mechanism in C to resolve these naming conflicts other than renaming of one of the duplicates, which may not be possible.
211
212The \CFA type-system allows extensive overloading, including enumerators.
213Furthermore, \CFA uses the left-hand of assignment in type resolution to pinpoint the best overloaded name.
214Finally, qualification is provided to disambiguate any ambiguous situations.
[bd67442]215\begin{lstlisting}
[e11cdc0]216enum C1 { First, Second, Third, Fourth };
217enum C2 { @Fourth@, @Third@, @Second@, @First@ };
218C1 p() { return Third; } $\C{// correctly resolved duplicate names}$
219C2 p() { return Fourth; }
220void foo() {
221 C1 e1 = First; C2 e2 = First;
222 e1 = Second; e2 = Second;
223 e1 = p(); e2 = p();
224 e1 = @C1.@First + @C1.@First; $\C{// ambiguous without qualification (and dangerous)}$
225}
[bd67442]226\end{lstlisting}
[e11cdc0]227\CFA overloading allows programmers to use the most meaningful names with little fear of unresolvable clashes from included files, which can always be corrected.
228
229
230\subsection{Enumerator Scoping}
231
232An enumeration can be scoped, so the enumerator constants are not projected into the enclosing scope, using @'!'@.
[bd67442]233\begin{lstlisting}
[e11cdc0]234enum Weekday @!@ { /* as above */ };
235enum( char * ) Names @!@ { /* as above */ };
[bab2917]236\end{lstlisting}
[e11cdc0]237Now the enumerators must be qualified with the associated enumeration.
238\begin{lstlisting}
239Weekday weekday = @Weekday@.Monday;
240Names names = @Names.@Fred;
241names = @Names.@Jane;
242\end{lstlisting}
243It is possible to toggle back to unscoping using the \CFA @with@ clause/statement.
244\begin{lstlisting}
245Weekday weekday;
246with ( @Weekday@, @Names@ ) { $\C{// type names}$
247 Names names = @Fred@;
248 names = @Jane@;
249 weekday = Saturday;
250}
251\end{lstlisting}
252As in section~\ref{s:EnumeratorNameResolution}, opening multiple unscoped enumerations can result in duplicate enumeration names, but \CFA type resolution and falling back to explicit qualification handles ambiguities.
253
254
255\subsection{Enumerator Typing}
256
257\CFA extends the enumeration declaration by parameterizing with a type (like a generic type), allowing enumerators to be assigned any values from the declared type.
258Figure~\ref{f:EumeratorTyping} shows a series of examples illustrating that all \CFA types can be use with an enumeration and each type's constants used to set the enumerator constants.
259Note, the synonyms @Liz@ and @Beth@ in the last declaration.
[0030b508]260
[bd67442]261% \begin{lstlisting}[label=lst:color]
262% struct S { int i, j; };
263% enum( S ) s { A = { 3, 4 }, B = { 7, 8 } };
264% enum( @char@ ) Currency { Dollar = '$\textdollar$', Euro = '$\texteuro$', Pound = '$\textsterling$' };
265% enum( @double@ ) Planet { Venus = 4.87, Earth = 5.97, Mars = 0.642 }; // mass
266% enum( @char *@ ) Colour { Red = "red", Green = "green", Blue = "blue" };
267% enum( @Currency@ ) Europe { Euro = '$\texteuro$', Pound = '$\textsterling$' }; // intersection
268% \end{lstlisting}
269
270\begin{figure}
271\begin{lstlisting}
272// integral
273 enum( @char@ ) Currency { Dollar = '$\textdollar$', Euro = '$\texteuro$', Pound = '$\textsterling$' };
274 enum( @signed char@ ) srgb { Red = -1, Green = 0, Blue = 1 };
275 enum( @long long int@ ) BigNum { X = 123_456_789_012_345, Y = 345_012_789_456_123 };
276// non-integral
277 enum( @double@ ) Math { PI_2 = 1.570796, PI = 3.141597, E = 2.718282 };
278 enum( @_Complex@ ) Plane { X = 1.5+3.4i, Y = 7+3i, Z = 0+0.5i };
279// pointer
[e11cdc0]280 enum( @char *@ ) Names { Fred = "FRED", Mary = "MARY", Jane = "JANE" };
[bd67442]281 int i, j, k;
282 enum( @int *@ ) ptr { I = &i, J = &j, K = &k };
283 enum( @int &@ ) ref { I = i, J = j, K = k };
284// tuple
[e11cdc0]285 enum( @[int, int]@ ) { T = [ 1, 2 ] }; $\C{// new \CFA type}$
[bd67442]286// function
287 void f() {...} void g() {...}
288 enum( @void (*)()@ ) funs { F = f, G = g };
289// aggregate
290 struct Person { char * name; int age, height; };
[e11cdc0]291@***@enum( @Person@ ) friends { @Liz@ = { "ELIZABETH", 22, 170 }, @Beth@ = Liz, Jon = { "JONATHAN", 35, 190 } };
[bd67442]292\end{lstlisting}
293\caption{Enumerator Typing}
294\label{f:EumeratorTyping}
295\end{figure}
296
[e11cdc0]297Typed enumerations deals with the \emph{harmonizing} problem between an enumeration and any companion data.
298The following example is from the \CFA compiler, written in \CC.
299\begin{lstlisting}
300enum integral_types { chr, schar, uschar, sshort, ushort, sint, usint, ..., NO_OF_ITYPES };
301char * integral_names[NO_OF_ITYPES] = {
302 "char", "signed char", "unsigned char",
303 "signed short int", "unsigned short int",
304 "signed int", "unsigned int",
305 ...
306};
307\end{lstlisting}
308The \emph{harmonizing} problem occurs because the enumeration declaration is in one header file and the names are declared in another translation unit.
309It is up to the programmer to ensure changes made in one location are harmonized with the other location (by identifying this requirement within a comment).
310The typed enumeration largely solves this problem by combining and managing the two data types.
311\begin{lstlisting}
312enum( char * ) integral_types {
313 chr = "char", schar = "signed char", uschar = "unsigned char",
314 sshort = "signed short int", ushort = "unsigned short int",
315 sint = "signed int", usint = "unsigned int",
316 ...
317};
318\end{lstlisting}
319
[bd67442]320\subsection{Pure Enumerators}
321
322An empty type, @enum()@, implies the enumerators are pure symbols without values;
323hence, there is no default conversion to @int@.
324
325\begin{lstlisting}
326enum() Mode { O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC, O_APPEND };
[e11cdc0]327@***@Mode iomode = O_RDONLY;
[bd67442]328int i = iomode; $\C{\color{red}// disallowed}$
329\end{lstlisting}
330
331\subsection{Enumerator Subset}
332
[e11cdc0]333If follows from enumerator typing that the enumerator type can be another enumerator.
[bd67442]334\begin{lstlisting}
335enum( char ) Letter { A = 'A', B = 'B', C = 'C', ..., Z = 'Z' };
[e11cdc0]336enum( @Letter@ ) Greek { Alph = A, Beta = B, ..., Zeta = Z }; // alphabet intersection
[bd67442]337\end{lstlisting}
338Enumeration @Greek@ may have more or less enumerators than @Letter@, but the enumerator values must be from @Letter@.
339Therefore, @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@.
[e11cdc0]340\begin{lstlisting}
341Letter letter = A;
342@***@Greak greek = Beta;
343letter = Beta; $\C{// allowed, letter == B}$
344greek = A; $\C{\color{red}// disallowed}$
345\end{lstlisting}
346
[bd67442]347
348\subsection{Enumeration Inheritance}
349
350\CFA Plan-9 inheritance may be used with enumerations.
351\begin{lstlisting}
[e11cdc0]352enum( char * ) Names { /* as above */ };
353enum( char * ) Names2 { @inline Names@, Jack = "JACK", Jill = "JILL" };
354@***@enum /* inferred */ Names3 { @inline Names2@, Sue = "SUE", Tom = "TOM" };
[bd67442]355\end{lstlisting}
[e11cdc0]356Enumeration @Name2@ inherits all the enumerators and their values from enumeration @Names@ by containment, and a @Names@ enumeration is a subtype of enumeration @Name2@.
[bd67442]357Note, enumerators must be unique in inheritance but enumerator values may be repeated.
358
359The enumeration type for the inheriting type must be the same as the inherited type;
360hence the enumeration type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for @Name3@.
[e11cdc0]361% When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
362Specifically, the inheritance relationship for @Names@ is:
[bd67442]363\begin{lstlisting}
[e11cdc0]364Names $\(\subset\)$ Names2 $\(\subset\)$ Names3 $\(\subset\)$ const char * $\C{// enum type of Names}$
[bd67442]365\end{lstlisting}
366For the given function prototypes, the following calls are valid.
367\begin{cquote}
368\begin{tabular}{ll}
369\begin{lstlisting}
[e11cdc0]370void f( Names );
371void g( Names2 );
372void h( Names3 );
[bd67442]373void j( const char * );
374\end{lstlisting}
375&
376\begin{lstlisting}
377f( Fred );
378g( Fred ); g( Jill );
379h( Fred ); h( Jill ); h( Sue );
[e11cdc0]380j( Fred ); j( Jill ); j( Sue ); j( "WILL" );
[bd67442]381\end{lstlisting}
382\end{tabular}
383\end{cquote}
384Note, the validity of calls is the same for call-by-reference as for call-by-value, and const restrictions are the same as for other types.
[0030b508]385
[66d92e3]386
[dd1ebb1]387\subsection{Enumeration Pseudo-functions}
[2989d6f]388
389Pseudo-functions are function-like operators that do not result in any run-time computations, i.e., like @sizeof@.
390Often 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..
[66d92e3]391
[e11cdc0]392
[dd1ebb1]393\subsubsection{Enumerator Attributes}
394The attributes of an enumerator are accessed by pseudo-functions @position@, @value@, and @label@.
[66d92e3]395\begin{lstlisting}
[e11cdc0]396@***@int jane_pos = position( Names.Jane ); $\C{// 2}$
397@***@char * jane_value = value( Names.Jane ); $\C{// "JANE"}$
398@***@char * jane_label = label( Names.Jane ); $\C{// "Jane"}$
[5ddb8bf]399\end{lstlisting}
400
[bd67442]401% An instance of \CFA-enum (denoted as @<enum_instance>@) is a label for the defined enum name.
402% The label can be retrieved by calling the function @label( <enum_instance> )@.
403% Similarly, the @value()@ function returns the value used to initialize the \CFA-enum.
404
[e11cdc0]405
406\subsubsection{\lstinline{switch/choose} Statement}
407
408An intuitive use of enumerations is with the \CFA @switch@/@choose@ statement, where @choose@ performs an implict @break@ rather than a fall-through at the end of a @case@ clause.
409\begin{lstlisting}
410enum Count { First, Second, Third, Fourth };
411Count e;
[0030b508]412\end{lstlisting}
[e11cdc0]413\begin{cquote}
414\begin{tabular}{ll}
415\begin{lstlisting}
416choose( e ) {
417 case @First@: ...;
418 case @Second@: ...;
419 case @Third@: ...;
420 case @Fourth@: ...;
421}
422\end{lstlisting}
423&
424\begin{lstlisting}
425choose( @value@( e ) ) {
426 case @value@( First ): ...;
427 case @value@( Second ): ...;
428 case @value@( Third ): ...;
429 case @value@( Fourth ): ...;
430}
431\end{lstlisting}
432\end{tabular}
433\end{cquote}
434Here, the intuitive implementation on the right uses the value of the enumeration and enumerators.
435However, this implementation is fragile, e.g., if the enumeration is changed to:
436\begin{lstlisting}
437enum Count { First, Second, Third @= First@, Fourth };
438\end{lstlisting}
439which make @Third == First@ and @Fourth == Second@, causing duplicase @case@ clauses.
440To better match with programmer intuition, \CFA uses a more robust implementation form when the type of a @switch@ expression is an enumeration.
441\begin{lstlisting}
442choose( @position@( e ) ) {
443 case @position@( First ): ...;
444 case @position@( Second ): ...;
445 case @position@( Third ): ...;
446 case @position@( Fourth ): ...;
447}
448\end{lstlisting}
449
450\begin{lstlisting}
451Count variable_a = First, variable_b = Second, variable_c = Third, variable_d = Fourth;
[5ddb8bf]452p(variable_a); // 0
453p(variable_b); // 1
454p(variable_c); // "Third"
455p(variable_d); // 3
[0030b508]456\end{lstlisting}
457
[dd1ebb1]458
[dc80280]459\section{Enumeration Storage}
[66d92e3]460
[dd1ebb1]461
[dc80280]462\subsection{Enumeration Variable}
[66d92e3]463
464Although \CFA enumeration captures three different attributes, an enumeration instance does not store all this information.
465The @sizeof@ a \CFA enumeration instance is always 4 bytes, the same size as a C enumeration instance (@sizeof( int )@).
[25f2798]466It comes from the fact that:
467\begin{enumerate}
468\item
469a \CFA enumeration is always statically typed;
470\item
[5ddb8bf]471it is always resolved as one of its attributes regarding real usage.
[25f2798]472\end{enumerate}
[66d92e3]473When creating an enumeration instance @colour@ and assigning it with the enumerator @Color.Green@, the compiler allocates an integer variable and stores the position 1.
[25f2798]474The invocations of $positions()$, $value()$, and $label()$ turn into calls to special functions defined in the prelude:
[0030b508]475\begin{lstlisting}[label=lst:companion_call]
476position( green );
477>>> position( Colour, 1 ) -> int
478value( green );
479>>> value( Colour, 1 ) -> T
480label( green );
481>>> label( Colour, 1) -> char *
482\end{lstlisting}
[dd1ebb1]483@T@ represents the type declared in the \CFA enumeration defined and @char *@ in the example.
[0030b508]484These generated functions are $Companion Functions$, they take an $companion$ object and the position as parameters.
485
[dd1ebb1]486
[dc80280]487\subsection{Enumeration Data}
[dd1ebb1]488
[0fa0201d]489\begin{lstlisting}[label=lst:enumeration_backing_data]
490enum(T) E { ... };
[dc80280]491// backing data
[dd1ebb1]492T * E_values;
493char ** E_labels;
[dc80280]494\end{lstlisting}
[dd1ebb1]495Storing values and labels as arrays can sometimes help support enumeration features.
496However, the data structures are the overhead for the programs. We want to reduce the memory usage for enumeration support by:
[0fa0201d]497\begin{itemize}
[dd1ebb1]498 \item Only generates the data array if necessary
499 \item The compilation units share the data structures.
500 No extra overhead if the data structures are requested multiple times.
[0fa0201d]501\end{itemize}
[dc80280]502
503
[21ce2c7]504\section{Unification}
505
[5ddb8bf]506\subsection{Enumeration as Value}
[21ce2c7]507\label{section:enumeration_as_value}
[dd1ebb1]508An \CFA enumeration with base type T can be used seamlessly as T, without explicitly calling the pseudo-function value.
[5ddb8bf]509\begin{lstlisting}[label=lst:implicit_conversion]
510char * green_value = Colour.Green; // "G"
[dd1ebb1]511// Is equivalent to
[21ce2c7]512// char * green_value = value( Color.Green ); "G"
513\end{lstlisting}
514
[dd1ebb1]515
[21ce2c7]516\subsection{Unification Distance}
[dd1ebb1]517
[21ce2c7]518\begin{lstlisting}[label=lst:unification_distance_example]
519T_2 Foo(T1);
[bab2917]520\end{lstlisting}
[21ce2c7]521The @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@.
522
523@path(A, B)@ is a compiler concept that returns one of the following:
524\begin{itemize}
[dd1ebb1]525 \item Zero or 0, if and only if $A == B$.
526 \item Safe, if B can be used as A without losing its precision, or B is a subtype of A.
527 \item Unsafe, if B loses its precision when used as A, or A is a subtype of B.
528 \item Infinite, if B cannot be used as A. A is not a subtype of B and B is not a subtype of A.
[21ce2c7]529\end{itemize}
530
531For example, @path(int, int)==Zero@, @path(int, char)==Safe@, @path(int, double)==Unsafe@, @path(int, struct S)@ is @Infinite@ for @struct S{}@.
532@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$$.
533
534(Skip over the distance matrix here because it is mostly irrelevant for enumeration discussion. In the actual implementation, distance( E, T ) is 1.)
535
536The arithmetic of distance is the following:
537\begin{itemize}
[dd1ebb1]538 \item $Zero + v= v$, for some value v.
539 \item $Safe * k < Unsafe$, for finite k.
540 \item $Unsafe * k < Infinite$, for finite k.
541 \item $Infinite + v = Infinite$, for some value v.
[21ce2c7]542\end{itemize}
[bab2917]543
[21ce2c7]544For @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@.
545
546
547\subsection{Variable Overloading and Parameter Unification}
[dd1ebb1]548
[21ce2c7]549\CFA allows variable names to be overloaded. It is possible to overload a variable that has type T and an enumeration with type T.
[5ddb8bf]550\begin{lstlisting}[label=lst:variable_overload]
551char * green = "Green";
[21ce2c7]552Colour green = Colour.Green; // "G"
553
554void bar(char * s) { return s; }
555void foo(Colour c) { return value( c ); }
556
[5ddb8bf]557foo( green ); // "G"
558bar( green ); // "Green"
[bab2917]559\end{lstlisting}
[21ce2c7]560\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 *@.
[25f2798]561
[5ddb8bf]562\subsection{Function Overloading}
[21ce2c7]563Similarly, functions can be overloaded with different signatures. \CFA picks the correct function entity based on the distance between parameter types and the arguments.
[5ddb8bf]564\begin{lstlisting}[label=lst:function_overload]
[dd1ebb1]565Colour green = Colour.Green;
[21ce2c7]566void foo(Colour c) { sout | "It is an enum"; } // First foo
567void foo(char * s) { sout | "It is a string"; } // Second foo
[5ddb8bf]568foo( green ); // "It is an enum"
[0030b508]569\end{lstlisting}
[21ce2c7]570Because @distance(Colour, Colour)@ is @Zero@ and @distance(char *, Colour)@ is @Safe@, \CFA determines the @foo( green )@ is a call to the first foo.
[0030b508]571
[21ce2c7]572\subsection{Attributes Functions}
573The 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@.
[2d373440]574
[21ce2c7]575\begin{lstlisting}[label=lst:declaration_code]
576int s1;
577\end{lstlisting}
578The 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
[2d373440]579
[21ce2c7]580% \subsection{Unification and Resolution (this implementation will probably not be used, safe as reference for now)}
581
582% \begin{lstlisting}
583% enum Colour( char * ) { Red = "R", Green = "G", Blue = "B" };
584% \end{lstlisting}
585% The @EnumInstType@ is convertible to other types.
586% A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
[dd1ebb1]587% The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context.
[21ce2c7]588
589% \begin{lstlisting}[caption={Null Context}, label=lst:null_context]
590% {
591% Colour.Green;
592% }
593% \end{lstlisting}
594% In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
595% In this case, any of the attributes is resolvable.
596% According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
597% The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
598% When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
599% \begin{lstlisting}[caption={Null Context Generated Code}, label=lst:null_context]
600% {
601% "G";
602% }
603% \end{lstlisting}
604% \begin{lstlisting}[caption={int Context}, label=lst:int_context]
605% {
606% int g = Colour.Green;
607% }
608% \end{lstlisting}
609% The assignment expression gives a context for the EnumInstType resolution.
610% The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
611% The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
612% In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
613% $$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
614% \begin{lstlisting}[label=lst:attr_resolution_1]
615% {
616% Unify( int, char * ); // unify with the type of value
617% Unify( int, int ); // unify with the type of position
618% Unify( int, char * ); // unify with the type of label
619% }
620% \end{lstlisting}
621% \begin{lstlisting}[label=lst:attr_resolution_precedence]
622% {
623% Unification( T1, EnumInstType<T2> ) {
624% if ( Unify( T1, T2 ) ) return T2;
625% if ( Unify( T1, int ) ) return int;
626% if ( Unify( T1, char * ) ) return char *;
627% Error: Cannot Unify T1 with EnumInstType<T2>;
628% }
629% }
630% \end{lstlisting}
631% After the unification, @EnumInstType@ is replaced by its attributes.
632
633% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
634% {
635% T2 foo ( T1 ); // function take variable with T1 as a parameter
636% foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
637% >>>> Unification( T1, EnumInstType<T3> )
638% }
639% \end{lstlisting}
[dd1ebb1]640% % The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType.
[21ce2c7]641% Backward conversion:
642% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
643% {
644% enum Colour colour = 1;
645% }
646% \end{lstlisting}
647
648% \begin{lstlisting}[caption={Unification Functions}, label=lst:unification_func_call]
649% {
[dd1ebb1]650% Unification( EnumInstType<Colour>, int ) >>> label
[21ce2c7]651% }
652% \end{lstlisting}
653% @int@ can be unified with the label of Colour.
[dd1ebb1]654% @5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into
[21ce2c7]655% \begin{lstlisting}
656% {
[dd1ebb1]657% enum Colour colour = Colour.Green;
[21ce2c7]658% }
659% \end{lstlisting}
660% Steps:
661% \begin{enumerate}
662% \item
663% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
664% \item
665% @unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
666% \item
667% return the enumeration constant at position 1
668% \end{enumerate}
669% \begin{lstlisting}
670% {
671% enum T (int) { ... } // Declaration
[dd1ebb1]672% enum T t = 1;
[21ce2c7]673% }
674% \end{lstlisting}
675% Steps:
676% \begin{enumerate}
677% \item
678% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
679% \item
680% @unification( EnumInstType<Colour>, int )@: @value( EnumInstType< Colour > )@
681% \item
682% return the FIRST enumeration constant that has the value 1, by searching through the values array
683% \end{enumerate}
[dd1ebb1]684% 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
[21ce2c7]685
686% \subsection{Casting}
687% Casting an EnumInstType to some other type T works similarly to unify the EnumInstType with T. For example:
688% \begin{lstlisting}
689% enum( int ) Foo { A = 10, B = 100, C = 1000 };
690% (int) Foo.A;
691% \end{lstlisting}
[dd1ebb1]692% 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.
[21ce2c7]693
694% \subsection{Value Conversion}
695% 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.
696
697% \begin{lstlisting}
698% Foo a; // int a;
699% int j = a;
700% char * s = a;
701% \end{lstlisting}
702% 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
703% \begin{lstlisting}
704% int j = value( Foo, a )
705% \end{lstlisting}
[dd1ebb1]706% Similarly, the generated code for the third line is
[21ce2c7]707% \begin{lstlisting}
708% char * j = label( Foo, a )
709% \end{lstlisting}
[25f2798]710
[0030b508]711
[2d373440]712\section{Enumerator Initialization}
713An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
714
715\subsection{C Enumeration Rule}
[dd1ebb1]716A 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$.
[2d373440]717
[0030b508]718\subsection{Auto Initializable}
719\label{s:AutoInitializable}
[25f2798]720
[0030b508]721
[25f2798]722\CFA enumerations have the same rule in enumeration constant initialization.
[66d92e3]723However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA.
[0030b508]724
[66d92e3]725Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@:
[0030b508]726\begin{lstlisting}
[bab2917]727forall(T)
728trait AutoInitializable {
[0030b508]729 void ?()( T & t, zero_t );
[5ddb8bf]730 S ?++( T & t);
[bab2917]731};
732\end{lstlisting}
[66d92e3]733An example of a user-defined @AutoInitializable@ is:
[25f2798]734\begin{lstlisting}[label=lst:sample_auto_Initializable]
[0030b508]735struct Odd { int i; };
736void ?()( Odd & t, zero_t ) { t.i = 1; };
[5ddb8bf]737Odd ?++( Odd t1 ) { return Odd( t1.i + 2); };
[0030b508]738\end{lstlisting}
[dd1ebb1]739When the type of an enumeration is @AutoInitializable@, implicit initialization is available.
[25f2798]740\begin{lstlisting}[label=lst:sample_auto_Initializable_usage]
[0030b508]741enum AutoInitUsage(Odd) {
[66d92e3]742 A, B, C = 7, D
[bab2917]743};
744\end{lstlisting}
[5ddb8bf]745In 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.
746@B@ and @D@ have the values of their $predecessor++$, where @one_t@ has the value 2.
[66d92e3]747Therefore, the enumeration is initialized as follows:
[25f2798]748\begin{lstlisting}[label=lst:sample_auto_Initializable_usage_gen]
[0030b508]749enum AutoInitUsage(Odd) {
[66d92e3]750 A = 1, B = 3, C = 7, D = 9
[85034ed]751};
752\end{lstlisting}
[2d373440]753Note that there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@.
[66d92e3]754
755In \CFA, character, integral, float, and imaginary types are all @AutoInitialiable@.
[0030b508]756\begin{lstlisting}[label=lst:letter]
[66d92e3]757enum Alphabet( int ) {
758 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,
759 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
[0030b508]760};
[66d92e3]761print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.z );
762>>> F, o, z
[0030b508]763\end{lstlisting}
[2d373440]764\section{Enumeration Features}
[0030b508]765\subsection{Iteration and Range}
766
[2d373440]767It is convenient to iterate over a \CFA enumeration value, e.g.:
[0030b508]768\begin{lstlisting}[label=lst:range_functions]
[2d373440]769for ( Alphabet alph; Alphabet ) { sout | alph; }
770>>> A B C ... D
[0030b508]771\end{lstlisting}
[66d92e3]772The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
773@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
[bab2917]774
[dd1ebb1]775\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
[0030b508]776\begin{lstlisting}[label=lst:range_functions]
[2d373440]777for ( Alphabet alph ) { sout | alph; }
778>>> A B C ... D
[0030b508]779\end{lstlisting}
[2d373440]780
781The 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.
782
783\textbullet\ H is implicit up-to exclusive range [0, H).
784\begin{lstlisting}[label=lst:range_function_1]
785for ( alph; Alphabet.D ) { sout | alph; }
786>>> A B C
[85034ed]787\end{lstlisting}
[0030b508]788
[2d373440]789\textbullet\ ~= H is implicit up-to inclusive range [0,H].
790\begin{lstlisting}[label=lst:range_function_2]
791for ( alph; ~= Alphabet.D ) { sout | alph; }
792>>> A B C D
793\end{lstlisting}
794
795\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
796\begin{lstlisting}[label=lst:range_function_3]
797for ( alph; Alphabet.B ~ Alphabet.D ) { sout | alph; }
798// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1 ); 1 is one_t
799>>> B C
800\end{lstlisting}
801
802\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
803\begin{lstlisting}[label=lst:range_function_4]
804for ( alph; Alphabet.B ~= Alphabet.D ) { sout | alph; }
805>>> B C D
[85034ed]806\end{lstlisting}
[2d373440]807
808\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
809\begin{lstlisting}[label=lst:range_function_5]
810for ( alph; Alphabet.D -~ Alphabet.B ) { sout | alph; }
811>>> D C
812\end{lstlisting}
813
814\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
815\begin{lstlisting}[label=lst:range_function_6]
816for ( alph; Alphabet.D -~= Alphabet.B ) { sout | alph; }
817>>> D C B
818\end{lstlisting}
819
820A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
821\begin{lstlisting}[label=lst:range_function_stepping]
822enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D = 18 };
823for ( s; Sequence.A ~= Sequence.D ~ 1 ) { sout | alph; }
824>>> 10 12 14 16 18
825for ( s; Sequence.A ~= Sequence.D; s+=1 ) { sout | alph; }
826>>> 10 11 12 13 14 15 16 17 18
827\end{lstlisting}
[dd1ebb1]828The 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
[2d373440]829\begin{lstlisting}[label=lst:range_function_stepping_converted]
830for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1 ) { sout | alph; }
831>>> 10 11 12 13 14 15 16 17 18
832\end{lstlisting}
833
834% \PAB{Explain what each loop does.}
[85034ed]835
[0030b508]836It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
837\begin{lstlisting}[label=lst:range_functions_label_implicit]
[66d92e3]838for ( char * alph; Alphabet )
[0030b508]839\end{lstlisting}
[dd1ebb1]840This 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.
[25f2798]841If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
[0030b508]842\begin{lstlisting}[label=lst:range_functions_label_implicit]
843for ( char * ch; labels( Alphabet ) )
844\end{lstlisting}
[85034ed]845
[2d373440]846
847% \subsection{Non-uniform Type}
848% TODO: Working in Progress, might need to change other sections. Conflict with the resolution right now.
849
850% \begin{lstlisting}
851% enum T( int, char * ) {
[dd1ebb1]852% a=42, b="Hello World"
[2d373440]853% };
854% \end{lstlisting}
[dd1ebb1]855% The enum T declares two different types: int and char *. The enumerators of T hold values of one of the declared types.
[2d373440]856
857\subsection{Enumeration Inheritance}
858
859\begin{lstlisting}[label=lst:EnumInline]
860enum( char * ) Name { Jack = "Jack", Jill = "Jill" };
861enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
862\end{lstlisting}
[dd1ebb1]863\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.
[2d373440]864\begin{lstlisting}[label=lst:EnumInline]
865Name Fred;
866void f( Name2 );
867f( Fred );
868\end{lstlisting}
869If enumeration A declares @inline B@ in its enumeration body, enumeration A is the "inlining enum" and enumeration B is the "inlined enum".
870
[dd1ebb1]871An 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.
[2d373440]872\begin{lstlisting}[label=lst:EnumInline]
873enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
874// is equivalent to enum Name2 { Jack = "Jack", Jill="Jill", Sue = "Sue", Tom = "Tom" };
875\end{lstlisting}
876Name.Jack is equivalent to Name2.Jack. Their attributes are all identical. Opening both Name and Name2 in the same scope will not introduce ambiguity.
877\begin{lstlisting}[label=lst:EnumInline]
878with( Name, Name2 ) { Jack; } // Name.Jack and Name2.Jack are equivalent. No ambiguity
879\end{lstlisting}
880
[0030b508]881\section{Implementation}
[25f2798]882
[367725d]883\subsection{Static Attribute Expression}
884\begin{lstlisting}[label=lst:static_attr]
885enum( char * ) Colour {
[dd1ebb1]886 Red = "red", Blue = "blue", Green = "green"
[367725d]887};
888\end{lstlisting}
[dd1ebb1]889An 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.
[367725d]890
891\subsection{Runtime Attribute Expression and Weak Referenced Data}
892\begin{lstlisting}[label=lst:dynamic_attr]
893Colour c;
894...
895value( c ); // or c
896\end{lstlisting}
897An 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.
898
[dd1ebb1]899\CFA stores the variables and labels in @const@ arrays to provide runtime lookup for enumeration information.
[367725d]900
901\begin{lstlisting}[label=lst:attr_array]
902const char * Colour_labels [3] = { "Red", "Blue", "Green" };
903const char * Colour_values [3] = { "red", "blue", "green" };
904\end{lstlisting}
905The \CFA compiles transforms the attribute expressions into array access.
906\begin{lstlisting}[label=lst:attr_array_access]
907position( c ) // c; an integer
908value( c ); // Colour_values[c]
909label( c ); // Colour_labels[c]
910\end{lstlisting}
911
[dd1ebb1]912To 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.
[367725d]913
914\subsection{Enum Prelude}
915
916\begin{lstlisting}[label=lst:enum_func_dec]
917forall( T ) {
[dd1ebb1]918 unsigned position( unsigned );
919 T value( unsigned );
920 char * label( unsigned );
[367725d]921}
922\end{lstlisting}
923\CFA loads the declaration of enumeration function from the enum.hfa.
924
925\subsection{Internal Representation}
926
[2d373440]927The 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:
928\begin{lstlisting}[label=lst:EnumDecl]
929forall(T)
930class EnumDecl {
[dd1ebb1]931 T* values;
932 char** label;
[2d373440]933};
934\end{lstlisting}
935
936The internal representation of an enumeration constant is @EnumInstType@.
937An @EnumInstType@ has a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
938\begin{lstlisting}[label=lst:EnumInstType]
939class EnumInstType {
[dd1ebb1]940 EnumDecl enumDecl;
941 int position;
[2d373440]942};
943\end{lstlisting}
944In 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>@.
945
[5ddb8bf]946\begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_data]
947const T * const values;
948const char * label;
949int length;
950\end{lstlisting}
951Companion 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".
952Companion 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.
953
954
[367725d]955% \subsection{(Rework) Companion Object and Companion Function}
[5ddb8bf]956
[367725d]957% \begin{lstlisting}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
958% forall( T )
959% struct Companion {
960% const T * const values;
[dd1ebb1]961% const char * label;
[367725d]962% int length;
963% };
964% \end{lstlisting}
965% \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@.
[5ddb8bf]966
[dd1ebb1]967% The companion object is singleton across the compilation (investigation).
[5ddb8bf]968
[367725d]969% \CFA generates the definition of companion functions.
970% Because \CFA implicitly stores an enumeration instance as its position, the companion function @position@ does nothing but return the position it is passed.
971% Companions function @value@ and @label@ return the array item at the given position of @values@ and @labels@, respectively.
972% \begin{lstlisting}[label=lst:companion_definition]
973% int position( Companion o, int pos ) { return pos; }
974% T value( Companion o, int pos ) { return o.values[ pos ]; }
975% char * label( Companion o, int pos ) { return o.labels[ pos ]; }
976% \end{lstlisting}
977% Notably, the @Companion@ structure definition, and all companion objects, are visible to users.
978% 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@
979% \begin{lstlisting}[label=lst:companion_definition_values_labels]
980% Colour.values; // read the Companion's values
981% values( Colour ); // same as Colour.values
982% \end{lstlisting}
[5ddb8bf]983
984\subsection{Companion Traits (experimental)}
985Not sure its semantics yet, and it might replace a companion object.
986\begin{lstlisting}[label=lst:companion_trait]
987forall(T1) {
[dd1ebb1]988 trait Companion(otype T2<otype T1>) {
989 T1 value((otype T2<otype T1> const &);
990 int position(otype T2<otype T1> const &);
991 char * label(otype T2<otype T1> const &);
992 }
[5ddb8bf]993}
994\end{lstlisting}
995All 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:
996
997\begin{enumerate}
998 \item The instance of enumeration has a single polymorphic type.
999 \item Each assertion should use the type once as a parameter.
1000\end{enumerate}
1001
1002\begin{lstlisting}
1003enum(int) Weekday {
[dd1ebb1]1004 Monday=10, Tuesday, ...
[5ddb8bf]1005};
1006
1007T value( enum Weekday<T> & this);
1008int position( enum Weekday<T> & this )
1009char * label( enum Weekday<T> & this )
1010
1011trait Companion obj = (enum(int)) Workday.Weekday;
1012value(obj); // 10
1013\end{lstlisting}
1014The 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.
1015(...)
1016
1017\subsection{User Define Enumeration Functions}
1018
[dd1ebb1]1019Companion objects make extending features for \CFA enumeration easy.
[5ddb8bf]1020\begin{lstlisting}[label=lst:companion_user_definition]
[dd1ebb1]1021char * charastic_string( Companion o, int position ) {
1022 return sprintf( "Label: %s; Value: %s", label( o, position ), value( o, position) );
[5ddb8bf]1023}
1024printf( charactic_string ( Color, 1 ) );
1025>>> Label: Green; Value: G
1026\end{lstlisting}
1027Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.
1028
1029The \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.
1030Therefore, a user can use the syntax with a user-defined enumeration function call:
1031\begin{lstlisting}[label=lst:companion_user_definition]
1032charactic_string( Color.Green ); // equivalent to charactic_string( Color, 1 )
1033>>> Label: Green; Value: G
1034\end{lstlisting}
1035Similarly, the user can work with the enumeration type itself: (see section ref...)
1036\begin{lstlisting}[ label=lst:companion_user_definition]
[dd1ebb1]1037void print_enumerators ( Companion o ) {
[5ddb8bf]1038 for ( c : Companion o ) {
1039 sout | label (c) | value( c ) ;
[dd1ebb1]1040 }
[5ddb8bf]1041}
1042print_enumerators( Colour );
1043\end{lstlisting}
1044
[85034ed]1045
[25f2798]1046\subsection{Declaration}
1047
[0030b508]1048The qualified enumeration syntax is dedicated to \CFA enumeration.
1049\begin{lstlisting}[label=lst:range_functions]
1050enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
[85034ed]1051\end{lstlisting}
[25f2798]1052A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
1053During the $Validation$ pass, the compiler links the type declaration to the type's definition.
1054It 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.
[66d92e3]1055If the declared type is not @AutoInitializable@, \CFA rejects the enumeration definition.
[dd1ebb1]1056Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section)
[85034ed]1057
[0030b508]1058\begin{lstlisting}[label=lst:init]
1059struct T { ... };
1060void ?{}( T & t, zero_t ) { ... };
1061void ?{}( T & t, one_t ) { ... };
1062T ?+?( T & lhs, T & rhs ) { ... };
[85034ed]1063
[dd1ebb1]1064enum (T) Sample {
1065 Zero: 0 /* zero_t */,
[25f2798]1066 One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
[85034ed]1067};
[0030b508]1068\end{lstlisting}
[25f2798]1069Challenge: \\
1070The value of an enumerator, or the initializer, requires @const_expr@.
1071While 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.
1072Might not be able to implement a \emph{correct} static check.
[0030b508]1073
1074\CFA $autogens$ a Companion object for the declared enumeration.
1075\begin{lstlisting}[label=lst:companion]
1076Companion( T ) Sample {
[25f2798]1077 .values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
1078 .labels: { "Zero", "One", "Two", "Three", ...},
1079 .length: /* number of enumerators */
[85034ed]1080};
1081\end{lstlisting}
[25f2798]1082\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
1083But the result is computed at run time, and the compiler ensures the @values@ are not changed.
[85034ed]1084
[66d92e3]1085\subsection{Qualified Expression}
[25f2798]1086
[dd1ebb1]1087\CFA uses qualified expression to address the scoping of \CFA-enumeration.
[0030b508]1088\begin{lstlisting}[label=lst:qualified_expression]
1089aggregation_name.field;
1090\end{lstlisting}
[25f2798]1091The qualified expression is not dedicated to \CFA enumeration.
1092It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
1093When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
1094\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
1095If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.
1096
[2d373440]1097\subsection{Instance Declaration}
[0030b508]1098
[25f2798]1099
[2d373440]1100\begin{lstlisting}[label=lst:var_declaration]
1101enum Sample s1;
[0030b508]1102\end{lstlisting}
1103
[2d373440]1104The declaration \CFA-enumeration variable has the same syntax as the C-enumeration. Internally, such a variable will be represented as an EnumInstType.
1105
[dd1ebb1]1106\section{Related Work}
[bd67442]1107\label{s:RelatedWork}
1108
1109Enumerations exist in many popular programming languages, e.g., Pascal, Ada, \Csharp, \CC, Go, Java, Modula-3, Rust, Swift, Python, and the algebraic data-type in functional programming.
1110There are a large set of overlapping features among these languages, but each language has its own unique restrictions and extensions.
[dd1ebb1]1111
[bd67442]1112\subsection{(Free) Pascal}
1113
1114Free Pascal is a modern object-oriented version of the classic Pascal programming language.
1115It allows a C-style enumeration type, where enumerators must be in assigned in ascending numerical order with a constant expression and the range can be non-consecutive.
1116\begin{lstlisting}[language=pascal,{moredelim=**[is][\color{red}]{@}{@}}]
1117Type EnumType = ( one, two, three, forty @= 40@, fortyone );
1118\end{lstlisting}
1119Pseudo-functions @Pred@ and @Succ@ can only be used if the range is consecutive.
1120The underlying type is an implementation-defined integral type large enough to hold all enumerated values; it does not have to be the smallest possible type.
1121The size underlying integral type can be explicitly specified using compiler directive @$PACKENUM@~$N$, where $N$ is the number of bytes, e.g.:
1122\begin{lstlisting}[language=pascal,{moredelim=**[is][\color{red}]{@}{@}}]
1123Type @{$\color{red}\$$PACKENUM 1}@ SmallEnum = ( one, two, three );
1124 @{$\color{red}\$$PACKENUM 4}@ LargeEnum = ( BigOne, BigTwo, BigThree );
1125Var S : SmallEnum; { 1 byte }
1126 L : LargeEnum; { 4 bytes}
1127\end{lstlisting}
[2989d6f]1128
1129
1130\subsection{Ada}
1131
[bd67442]1132An enumeration type is defined as a list of possible values:
1133\begin{lstlisting}[language=ada]
1134type RGB is (Red, Green, Blue);
1135\end{lstlisting}
1136Like for numeric types, where e.g., 1 is an integer literal, @Red@, @Green@ and @Blue@ are called the literals of this type.
1137There are no other values assignable to objects of this type.
1138
1139\paragraph{Operators and attributes} ~\newline
1140Apart from equality (@"="@), the only operators on enumeration types are the ordering operators: @"<"@, @"<="@, @"="@, @"/="@, @">="@, @">"@, where the order relation is given implicitly by the sequence of literals:
1141Each literal has a position, starting with 0 for the first, incremented by one for each successor.
1142This position can be queried via the @'Pos@ attribute; the inverse is @'Val@, which returns the corresponding literal. In our example:
1143\begin{lstlisting}[language=ada]
1144RGB'Pos (Red) = 0
1145RGB'Val (0) = Red
1146\end{lstlisting}
1147There are two other important attributes: @Image@ and @Value@.
1148@Image@ returns the string representation of the value (in capital letters), @Value@ is the inverse:
1149\begin{lstlisting}[language=ada]
1150RGB'Image ( Red ) = "RED"
1151RGB'Value ("Red") = Red
1152\end{lstlisting}
1153These attributes are important for simple IO (there are more elaborate IO facilities in @Ada.Text_IO@ for enumeration types).
1154Note that, since Ada is case-insensitive, the string given to @'Value@ can be in any case.
1155
1156\paragraph{Enumeration literals} ~\newline
1157Literals are overloadable, i.e. you can have another type with the same literals.
1158\begin{lstlisting}[language=ada]
1159type Traffic_Light is (Red, Yellow, Green);
1160\end{lstlisting}
1161Overload resolution within the context of use of a literal normally resolves which @Red@ is meant.
1162Only if you have an unresolvable overloading conflict, you can qualify with special syntax which @Red@ is meant:
1163\begin{lstlisting}[language=ada]
1164RGB'(Red)
1165\end{lstlisting}
1166Like many other declarative items, enumeration literals can be renamed.
1167In fact, such a literal is actually a function, so it has to be renamed as such:
1168\begin{lstlisting}[language=ada]
1169function Red return P.RGB renames P.Red;
1170\end{lstlisting}
1171Here, @RGB@ is assumed to be defined in package @P@, which is visible at the place of the renaming declaration.
1172Renaming makes @Red@ directly visible without necessity to resort the use-clause.
1173
1174Note that redeclaration as a function does not affect the staticness of the literal.
1175
1176\paragraph{Characters as enumeration literals} ~\newline
1177Rather unique to Ada is the use of character literals as enumeration literals:
1178\begin{lstlisting}[language=ada]
1179type ABC is ('A', 'B', 'C');
1180\end{lstlisting}
1181This literal @'A'@ has nothing in common with the literal @'A'@ of the predefined type @Character@ (or @Wide_Character@).
1182
1183Every type that has at least one character literal is a character type.
1184For every character type, string literals and the concatenation operator @"&"@ are also implicitly defined.
1185\begin{lstlisting}[language=ada]
1186type My_Character is (No_Character, 'a', Literal, 'z');
1187type My_String is array (Positive range <>) of My_Character;
1188
1189S: My_String := "aa" & Literal & "za" & 'z';
1190T: My_String := ('a', 'a', Literal, 'z', 'a', 'z');
1191\end{lstlisting}
1192In this example, @S@ and @T@ have the same value.
1193
1194Ada's @Character@ type is defined that way.
1195See Ada Programming/Libraries/Standard.
1196
1197\paragraph{Booleans as enumeration literals} ~\newline
1198Also Booleans are defined as enumeration types:
1199\begin{lstlisting}[language=ada]
1200type Boolean is (False, True);
1201\end{lstlisting}
1202There is special semantics implied with this declaration in that objects and expressions of this type can be used as conditions.
1203Note that the literals @False@ and @True@ are not Ada keywords.
1204
1205Thus it is not sufficient to declare a type with these literals and then hope objects of this type can be used like so:
1206\begin{lstlisting}[language=ada]
1207type My_Boolean is (False, True);
1208Condition: My_Boolean;
1209
1210if Condition then -- wrong, won't compile
1211\end{lstlisting}
1212
1213If you need your own Booleans (perhaps with special size requirements), you have to derive from the predefined Boolean:
1214\begin{lstlisting}[language=ada]
1215type My_Boolean is new Boolean;
1216Condition: My_Boolean;
1217
1218if Condition then -- OK
1219\end{lstlisting}
1220
1221\paragraph{Enumeration subtypes} ~\newline
1222You can use range to subtype an enumeration type:
1223\begin{lstlisting}[language=ada]
1224subtype Capital_Letter is Character range 'A' .. 'Z';
1225type Day_Of_Week is (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday);
1226subtype Working_Day is Day_Of_Week range Monday .. Friday;
1227\end{lstlisting}
1228
1229\paragraph{Using enumerations} ~\newline
1230Enumeration types being scalar subtypes, type attributes such as @First@ and @Succ@ will allow stepping through a subsequence of the values.
1231\begin{lstlisting}[language=ada]
1232case Day_Of_Week'First is
1233 when Sunday =>
1234 ISO (False);
1235 when Day_Of_Week'Succ(Sunday) =>
1236 ISO (True);
1237 when Tuesday .. Saturday =>
1238 raise Program_Error;
1239end case;
1240\end{lstlisting}
1241A loop will automatically step through the values of the subtype's range.
1242Filtering week days to include only working days with an even position number:
1243\begin{lstlisting}[language=ada]
1244 for Day in Working_Day loop
1245 if Day_Of_Week'Pos(Day) mod 2 = 0 then
1246 Work_In_Backyard;
1247 end if;
1248 end loop;
1249\end{lstlisting}
1250Enumeration types can be used as array index subtypes, yielding a table feature:
1251\begin{lstlisting}[language=ada]
1252type Officer_ID is range 0 .. 50;
1253type Schedule is array (Working_Day) of Officer_ID;
1254\end{lstlisting}
1255
1256\begin{lstlisting}[language=ada]
1257type Subtype_Name is (Id1, Id2, Id3 ... );
1258\end{lstlisting}
1259where @Id1@, @Id2@, etc. are identifiers or characters literals.
1260In either case, the legal values of the type are referred to as "enumeration literals."
1261Each of these values has a "position number" corresponding to its position in the list such that @Id1@ has position 0, @Id2@ has position 1, and the Nth value has position N-1.
1262
1263\paragraph{Attributes of Enumeration Types} ~\newline
1264An enumeration type, @T@, has the following attributes: @T'First@, @T'Last@, @T'Range@, @T'Pred@, @T'Succ@, @T'Min@, @T'Max@, @T'Image@, @T'Wide_Image@, @T'Value@, @T'Wide_Value@, @T'Pos@, and @T'Val@ (pronounced "T tick first", "T tick last", etc.).
1265Most of these are illustrated in the example program given below, and most of them produce what you would intuitively expect based on their names.
1266
1267@T'Image@ and @T'Value@ form a complementary pair of attributes.
1268The former takes a value in @T@ and returns a String representation of that value.
1269The latter takes a @String@ that is a representation of a value in @T@ and returns that value.
1270
1271@T'Pos@ and @T'Val@ form another complementary pair.
1272The former takes a value in @T@ and returns its position number.
1273The latter takes a position number and returns the corresponding value of type @T@.
1274
1275
[2989d6f]1276\subsection{\Csharp}
1277
1278\subsection{\CC}
1279
[bd67442]1280\CC is backwards compatible with C, so it inherited C's enumerations, except there is no implicit conversion from an integral value to an enumeration;
1281hence, the values in a \CC enumeration can only be its enumerators (without a cast).
1282There is no mechanism to iterate through an enumeration.
[2989d6f]1283
[bd67442]1284\CC{11} added a scoped enumeration, \lstinline[language=c++]{enum class} (or \lstinline[language=c++]{enum struct}), so the enumerators are local to the enumeration and must be accessed using type qualification, e.g., @Weekday::Monday@.
[2989d6f]1285\CC{20} supports unscoped access with a \lstinline[language=c++]{using enum} declaration.
1286
[bd67442]1287For both unscoped and scoped enumerations, the underlying type is an implementation-defined integral type large enough to hold all enumerated values; it does not have to be the smallest possible type.
1288In \CC{11}, the underlying integral type can be explicitly specified:
[2989d6f]1289\begin{lstlisting}[language=c++,{moredelim=**[is][\color{red}]{@}{@}}]
1290enum class RGB : @long@ { Red, Green, Blue };
1291enum class rgb : @char@ { Red = 'r', Green = 'g', Blue = 'b' };
1292enum class srgb : @signed char@ { Red = -1, Green = 0, Blue = 1 };
[bd67442]1293RGB colour1 = @RGB::@Red;
1294rgb colour2 = @rgb::@Red;
1295srgb colour3 = @srgb::@Red;
[2989d6f]1296\end{lstlisting}
1297
1298\subsection{Go}
1299
1300\subsection{Java}
1301
1302\subsection{Modula-3}
1303
1304\subsection{Rust}
1305
1306\subsection{Swift}
1307
1308\subsection{Python}
1309
1310\subsection{Algebraic Data Type}
[5ddb8bf]1311
[85034ed]1312\end{document}
[0030b508]1313
1314% Local Variables: %
1315% tab-width: 4 %
1316% compile-command: "pdflatex enum.tex" %
1317% End: %
Note: See TracBrowser for help on using the repository browser.