source: doc/theses/jiada_liang_MMath/implementation.tex @ a03ed29

Last change on this file since a03ed29 was a03ed29, checked in by JiadaL <j82liang@…>, 5 days ago

conclude merge

  • Property mode set to 100644
File size: 35.2 KB
Line 
1\chapter{Enumeration Implementation}
2
3\section{Enumeration Traits}
4
5\CFA defines a set of traits containing operators and helper functions for @enum@.
6A \CFA enumeration satisfies all of these traits allowing it to interact with runtime features in \CFA.
7Each trait is discussed in detail.
8
9The trait @CfaEnum@:
10\begin{cfa}
11forall( E ) trait CfaEnum {
12        const char * @label@( E e );
13        unsigned int @posn@( E e );
14};
15\end{cfa}
16asserts an enumeration type @E@ has named enumerator constants (@label@) with positions (@posn@).
17
18The trait @TypedEnum@ extends @CfaEnum@:
19\begin{cfa}
20forall( E, V | CfaEnum( E ) ) trait TypedEnum {
21        V @value@( E e );
22};
23\end{cfa}
24asserting an enumeration type @E@ can have homogeneous enumerator values of type @V@.
25
26The declarative syntax
27\begin{cfa}
28enum(T) E { A = ..., B = ..., C = ... };
29\end{cfa}
30creates an enumerated type E with @label@, @posn@ and @value@ implemented automatically.
31\begin{cfa}
32void foo( T t ) { ... }
33void bar(E e) {
34        choose ( e ) {
35                case A: printf( "\%d", posn( e) );
36                case B: printf( "\%s", label( e ) );
37                case C: foo( value( e ) );
38        } 
39}
40\end{cfa}
41
42Implementing general functions across all enumeration types is possible by asserting @CfaEnum( E, T )@, \eg:
43\begin{cfa}
44#include <string.hfa>
45forall( E, T | CfaEnum( E, T ) | {unsigned int toUnsigned(T)} )
46string formatEnum( E e ) {
47        unsigned int v = toUnsigned( value( e ) );
48        string out = label(e) + '(' + v +')';
49        return out;
50}
51formatEnum( Week.Mon );
52formatEnum( RGB.Green );
53\end{cfa}
54
55\CFA does not define attribute functions for C-style enumeration.
56But it is possible for users to explicitly implement enumeration traits for C enum and any other types.
57\begin{cfa}
58enum Fruit { Apple, Pear, Cherry };                     $\C{// C enum}$
59const char * label( Fruit f ) {
60        choose ( f ) {
61                case Apple: return "Apple";
62                case Bear: return "Pear";
63                case Cherry: return "Cherry";
64        }
65}
66unsigned posn( Fruit f ) { return f; }
67const char * value( Fruit f ) { return ""; } $\C{// value can return any non void type}$
68formatEnum( Apple );                                            $\C{// Fruit is now a \CFA enum}$
69\end{cfa}
70
71A type that implements trait @CfaEnum@, \ie, a type has no @value@, is called an opaque enum.
72
73% \section{Enumerator Opaque Type}
74
75% \CFA provides a special opaque enumeration type, where the internal representation is chosen by the compiler and only equality operations are available.
76\begin{cfa}
77enum@()@ Planets { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE };
78\end{cfa}
79
80
81In addition, \CFA implements @Bound@ and @Serial@ for \CFA enumerations.
82\begin{cfa}
83forall( E ) trait Bounded {
84        E first();
85        E last();
86};
87\end{cfa}
88The function @first()@ and @last()@ of enumerated type E return the first and the last enumerator declared in E, respectively. \eg:
89\begin{cfa}
90Workday day = first();                                  $\C{// Mon}$
91Planet outermost = last();                              $\C{// NEPTUNE}$
92\end{cfa}
93@first()@ and @last()@ are overloaded with return types only, so in the example, the enumeration type is found on the left-hand side of the assignment.
94Calling either functions without a context results in a type ambiguity, except in the rare case where the type environment has only one enumeration.
95\begin{cfa}
96@first();@                                                              $\C{// ambiguous because both Workday and Planet implement Bounded}$
97sout | @last()@;
98Workday day = first();                                  $\C{// day provides type Workday}$
99void foo( Planet p );
100foo( last() );                                                  $\C{// argument provides type Planet}$
101\end{cfa}
102
103The trait @Serial@:
104\begin{cfa}
105forall( E | Bounded( E ) ) trait Serial {
106        unsigned fromInstance( E e );
107        E fromInt( unsigned int posn );
108        E succ( E e );
109        E pred( E e );
110};
111\end{cfa}
112is a @Bounded@ trait, where elements can be mapped to an integer sequence.
113A type @T@ matching @Serial@ can project to an unsigned @int@ type, \ie an instance of type T has a corresponding integer value.
114%However, the inverse may not be possible, and possible requires a bound check.
115The mapping from a serial type to integer is defined by @fromInstance@, which returns the enumerator's position.
116The inverse operation is @fromInt@, which performs a bound check using @first()@ and @last()@ before casting the integer into an enumerator.
117Specifically, for enumerator @E@ declaring $N$ enumerators, @fromInt( i )@ returns the $i-1_{th}$ enumerator, if $0 \leq i < N$, or raises the exception @enumBound@.
118
119The @succ( E e )@ and @pred( E e )@ imply the enumeration positions are consecutive and ordinal.
120Specifically, if @e@ is the $i_{th}$ enumerator, @succ( e )@ returns the $i+1_{th}$ enumerator when $e \ne last()$, and @pred( e )@ returns the $i-1_{th}$ enumerator when $e \ne first()$.
121The exception @enumRange@ is raised if the result of either operation is outside the range of type @E@.
122
123Finally, there is an associated trait defining comparison operators among enumerators.
124\begin{cfa}
125forall( E, T | CfaEnum( E, T ) ) {
126        // comparison
127        int ?==?( E l, E r );           $\C{// true if l and r are same enumerators}$
128        int ?!=?( E l, E r );           $\C{// true if l and r are different enumerators}$
129        int ?!=?( E l, zero_t );        $\C{// true if l is not the first enumerator}$
130        int ?<?( E l, E r );            $\C{// true if l is an enumerator before r}$
131        int ?<=?( E l, E r );           $\C{// true if l before or the same as r}$
132        int ?>?( E l, E r );            $\C{// true if l is an enumerator after r}$
133        int ?>=?( E l, E r );           $\C{// true if l after or the same as r}$         
134}
135\end{cfa}
136
137As an alternative, users can define the boolean conversion for CfaEnum:
138
139\begin{cfa}
140forall(E | CfaEnum(E))
141bool ?!=?(E lhs, zero_t) {
142        return posn(lhs) != 0;
143}
144\end{cfa}
145which effectively turns the first enumeration as a logical zero and non-zero for others.
146
147\begin{cfa}
148Count variable_a = First, variable_b = Second, variable_c = Third, variable_d = Fourth;
149p(variable_a); // 0
150p(variable_b); // 1
151p(variable_c); // "Third"
152p(variable_d); // 3
153\end{cfa}
154
155
156\section{Enumeration Variable}
157
158Although \CFA enumeration captures three different attributes, an enumeration instance does not store all this information.
159The @sizeof@ a \CFA enumeration instance is always 4 bytes, the same size as a C enumeration instance (@sizeof( int )@).
160It comes from the fact that:
161\begin{enumerate}
162\item
163a \CFA enumeration is always statically typed;
164\item
165it is always resolved as one of its attributes regarding real usage.
166\end{enumerate}
167When creating an enumeration instance @colour@ and assigning it with the enumerator @Color.Green@, the compiler allocates an integer variable and stores the position 1.
168The invocations of $positions()$, $value()$, and $label()$ turn into calls to special functions defined in the prelude:
169\begin{cfa}
170position( green );
171>>> position( Colour, 1 ) -> int
172value( green );
173>>> value( Colour, 1 ) -> T
174label( green );
175>>> label( Colour, 1) -> char *
176\end{cfa}
177@T@ represents the type declared in the \CFA enumeration defined and @char *@ in the example.
178These generated functions are $Companion Functions$, they take an $companion$ object and the position as parameters.
179
180
181\section{Enumeration Data}
182
183\begin{cfa}
184enum(T) E { ... };
185// backing data
186T * E_values;
187char ** E_labels;
188\end{cfa}
189Storing values and labels as arrays can sometimes help support enumeration features.
190However, the data structures are the overhead for the programs. We want to reduce the memory usage for enumeration support by:
191\begin{itemize}
192        \item Only generates the data array if necessary
193        \item The compilation units share the data structures.
194        No extra overhead if the data structures are requested multiple times.
195\end{itemize}
196
197
198\section{Unification}
199
200\section{Enumeration as Value}
201\label{section:enumeration_as_value}
202An \CFA enumeration with base type T can be used seamlessly as T, without explicitly calling the pseudo-function value.
203\begin{cfa}
204char * green_value = Colour.Green; // "G"
205// Is equivalent to
206// char * green_value = value( Color.Green ); "G"
207\end{cfa}
208
209
210\section{Unification Distance}
211
212\begin{cfa}
213T_2 Foo(T1);
214\end{cfa}
215The @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@.
216
217@path(A, B)@ is a compiler concept that returns one of the following:
218\begin{itemize}
219        \item Zero or 0, if and only if $A == B$.
220        \item Safe, if B can be used as A without losing its precision, or B is a subtype of A.
221        \item Unsafe, if B loses its precision when used as A, or A is a subtype of B.
222        \item Infinite, if B cannot be used as A. A is not a subtype of B and B is not a subtype of A.
223\end{itemize}
224
225For example, @path(int, int)==Zero@, @path(int, char)==Safe@, @path(int, double)==Unsafe@, @path(int, struct S)@ is @Infinite@ for @struct S{}@.
226@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$$.
227
228(Skip over the distance matrix here because it is mostly irrelevant for enumeration discussion. In the actual implementation, distance( E, T ) is 1.)
229
230The arithmetic of distance is the following:
231\begin{itemize}
232        \item $Zero + v= v$, for some value v.
233        \item $Safe * k <  Unsafe$, for finite k.
234        \item $Unsafe * k < Infinite$, for finite k.
235        \item $Infinite + v = Infinite$, for some value v.
236\end{itemize}
237
238For @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@.
239
240
241\section{Variable Overloading and Parameter Unification}
242
243\CFA allows variable names to be overloaded. It is possible to overload a variable that has type T and an enumeration with type T.
244\begin{cfa}
245char * green = "Green";
246Colour green = Colour.Green; // "G"
247
248void bar(char * s) { return s; }
249void foo(Colour c) { return value( c ); }
250
251foo( green ); // "G"
252bar( green ); // "Green"
253\end{cfa}
254\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 *@.
255
256\section{Function Overloading}
257Similarly, functions can be overloaded with different signatures. \CFA picks the correct function entity based on the distance between parameter types and the arguments.
258\begin{cfa}
259Colour green = Colour.Green;
260void foo(Colour c) { sout | "It is an enum"; } // First foo
261void foo(char * s) { sout | "It is a string"; } // Second foo
262foo( green ); // "It is an enum"
263\end{cfa}
264Because @distance(Colour, Colour)@ is @Zero@ and @distance(char *, Colour)@ is @Safe@, \CFA determines the @foo( green )@ is a call to the first foo.
265
266\section{Attributes Functions}
267The 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@.
268
269\begin{cfa}
270int s1;
271\end{cfa}
272The 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
273
274% \section{Unification and Resolution (this implementation will probably not be used, safe as reference for now)}
275
276% \begin{cfa}
277% enum Colour( char * ) { Red = "R", Green = "G", Blue = "B"  };
278% \end{cfa}
279% The @EnumInstType@ is convertible to other types.
280% A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
281% The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context.
282
283% \begin{cfa}[caption={Null Context}, label=lst:null_context]
284% {
285%       Colour.Green;
286% }
287% \end{cfa}
288% In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
289% In this case, any of the attributes is resolvable.
290% According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
291% The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
292% When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
293% \begin{cfa}[caption={Null Context Generated Code}, label=lst:null_context]
294% {
295%       "G";
296% }
297% \end{cfa}
298% \begin{cfa}[caption={int Context}, label=lst:int_context]
299% {
300%       int g = Colour.Green;
301% }
302% \end{cfa}
303% The assignment expression gives a context for the EnumInstType resolution.
304% The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
305% The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
306% In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
307% $$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
308% \begin{cfa}[label=lst:attr_resolution_1]
309% {
310%       Unify( int, char * ); // unify with the type of value
311%       Unify( int, int ); // unify with the type of position
312%       Unify( int, char * ); // unify with the type of label
313% }
314% \end{cfa}
315% \begin{cfa}[label=lst:attr_resolution_precedence]
316% {
317%       Unification( T1, EnumInstType<T2> ) {
318%               if ( Unify( T1, T2 ) ) return T2;
319%               if ( Unify( T1, int ) ) return int;
320%               if ( Unify( T1, char * ) ) return char *;
321%               Error: Cannot Unify T1 with EnumInstType<T2>;
322%       }
323% }
324% \end{cfa}
325% After the unification, @EnumInstType@ is replaced by its attributes.
326
327% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
328% {
329%       T2 foo ( T1 ); // function take variable with T1 as a parameter
330%       foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
331%       >>>> Unification( T1, EnumInstType<T3> )
332% }
333% \end{cfa}
334% % The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType.
335% Backward conversion:
336% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
337% {
338%       enum Colour colour = 1;
339% }
340% \end{cfa}
341
342% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
343% {
344%       Unification( EnumInstType<Colour>, int ) >>> label
345% }
346% \end{cfa}
347% @int@ can be unified with the label of Colour.
348% @5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into
349% \begin{cfa}
350% {
351%       enum Colour colour = Colour.Green;
352% }
353% \end{cfa}
354% Steps:
355% \begin{enumerate}
356% \item
357% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
358% \item
359% @unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
360% \item
361% return the enumeration constant at position 1
362% \end{enumerate}
363% \begin{cfa}
364% {
365%       enum T (int) { ... } // Declaration
366%       enum T t = 1;
367% }
368% \end{cfa}
369% Steps:
370% \begin{enumerate}
371% \item
372% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
373% \item
374% @unification( EnumInstType<Colour>, int )@: @value( EnumInstType< Colour > )@
375% \item
376% return the FIRST enumeration constant that has the value 1, by searching through the values array
377% \end{enumerate}
378% 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
379
380% \section{Casting}
381% Casting an EnumInstType to some other type T works similarly to unify the EnumInstType with T. For example:
382% \begin{cfa}
383% enum( int ) Foo { A = 10, B = 100, C = 1000 };
384% (int) Foo.A;
385% \end{cfa}
386% 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.
387
388% \section{Value Conversion}
389% 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.
390
391% \begin{cfa}
392% Foo a; // int a;
393% int j = a;
394% char * s = a;
395% \end{cfa}
396% 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
397% \begin{cfa}
398% int j = value( Foo, a )
399% \end{cfa}
400% Similarly, the generated code for the third line is
401% \begin{cfa}
402% char * j = label( Foo, a )
403% \end{cfa}
404
405
406\section{Enumerator Initialization}
407
408An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
409
410
411\section{C Enumeration Rule}
412
413A 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$.
414
415
416\section{Auto Initialization}
417
418C auto-initialization works for the integral type @int@ with constant expressions.
419\begin{cfa}
420enum Alphabet ! {
421        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,
422        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
423};
424\end{cfa}
425The complexity of the constant expression depends on the level of runtime computation the compiler implements, \eg \CC \lstinline[language={[GNU]C++}]{constexpr} provides complex compile-time computation across multiple types, which blurs the compilation/runtime boundary.
426
427The notion of auto-initialization can be generalized in \CFA through the trait @AutoInitializable@.
428\begin{cfa}
429forall(T) @trait@ AutoInitializable {
430        void ?{}( T & o, T v );                         $\C{// initialization}$
431        void ?{}( T & t, zero_t );                      $\C{// 0}$
432        T ?++( T & t);                                          $\C{// increment}$
433};
434\end{cfa}
435In addition, there is an implicit enumeration counter, @ecnt@ of type @T@, managed by the compiler.
436For example, the type @Odd@ satisfies @AutoInitializable@:
437\begin{cfa}
438struct Odd { int i; };
439void ?{}( Odd & o, int v ) { if ( v & 1 ) o.i = v; else /* error not odd */ ; };
440void ?{}( Odd & o, zero_t ) { o.i = 1; };
441Odd ?++( Odd o ) { return (Odd){ o.i + 2 }; };
442\end{cfa}
443and implicit initialization is available.
444\begin{cfa}
445enum( Odd ) { A, B, C = 7, D };                 $\C{// 1, 3, 7, 9}$
446\end{cfa}
447where the compiler performs the following transformation and runs the code.
448\begin{cfa}
449enum( Odd ) {
450        ?{}( ecnt, @0@ }  ?{}( A, ecnt },       ?++( ecnt )  ?{}( B, ecnt ),
451        ?{}( ecnt, 7 )  ?{}( C, ecnt ), ?++( ecnt )  ?{}( D, ecnt )
452};
453\end{cfa}
454
455Unfortunately, auto-initialization is not implemented because \CFA is only a transpiler, relying on generated C code to perform the detail work.
456C does not have the equivalent of \CC \lstinline[language={[GNU]C++}]{constexpr}, and it is currently beyond the scope of the \CFA project to implement a complex runtime interpreter in the transpiler.
457Nevertheless, the necessary language concepts exist to support this feature.
458
459
460\section{Enumeration Features}
461
462
463\section{Iteration and Range}
464
465It is convenient to iterate over a \CFA enumeration value, \eg:
466\begin{cfa}[label=lst:range_functions]
467for ( Alphabet alph; Alphabet ) { sout | alph; }
468>>> A B C ... D
469\end{cfa}
470The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
471@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
472
473\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
474\begin{cfa}[label=lst:range_functions]
475for ( Alphabet alph ) { sout | alph; }
476>>> A B C ... D
477\end{cfa}
478
479The 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.
480
481\textbullet\ H is implicit up-to exclusive range [0, H).
482\begin{cfa}[label=lst:range_function_1]
483for ( alph; Alphabet.D ) { sout | alph; }
484>>> A B C
485\end{cfa}
486
487\textbullet\ ~= H is implicit up-to inclusive range [0,H].
488\begin{cfa}[label=lst:range_function_2]
489for ( alph; ~= Alphabet.D ) { sout | alph; }
490>>> A B C D
491\end{cfa}
492
493\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
494\begin{cfa}[label=lst:range_function_3]
495for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
496// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
497>>> B C
498\end{cfa}
499
500\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
501\begin{cfa}[label=lst:range_function_4]
502for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
503>>> B C D
504\end{cfa}
505
506\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
507\begin{cfa}[label=lst:range_function_5]
508for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
509>>> D C
510\end{cfa}
511
512\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
513\begin{cfa}[label=lst:range_function_6]
514for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
515>>> D C B
516\end{cfa}
517
518A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
519\begin{cfa}[label=lst:range_function_stepping]
520enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
521for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
522>>> 10 12 14 16 18
523for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
524>>> 10 11 12 13 14 15 16 17 18
525\end{cfa}
526The 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
527\begin{cfa}[label=lst:range_function_stepping_converted]
528for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
529>>> 10 11 12 13 14 15 16 17 18
530\end{cfa}
531
532% \PAB{Explain what each loop does.}
533
534It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
535\begin{cfa}[label=lst:range_functions_label_implicit]
536for ( char * alph; Alphabet )
537\end{cfa}
538This 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.
539If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
540\begin{cfa}[label=lst:range_functions_label_implicit]
541for ( char * ch; labels( Alphabet ) )
542\end{cfa}
543
544
545% \section{Non-uniform Type}
546% TODO: Working in Progress, might need to change other sections. Conflict with the resolution right now.
547
548% \begin{cfa}
549% enum T( int, char * ) {
550%        a=42, b="Hello World"
551% };
552% \end{cfa}
553% The enum T declares two different types: int and char *. The enumerators of T hold values of one of the declared types.
554
555\section{Enumeration Inheritance}
556
557\begin{cfa}[label=lst:EnumInline]
558enum( char * ) Name { Jack = "Jack", Jill = "Jill" };
559enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
560\end{cfa}
561\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.
562\begin{cfa}[label=lst:EnumInline]
563Name Fred;
564void f( Name2 );
565f( Fred );
566\end{cfa}
567If enumeration A declares @inline B@ in its enumeration body, enumeration A is the "inlining enum" and enumeration B is the "inlined enum".
568
569An 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.
570\begin{cfa}[label=lst:EnumInline]
571enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
572// is equivalent to enum Name2 { Jack = "Jack", Jill="Jill", Sue = "Sue", Tom = "Tom" };
573\end{cfa}
574Name.Jack is equivalent to Name2.Jack. Their attributes are all identical. Opening both Name and Name2 in the same scope will not introduce ambiguity.
575\begin{cfa}[label=lst:EnumInline]
576with( Name, Name2 ) { Jack; } // Name.Jack and Name2.Jack are equivalent. No ambiguity
577\end{cfa}
578
579\section{Implementation}
580
581\section{Static Attribute Expression}
582\begin{cfa}[label=lst:static_attr]
583enum( char * ) Colour {
584        Red = "red", Blue = "blue", Green = "green"
585};
586\end{cfa}
587An 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.
588
589\section{Runtime Attribute Expression and Weak Referenced Data}
590\begin{cfa}[label=lst:dynamic_attr]
591Colour c;
592...
593value( c ); // or c
594\end{cfa}
595An 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.
596
597\CFA stores the variables and labels in @const@ arrays to provide runtime lookup for enumeration information.
598
599\begin{cfa}[label=lst:attr_array]
600const char * Colour_labels [3] = { "Red", "Blue", "Green" };
601const char * Colour_values [3] = { "red", "blue", "green" };
602\end{cfa}
603The \CFA compiles transforms the attribute expressions into array access.
604\begin{cfa}[label=lst:attr_array_access]
605position( c ) // c; an integer
606value( c ); // Colour_values[c]
607label( c ); // Colour_labels[c]
608\end{cfa}
609
610To 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.
611
612\section{Enum Prelude}
613
614\begin{cfa}[label=lst:enum_func_dec]
615forall( T ) {
616        unsigned position( unsigned );
617        T value( unsigned );
618        char * label( unsigned );
619}
620\end{cfa}
621\CFA loads the declaration of enumeration function from the enum.hfa.
622
623\section{Internal Representation}
624
625The 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:
626\begin{cfa}[label=lst:EnumDecl]
627forall(T)
628class EnumDecl {
629        T* values;
630        char** label;
631};
632\end{cfa}
633
634The internal representation of an enumeration constant is @EnumInstType@.
635An @EnumInstType@ has a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
636\begin{cfa}[label=lst:EnumInstType]
637class EnumInstType {
638        EnumDecl enumDecl;
639        int position;
640};
641\end{cfa}
642In 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>@.
643
644\begin{cfa}[caption={Enum Type Functions}, label=lst:cforall_enum_data]
645const T * const values;
646const char * label;
647int length;
648\end{cfa}
649Companion 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".
650Companion 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.
651
652
653% \section{(Rework) Companion Object and Companion Function}
654
655% \begin{cfa}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
656% forall( T )
657% struct Companion {
658%       const T * const values;
659%                const char * label;
660%       int length;
661% };
662% \end{cfa}
663% \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@.
664
665% The companion object is singleton across the compilation (investigation).
666
667% \CFA generates the definition of companion functions.
668% Because \CFA implicitly stores an enumeration instance as its position, the companion function @position@ does nothing but return the position it is passed.
669% Companions function @value@ and @label@ return the array item at the given position of @values@ and @labels@, respectively.
670% \begin{cfa}[label=lst:companion_definition]
671% int position( Companion o, int pos ) { return pos; }
672% T value( Companion o, int pos ) { return o.values[ pos ]; }
673% char * label( Companion o, int pos ) { return o.labels[ pos ]; }
674% \end{cfa}
675% Notably, the @Companion@ structure definition, and all companion objects, are visible to users.
676% 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@
677% \begin{cfa}[label=lst:companion_definition_values_labels]
678% Colour.values; // read the Companion's values
679% values( Colour ); // same as Colour.values
680% \end{cfa}
681
682\section{Companion Traits (experimental)}
683Not sure its semantics yet, and it might replace a companion object.
684\begin{cfa}[label=lst:companion_trait]
685forall(T1) {
686        trait Companion(otype T2<otype T1>) {
687                T1 value((otype T2<otype T1> const &);
688                int position(otype T2<otype T1> const &);
689                char * label(otype T2<otype T1> const &);
690        }
691}
692\end{cfa}
693All 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:
694
695\begin{enumerate}
696  \item The instance of enumeration has a single polymorphic type.
697  \item Each assertion should use the type once as a parameter.
698\end{enumerate}
699
700\begin{cfa}
701enum(int) Weekday {
702        Mon = 10, Tue, ...
703};
704
705T value( enum Weekday<T> & this);
706int position( enum Weekday<T> & this )
707char * label( enum Weekday<T> & this )
708
709trait Companion obj = (enum(int)) Workday.Weekday;
710value(obj); // 10
711\end{cfa}
712The 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.
713(...)
714
715\section{User Define Enumeration Functions}
716
717Companion objects make extending features for \CFA enumeration easy.
718\begin{cfa}[label=lst:companion_user_definition]
719char * charastic_string( Companion o, int position ) {
720        return sprintf( "Label: %s; Value: %s", label( o, position ), value( o, position) );
721}
722printf( charactic_string ( Color, 1 ) );
723>>> Label: Green; Value: G
724\end{cfa}
725Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.
726
727The \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.
728Therefore, a user can use the syntax with a user-defined enumeration function call:
729\begin{cfa}[label=lst:companion_user_definition]
730charactic_string( Color.Green ); // equivalent to charactic_string( Color, 1 )
731>>> Label: Green; Value: G
732\end{cfa}
733Similarly, the user can work with the enumeration type itself: (see section ref...)
734\begin{cfa}[ label=lst:companion_user_definition]
735void print_enumerators ( Companion o ) {
736        for ( c : Companion o ) {
737                sout | label (c) | value( c ) ;
738        }
739}
740print_enumerators( Colour );
741\end{cfa}
742
743
744\section{Declaration}
745
746The qualified enumeration syntax is dedicated to \CFA enumeration.
747\begin{cfa}[label=lst:range_functions]
748enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
749\end{cfa}
750A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
751During the $Validation$ pass, the compiler links the type declaration to the type's definition.
752It 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.
753If the declared type is not @AutoInitializable@, \CFA rejects the enumeration definition.
754Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section)
755
756\begin{cfa}[label=lst:init]
757struct T { ... };
758void ?{}( T & t, zero_t ) { ... };
759void ?{}( T & t, one_t ) { ... };
760T ?+?( T & lhs, T & rhs ) { ... };
761
762enum (T) Sample {
763        Zero: 0 /* zero_t */,
764        One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
765};
766\end{cfa}
767Challenge: \\
768The value of an enumerator, or the initializer, requires @const_expr@.
769While 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.
770Might not be able to implement a \emph{correct} static check.
771
772\CFA $autogens$ a Companion object for the declared enumeration.
773\begin{cfa}[label=lst:companion]
774Companion( T ) Sample {
775        .values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
776        .labels: { "Zero", "One", "Two", "Three", ...},
777        .length: /* number of enumerators */
778};
779\end{cfa}
780\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
781But the result is computed at run time, and the compiler ensures the @values@ are not changed.
782
783\section{Qualified Expression}
784
785\CFA uses qualified expression to address the scoping of \CFA-enumeration.
786\begin{cfa}[label=lst:qualified_expression]
787aggregation_name.field;
788\end{cfa}
789The qualified expression is not dedicated to \CFA enumeration.
790It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
791When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
792\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
793If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.
794
795\section{Instance Declaration}
796
797
798\begin{cfa}[label=lst:var_declaration]
799enum Sample s1;
800\end{cfa}
801
802The declaration \CFA-enumeration variable has the same syntax as the C-enumeration. Internally, such a variable will be represented as an EnumInstType.
Note: See TracBrowser for help on using the repository browser.