source: doc/theses/jiada_liang_MMath/implementation.tex @ 956299b

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

copy enum proposal to enum thesis

  • Property mode set to 100644
File size: 29.3 KB
Line 
1\chapter{Enumeration Implementation}
2
3
4\section{Enumeration Variable}
5
6Although \CFA enumeration captures three different attributes, an enumeration instance does not store all this information.
7The @sizeof@ a \CFA enumeration instance is always 4 bytes, the same size as a C enumeration instance (@sizeof( int )@).
8It comes from the fact that:
9\begin{enumerate}
10\item
11a \CFA enumeration is always statically typed;
12\item
13it is always resolved as one of its attributes regarding real usage.
14\end{enumerate}
15When creating an enumeration instance @colour@ and assigning it with the enumerator @Color.Green@, the compiler allocates an integer variable and stores the position 1.
16The invocations of $positions()$, $value()$, and $label()$ turn into calls to special functions defined in the prelude:
17\begin{cfa}
18position( green );
19>>> position( Colour, 1 ) -> int
20value( green );
21>>> value( Colour, 1 ) -> T
22label( green );
23>>> label( Colour, 1) -> char *
24\end{cfa}
25@T@ represents the type declared in the \CFA enumeration defined and @char *@ in the example.
26These generated functions are $Companion Functions$, they take an $companion$ object and the position as parameters.
27
28
29\section{Enumeration Data}
30
31\begin{cfa}
32enum(T) E { ... };
33// backing data
34T * E_values;
35char ** E_labels;
36\end{cfa}
37Storing values and labels as arrays can sometimes help support enumeration features.
38However, the data structures are the overhead for the programs. We want to reduce the memory usage for enumeration support by:
39\begin{itemize}
40        \item Only generates the data array if necessary
41        \item The compilation units share the data structures.
42        No extra overhead if the data structures are requested multiple times.
43\end{itemize}
44
45
46\section{Unification}
47
48\section{Enumeration as Value}
49\label{section:enumeration_as_value}
50An \CFA enumeration with base type T can be used seamlessly as T, without explicitly calling the pseudo-function value.
51\begin{cfa}
52char * green_value = Colour.Green; // "G"
53// Is equivalent to
54// char * green_value = value( Color.Green ); "G"
55\end{cfa}
56
57
58\section{Unification Distance}
59
60\begin{cfa}
61T_2 Foo(T1);
62\end{cfa}
63The @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@.
64
65@path(A, B)@ is a compiler concept that returns one of the following:
66\begin{itemize}
67        \item Zero or 0, if and only if $A == B$.
68        \item Safe, if B can be used as A without losing its precision, or B is a subtype of A.
69        \item Unsafe, if B loses its precision when used as A, or A is a subtype of B.
70        \item Infinite, if B cannot be used as A. A is not a subtype of B and B is not a subtype of A.
71\end{itemize}
72
73For example, @path(int, int)==Zero@, @path(int, char)==Safe@, @path(int, double)==Unsafe@, @path(int, struct S)@ is @Infinite@ for @struct S{}@.
74@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$$.
75
76(Skip over the distance matrix here because it is mostly irrelevant for enumeration discussion. In the actual implementation, distance( E, T ) is 1.)
77
78The arithmetic of distance is the following:
79\begin{itemize}
80        \item $Zero + v= v$, for some value v.
81        \item $Safe * k <  Unsafe$, for finite k.
82        \item $Unsafe * k < Infinite$, for finite k.
83        \item $Infinite + v = Infinite$, for some value v.
84\end{itemize}
85
86For @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@.
87
88
89\section{Variable Overloading and Parameter Unification}
90
91\CFA allows variable names to be overloaded. It is possible to overload a variable that has type T and an enumeration with type T.
92\begin{cfa}
93char * green = "Green";
94Colour green = Colour.Green; // "G"
95
96void bar(char * s) { return s; }
97void foo(Colour c) { return value( c ); }
98
99foo( green ); // "G"
100bar( green ); // "Green"
101\end{cfa}
102\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 *@.
103
104\section{Function Overloading}
105Similarly, functions can be overloaded with different signatures. \CFA picks the correct function entity based on the distance between parameter types and the arguments.
106\begin{cfa}
107Colour green = Colour.Green;
108void foo(Colour c) { sout | "It is an enum"; } // First foo
109void foo(char * s) { sout | "It is a string"; } // Second foo
110foo( green ); // "It is an enum"
111\end{cfa}
112Because @distance(Colour, Colour)@ is @Zero@ and @distance(char *, Colour)@ is @Safe@, \CFA determines the @foo( green )@ is a call to the first foo.
113
114\section{Attributes Functions}
115The 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@.
116
117\begin{cfa}
118int s1;
119\end{cfa}
120The 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
121
122% \section{Unification and Resolution (this implementation will probably not be used, safe as reference for now)}
123
124% \begin{cfa}
125% enum Colour( char * ) { Red = "R", Green = "G", Blue = "B"  };
126% \end{cfa}
127% The @EnumInstType@ is convertible to other types.
128% A \CFA enumeration expression is implicitly \emph{overloaded} with its three different attributes: value, position, and label.
129% The \CFA compilers need to resolve an @EnumInstType@ as one of its attributes based on the current context.
130
131% \begin{cfa}[caption={Null Context}, label=lst:null_context]
132% {
133%       Colour.Green;
134% }
135% \end{cfa}
136% In example~\ref{lst:null_context}, the environment gives no information to help with the resolution of @Colour.Green@.
137% In this case, any of the attributes is resolvable.
138% According to the \textit{precedence rule}, the expression with @EnumInstType@ resolves as @value( Colour.Green )@.
139% The @EnumInstType@ is converted to the type of the value, which is statically known to the compiler as @char *@.
140% When the compilation reaches the code generation, the compiler outputs code for type @char *@ with the value @"G"@.
141% \begin{cfa}[caption={Null Context Generated Code}, label=lst:null_context]
142% {
143%       "G";
144% }
145% \end{cfa}
146% \begin{cfa}[caption={int Context}, label=lst:int_context]
147% {
148%       int g = Colour.Green;
149% }
150% \end{cfa}
151% The assignment expression gives a context for the EnumInstType resolution.
152% The EnumInstType is used as an @int@, and \CFA needs to determine which of the attributes can be resolved as an @int@ type.
153% The functions $Unify( T1, T2 ): bool$ take two types as parameters and determine if one type can be used as another.
154% In example~\ref{lst:int_context}, the compiler is trying to unify @int@ and @EnumInstType@ of @Colour@.
155% $$Unification( int, EnumInstType<Colour> )$$ which turns into three Unification call
156% \begin{cfa}[label=lst:attr_resolution_1]
157% {
158%       Unify( int, char * ); // unify with the type of value
159%       Unify( int, int ); // unify with the type of position
160%       Unify( int, char * ); // unify with the type of label
161% }
162% \end{cfa}
163% \begin{cfa}[label=lst:attr_resolution_precedence]
164% {
165%       Unification( T1, EnumInstType<T2> ) {
166%               if ( Unify( T1, T2 ) ) return T2;
167%               if ( Unify( T1, int ) ) return int;
168%               if ( Unify( T1, char * ) ) return char *;
169%               Error: Cannot Unify T1 with EnumInstType<T2>;
170%       }
171% }
172% \end{cfa}
173% After the unification, @EnumInstType@ is replaced by its attributes.
174
175% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
176% {
177%       T2 foo ( T1 ); // function take variable with T1 as a parameter
178%       foo( EnumInstType<T3> ); // Call foo with a variable has type EnumInstType<T3>
179%       >>>> Unification( T1, EnumInstType<T3> )
180% }
181% \end{cfa}
182% % The conversion can work backward: in restrictive cases, attributes of can be implicitly converted back to the EnumInstType.
183% Backward conversion:
184% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
185% {
186%       enum Colour colour = 1;
187% }
188% \end{cfa}
189
190% \begin{cfa}[caption={Unification Functions}, label=lst:unification_func_call]
191% {
192%       Unification( EnumInstType<Colour>, int ) >>> label
193% }
194% \end{cfa}
195% @int@ can be unified with the label of Colour.
196% @5@ is a constant expression $\Rightarrow$ Compiler knows the value during the compilation $\Rightarrow$ turns it into
197% \begin{cfa}
198% {
199%       enum Colour colour = Colour.Green;
200% }
201% \end{cfa}
202% Steps:
203% \begin{enumerate}
204% \item
205% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
206% \item
207% @unification( EnumInstType<Colour>, int )@: @position( EnumInstType< Colour > )@
208% \item
209% return the enumeration constant at position 1
210% \end{enumerate}
211% \begin{cfa}
212% {
213%       enum T (int) { ... } // Declaration
214%       enum T t = 1;
215% }
216% \end{cfa}
217% Steps:
218% \begin{enumerate}
219% \item
220% identify @1@ as a constant expression with type @int@, and the value is statically known as @1@
221% \item
222% @unification( EnumInstType<Colour>, int )@: @value( EnumInstType< Colour > )@
223% \item
224% return the FIRST enumeration constant that has the value 1, by searching through the values array
225% \end{enumerate}
226% 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
227
228% \section{Casting}
229% Casting an EnumInstType to some other type T works similarly to unify the EnumInstType with T. For example:
230% \begin{cfa}
231% enum( int ) Foo { A = 10, B = 100, C = 1000 };
232% (int) Foo.A;
233% \end{cfa}
234% 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.
235
236% \section{Value Conversion}
237% 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.
238
239% \begin{cfa}
240% Foo a; // int a;
241% int j = a;
242% char * s = a;
243% \end{cfa}
244% 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
245% \begin{cfa}
246% int j = value( Foo, a )
247% \end{cfa}
248% Similarly, the generated code for the third line is
249% \begin{cfa}
250% char * j = label( Foo, a )
251% \end{cfa}
252
253
254\section{Enumerator Initialization}
255An enumerator must have a deterministic immutable value, either be explicitly initialized in the enumeration definition, or implicitly initialized by rules.
256
257\section{C Enumeration Rule}
258A 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$.
259
260\section{Auto Initializable}
261\label{s:AutoInitializable}
262
263
264\CFA enumerations have the same rule in enumeration constant initialization.
265However, only \CFA types that have defined traits for @zero_t@, @one_t@, and an addition operator can be automatically initialized by \CFA.
266
267Specifically, a type is auto-initializable only if it satisfies the trait @AutoInitializable@:
268\begin{cfa}
269forall(T)
270trait AutoInitializable {
271        void ?()( T & t, zero_t );
272        S ?++( T & t);
273};
274\end{cfa}
275An example of a user-defined @AutoInitializable@ is:
276\begin{cfa}[label=lst:sample_auto_Initializable]
277struct Odd { int i; };
278void ?()( Odd & t, zero_t ) { t.i = 1; };
279Odd ?++( Odd t1 ) { return Odd( t1.i + 2); };
280\end{cfa}
281When the type of an enumeration is @AutoInitializable@, implicit initialization is available.
282\begin{cfa}[label=lst:sample_auto_Initializable_usage]
283enum AutoInitUsage(Odd) {
284        A, B, C = 7, D
285};
286\end{cfa}
287In 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.
288@B@ and @D@ have the values of their $predecessor++$, where @one_t@ has the value 2.
289Therefore, the enumeration is initialized as follows:
290\begin{cfa}[label=lst:sample_auto_Initializable_usage_gen]
291enum AutoInitUsage(Odd) {
292        A = 1, B = 3, C = 7, D = 9
293};
294\end{cfa}
295Note that there is no mechanism to prevent an even value for the direct initialization, such as @C = 6@.
296
297In \CFA, character, integral, float, and imaginary types are all @AutoInitialiable@.
298\begin{cfa}[label=lst:letter]
299enum Alphabet( int ) {
300        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,
301        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
302};
303print( "%c, %c, %c", Alphabet.F, Alphabet.o, Alphabet.z );
304>>> F, o, z
305\end{cfa}
306\section{Enumeration Features}
307\section{Iteration and Range}
308
309It is convenient to iterate over a \CFA enumeration value, e.g.:
310\begin{cfa}[label=lst:range_functions]
311for ( Alphabet alph; Alphabet ) { sout | alph; }
312>>> A B C ... D
313\end{cfa}
314The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
315@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
316
317\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
318\begin{cfa}[label=lst:range_functions]
319for ( Alphabet alph ) { sout | alph; }
320>>> A B C ... D
321\end{cfa}
322
323The 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.
324
325\textbullet\ H is implicit up-to exclusive range [0, H).
326\begin{cfa}[label=lst:range_function_1]
327for ( alph; Alphabet.D ) { sout | alph; }
328>>> A B C
329\end{cfa}
330
331\textbullet\ ~= H is implicit up-to inclusive range [0,H].
332\begin{cfa}[label=lst:range_function_2]
333for ( alph; ~= Alphabet.D ) { sout | alph; }
334>>> A B C D
335\end{cfa}
336
337\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
338\begin{cfa}[label=lst:range_function_3]
339for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
340// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
341>>> B C
342\end{cfa}
343
344\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
345\begin{cfa}[label=lst:range_function_4]
346for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
347>>> B C D
348\end{cfa}
349
350\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
351\begin{cfa}[label=lst:range_function_5]
352for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
353>>> D C
354\end{cfa}
355
356\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
357\begin{cfa}[label=lst:range_function_6]
358for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
359>>> D C B
360\end{cfa}
361
362A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
363\begin{cfa}[label=lst:range_function_stepping]
364enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
365for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
366>>> 10 12 14 16 18
367for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
368>>> 10 11 12 13 14 15 16 17 18
369\end{cfa}
370The 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
371\begin{cfa}[label=lst:range_function_stepping_converted]
372for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
373>>> 10 11 12 13 14 15 16 17 18
374\end{cfa}
375
376% \PAB{Explain what each loop does.}
377
378It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
379\begin{cfa}[label=lst:range_functions_label_implicit]
380for ( char * alph; Alphabet )
381\end{cfa}
382This 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.
383If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
384\begin{cfa}[label=lst:range_functions_label_implicit]
385for ( char * ch; labels( Alphabet ) )
386\end{cfa}
387
388
389% \section{Non-uniform Type}
390% TODO: Working in Progress, might need to change other sections. Conflict with the resolution right now.
391
392% \begin{cfa}
393% enum T( int, char * ) {
394%        a=42, b="Hello World"
395% };
396% \end{cfa}
397% The enum T declares two different types: int and char *. The enumerators of T hold values of one of the declared types.
398
399\section{Enumeration Inheritance}
400
401\begin{cfa}[label=lst:EnumInline]
402enum( char * ) Name { Jack = "Jack", Jill = "Jill" };
403enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
404\end{cfa}
405\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.
406\begin{cfa}[label=lst:EnumInline]
407Name Fred;
408void f( Name2 );
409f( Fred );
410\end{cfa}
411If enumeration A declares @inline B@ in its enumeration body, enumeration A is the "inlining enum" and enumeration B is the "inlined enum".
412
413An 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.
414\begin{cfa}[label=lst:EnumInline]
415enum /* inferred */ Name2 { inline Name, Sue = "Sue", Tom = "Tom" };
416// is equivalent to enum Name2 { Jack = "Jack", Jill="Jill", Sue = "Sue", Tom = "Tom" };
417\end{cfa}
418Name.Jack is equivalent to Name2.Jack. Their attributes are all identical. Opening both Name and Name2 in the same scope will not introduce ambiguity.
419\begin{cfa}[label=lst:EnumInline]
420with( Name, Name2 ) { Jack; } // Name.Jack and Name2.Jack are equivalent. No ambiguity
421\end{cfa}
422
423\section{Implementation}
424
425\section{Static Attribute Expression}
426\begin{cfa}[label=lst:static_attr]
427enum( char * ) Colour {
428        Red = "red", Blue = "blue", Green = "green"
429};
430\end{cfa}
431An 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.
432
433\section{Runtime Attribute Expression and Weak Referenced Data}
434\begin{cfa}[label=lst:dynamic_attr]
435Colour c;
436...
437value( c ); // or c
438\end{cfa}
439An 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.
440
441\CFA stores the variables and labels in @const@ arrays to provide runtime lookup for enumeration information.
442
443\begin{cfa}[label=lst:attr_array]
444const char * Colour_labels [3] = { "Red", "Blue", "Green" };
445const char * Colour_values [3] = { "red", "blue", "green" };
446\end{cfa}
447The \CFA compiles transforms the attribute expressions into array access.
448\begin{cfa}[label=lst:attr_array_access]
449position( c ) // c; an integer
450value( c ); // Colour_values[c]
451label( c ); // Colour_labels[c]
452\end{cfa}
453
454To 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.
455
456\section{Enum Prelude}
457
458\begin{cfa}[label=lst:enum_func_dec]
459forall( T ) {
460        unsigned position( unsigned );
461        T value( unsigned );
462        char * label( unsigned );
463}
464\end{cfa}
465\CFA loads the declaration of enumeration function from the enum.hfa.
466
467\section{Internal Representation}
468
469The 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:
470\begin{cfa}[label=lst:EnumDecl]
471forall(T)
472class EnumDecl {
473        T* values;
474        char** label;
475};
476\end{cfa}
477
478The internal representation of an enumeration constant is @EnumInstType@.
479An @EnumInstType@ has a reference to the \CFA-enumeration declaration and the position of the enumeration constant.
480\begin{cfa}[label=lst:EnumInstType]
481class EnumInstType {
482        EnumDecl enumDecl;
483        int position;
484};
485\end{cfa}
486In 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>@.
487
488\begin{cfa}[caption={Enum Type Functions}, label=lst:cforall_enum_data]
489const T * const values;
490const char * label;
491int length;
492\end{cfa}
493Companion 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".
494Companion 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.
495
496
497% \section{(Rework) Companion Object and Companion Function}
498
499% \begin{cfa}[caption={Enum Type Functions}, label=lst:cforall_enum_functions]
500% forall( T )
501% struct Companion {
502%       const T * const values;
503%                const char * label;
504%       int length;
505% };
506% \end{cfa}
507% \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@.
508
509% The companion object is singleton across the compilation (investigation).
510
511% \CFA generates the definition of companion functions.
512% Because \CFA implicitly stores an enumeration instance as its position, the companion function @position@ does nothing but return the position it is passed.
513% Companions function @value@ and @label@ return the array item at the given position of @values@ and @labels@, respectively.
514% \begin{cfa}[label=lst:companion_definition]
515% int position( Companion o, int pos ) { return pos; }
516% T value( Companion o, int pos ) { return o.values[ pos ]; }
517% char * label( Companion o, int pos ) { return o.labels[ pos ]; }
518% \end{cfa}
519% Notably, the @Companion@ structure definition, and all companion objects, are visible to users.
520% 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@
521% \begin{cfa}[label=lst:companion_definition_values_labels]
522% Colour.values; // read the Companion's values
523% values( Colour ); // same as Colour.values
524% \end{cfa}
525
526\section{Companion Traits (experimental)}
527Not sure its semantics yet, and it might replace a companion object.
528\begin{cfa}[label=lst:companion_trait]
529forall(T1) {
530        trait Companion(otype T2<otype T1>) {
531                T1 value((otype T2<otype T1> const &);
532                int position(otype T2<otype T1> const &);
533                char * label(otype T2<otype T1> const &);
534        }
535}
536\end{cfa}
537All 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:
538
539\begin{enumerate}
540  \item The instance of enumeration has a single polymorphic type.
541  \item Each assertion should use the type once as a parameter.
542\end{enumerate}
543
544\begin{cfa}
545enum(int) Weekday {
546        Monday=10, Tuesday, ...
547};
548
549T value( enum Weekday<T> & this);
550int position( enum Weekday<T> & this )
551char * label( enum Weekday<T> & this )
552
553trait Companion obj = (enum(int)) Workday.Weekday;
554value(obj); // 10
555\end{cfa}
556The 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.
557(...)
558
559\section{User Define Enumeration Functions}
560
561Companion objects make extending features for \CFA enumeration easy.
562\begin{cfa}[label=lst:companion_user_definition]
563char * charastic_string( Companion o, int position ) {
564        return sprintf( "Label: %s; Value: %s", label( o, position ), value( o, position) );
565}
566printf( charactic_string ( Color, 1 ) );
567>>> Label: Green; Value: G
568\end{cfa}
569Defining a function takes a Companion object effectively defines functions for all \CFA enumeration.
570
571The \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.
572Therefore, a user can use the syntax with a user-defined enumeration function call:
573\begin{cfa}[label=lst:companion_user_definition]
574charactic_string( Color.Green ); // equivalent to charactic_string( Color, 1 )
575>>> Label: Green; Value: G
576\end{cfa}
577Similarly, the user can work with the enumeration type itself: (see section ref...)
578\begin{cfa}[ label=lst:companion_user_definition]
579void print_enumerators ( Companion o ) {
580        for ( c : Companion o ) {
581                sout | label (c) | value( c ) ;
582        }
583}
584print_enumerators( Colour );
585\end{cfa}
586
587
588\section{Declaration}
589
590The qualified enumeration syntax is dedicated to \CFA enumeration.
591\begin{cfa}[label=lst:range_functions]
592enum (type_declaration) name { enumerator = const_expr, enumerator = const_expr, ... }
593\end{cfa}
594A compiler stores the name, the underlying type, and all enumerators in an @enumeration table@.
595During the $Validation$ pass, the compiler links the type declaration to the type's definition.
596It 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.
597If the declared type is not @AutoInitializable@, \CFA rejects the enumeration definition.
598Otherwise, it attempts to initialize enumerators with the enumeration initialization pattern. (a reference to a future initialization pattern section)
599
600\begin{cfa}[label=lst:init]
601struct T { ... };
602void ?{}( T & t, zero_t ) { ... };
603void ?{}( T & t, one_t ) { ... };
604T ?+?( T & lhs, T & rhs ) { ... };
605
606enum (T) Sample {
607        Zero: 0 /* zero_t */,
608        One: Zero + 1 /* ?+?( Zero, one_t ) */ , ...
609};
610\end{cfa}
611Challenge: \\
612The value of an enumerator, or the initializer, requires @const_expr@.
613While 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.
614Might not be able to implement a \emph{correct} static check.
615
616\CFA $autogens$ a Companion object for the declared enumeration.
617\begin{cfa}[label=lst:companion]
618Companion( T ) Sample {
619        .values: { 0, 0+1, 0+1+1, 0+1+1+1, ... }, /* 0: zero_t, 1: one_t, +: ?+?{} */
620        .labels: { "Zero", "One", "Two", "Three", ...},
621        .length: /* number of enumerators */
622};
623\end{cfa}
624\CFA stores values as intermediate expressions because the result of the function call to the function @?+?{}(T&, T&)@ is statically unknown to \CFA.
625But the result is computed at run time, and the compiler ensures the @values@ are not changed.
626
627\section{Qualified Expression}
628
629\CFA uses qualified expression to address the scoping of \CFA-enumeration.
630\begin{cfa}[label=lst:qualified_expression]
631aggregation_name.field;
632\end{cfa}
633The qualified expression is not dedicated to \CFA enumeration.
634It is a feature that is supported by other aggregation in \CFA as well, including a C enumeration.
635When C enumerations are unscoped, the qualified expression syntax still helps to disambiguate names in the context.
636\CFA recognizes if the expression references a \CFA aggregation by searching the presence of @aggregation_name@ in the \CFA enumeration table.
637If the @aggregation_name@ is identified as a \CFA enumeration, the compiler checks if @field@ presents in the declared \CFA enumeration.
638
639\section{Instance Declaration}
640
641
642\begin{cfa}[label=lst:var_declaration]
643enum Sample s1;
644\end{cfa}
645
646The 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.