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

Last change on this file since e561551 was e561551, checked in by JiadaL <j82liang@…>, 6 weeks ago

Save current progress for pull

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