source: doc/theses/jiada_liang_MMath/trait.tex @ 21f4dff

Last change on this file since 21f4dff was 21f4dff, checked in by JiadaL <j82liang@…>, 4 months ago

Add motivation for trait

  • Property mode set to 100644
File size: 12.9 KB
Line 
1\chapter{Enumeration Traits}
2\label{c:trait}
3
4% Despite parametric polymorphism being a pivotal feature of \CFA, for a long time, there was not
5% a technique to write functions being polymorphic over enumerated types.
6\CC introduced @std::is_enum@ trait on \CC{11} and @concepts@ on \CC{20}; with the combination, users can
7write function polymorphic over enumerated type in \CC:
8\begin{cfa}
9#include <type_traits>
10
11template<typename T>
12@concept Enumerable = std::is_enum<T>::value;@
13
14template<@Enumerable@ T>
15void f(T) {}
16\end{cfa}
17The @std::is_enum@ and other \CC @traits@ are a compile-time interfaces to query type information.
18While named the same as @trait@, it is orthogonal to \CFA trait, as the latter being defined as
19a collection of assertion to be satisfied by a polymorphic type.
20
21\CFA provides @CfaEnum@ and @TypedEnum@ traits to supports polymorphic functions for \CFA enumeration:
22\begin{cfa}
23forall(T | @CfaEnum(T)@)
24void f(T) {}
25\end{cfa}
26
27\section{CfaEnum and TypedEnum}
28\CFA defines attribute functions @label()@ and @posn()@ for all \CFA enumerations,
29and therefore \CFA enumerations fulfills the type assertions with the combination.
30With the observation, we define trait @CfaEnum@:
31\begin{cfa}
32forall( E ) trait CfaEnum {
33        const char * @label@( E e );
34        unsigned int @posn@( E e );
35};
36\end{cfa}
37
38% The trait @TypedEnum@ extends @CfaEnum@ with an additional value() assertion:
39Typed enumerations are \CFA enumeration with an additional @value@ attribute. Extending
40CfaEnum traits, TypedEnum is a subset of CFAEnum that implements attribute function @value()@,
41which includes all typed enumerations.
42\begin{cfa}
43forall( E, V | CfaEnum( E ) ) trait TypedEnum {
44        V @value@( E e );
45};
46\end{cfa}
47Type parameter V of TypedEnum trait binds to return type of @value()@, which is also the base
48type for typed enumerations. CfaEnum and TypedEnum triats constitues a CfaEnum function interfaces, as well a way to define functions
49over all CfaEnum enumerations.
50\begin{cfa}
51// for all type E that implements value() to return type T, where T is a type that convertible to string
52forall(  E, T | TypedEnum( E, T ) | { ?{}(string &, T ); } )
53string format_enum( E e ) { return label(E) + "(" + string(value(e)) + ")"; }
54
55// int is convertible to string; implemented in the standard library
56enum(int) RGB { Red = 0xFF0000, Green = 0x00FF00, Blue = 0x0000FF };
57
58struct color_code { int R; int G; int B };
59// Implement color_code to string conversion
60?{}(string & this, struct color_code p ) {
61        this = string(p.R) + ',' + string(p.G) + ',' + string(p.B);
62}
63enum(color_code) Rainbow {
64        Red = {255, 0, 0}, Orange = {255, 127, 0}, Yellow = {255, 255, 0}, Green = {0, 255, 0},
65        Blue = {0, 0, 255}, Indigo = {75, 0, 130}, Purple = {148, 0, 211}
66};
67
68format_enum(RGB.Green); // "Green(65280)"
69format_enum(Rainbow.Green); // "Green(0,255,0)"
70\end{cfa}
71
72
73% Not only CFA enumerations can be used with CfaEnum trait, other types that satisfy
74% CfaEnum assertions are all valid.
75Types does not need be defined as \CFA enumerations to work with CfaEnum traits. CfaEnum applies to any type
76with @label()@ and @value()@ being properly defined.
77Here is an example on how to extend a C enumeration to comply CfaEnum traits:
78\begin{cfa}
79enum Fruit { Apple, Banana, Cherry };                   $\C{// C enum}$
80const char * label( Fruit f ) {
81        choose( f ) {
82                case Apple: return "Apple";
83                case Banana: return "Banana";
84                case Cherry: return "Cherry";
85        }
86}
87unsigned posn( Fruit f ) { return f; } 
88char value( Fruit f ) { 
89        choose(f)  {
90                case Apple: return 'a';
91                case Banana: return 'b';
92                case Cherry: return 'c';
93        }
94}
95
96format_enum(Cherry); // "Cherry(c)"
97\end{cfa}
98
99\subsection{Bounded and Serial}
100A bounded type defines a lower bound and a upper bound.
101\begin{cfa}
102forall( E ) trait Bounded {
103        E lowerBound();
104        E lowerBound();
105};
106
107\end{cfa}
108Both Bounded functions are implement for \CFA enumerations, with @lowerBound()@ returning the first enumerator and @upperBound()@ returning
109the last enumerator.
110\begin{cfa}
111Workday day = lowerBound();                                     $\C{// Mon}$
112Planet outermost = upperBound();                                $\C{// NEPTUNE}$
113\end{cfa}
114
115The lowerBound() and upperBound() are functions overloaded on return type only, means their type resolution solely depend on the outer context,
116including expected type as a function argument, or the left hand size of an assignment expression.
117Calling either function without a context results in a type ambiguity, except in the rare case where the type environment has only one
118type overloads the functions, including \CFA enumerations, which has Bounded functions automatic defined.
119\begin{cfa}
120@lowerBound();@                 $\C{// ambiguous as both Workday and Planet implement Bounded}$
121sout | @lowerBound()@;
122Workday day = first();          $\C{// day provides type Workday}$
123void foo( Planet p );
124foo( last() );                      $\C{// argument provides type Planet}$
125\end{cfa}
126
127@Serial@ is a subset of @Bounded@, with functions maps elements against integers, as well implements a sequential order between members.
128\begin{cfa}
129forall( E | Bounded( E ) ) trait Serial {
130        unsigned fromInstance( E e );
131        E fromInt( unsigned int i );
132        E succ( E e );
133        E pred( E e );
134        unsigned Countof( E e );
135};
136\end{cfa}
137
138% A Serail type can project to an unsigned @int@ type, \ie an instance of type T has a corresponding integer value.
139Function @fromInstance()@ projects a @Bounded@ member to a number and @fromInt@ is the inverser. Function @succ()@ take an element, returns the "next"
140member in sequential order and @pred()@ returns the "last" member.
141
142A Serial type E may not be having a one-to-one mapping to integer because of bound. An integer that cannot be mapping to a member of E is called the member \newterm{out of bound}.
143Calling @succ()@ on @upperBound@ or @pred()@ on @lowerBound()@ results in out of bound.
144
145\CFA implements Serial interface for CFA enumerations with \newterm{bound check} on @fromInt()@, @succ()@ and @pred()@, and abort the program if the function call results in out of bound.
146Unlike a cast, conversion between \CFA enumeration and integer with @Serial@ interface is type safe.
147Specifically for @fromInt@, \CFA abort if input i smaller than @fromInstance(lowerBound())@ or greater than @fromInstance(upperBound())@
148
149Function @Countof@ takes an object as a parameter and returns the number of elements in the Serial type, which is @fromInstance( upper ) - fromInstance( lower ) + 1@.
150@Countof@ does not use its arugment as procedural input; it needs
151an argument to anchor its polymorphic type T.
152
153\CFA has an expression @countof@ (lower case) that returns the number of enumerators defined for enumerations.
154\begin{cfa}
155enum RGB {Red, Green, Blue};
156countof( RGB ); // (1)
157countof( Red ); // (2)
158\end{cfa}
159Both expressions from the previous example are converted to constant expression @3@ with no function call at runtime.
160@countof@ also works for any type T that defines @Countof@ and @lowerBound@, for which it turns into
161a function call @Countof( T )@. The resolution step on expression @countof(e)@ works as the following with priority ordered:
162\begin{enumerate}
163\item Looks for an enumeration named e, such as @enum e {... }@.
164If such an enumeration e exists, \CFA replace @countof(e)@  with constant expression with number of enumerator of e.
165\item Looks for a non-enumeration type named e that defines @Countof@ and @lowerBound@, including e being a polymorphic type, such as @forall(e)@.
166If type e exists, \CFA replaces it with @Countof(lowerBound())@, where lowerBound() is bounded to type e. 
167\item Looks for an enumerator e that defined in enumeration E. If such an enumeration e exists, \CFA replace @countof(e)@ with constant expression with number of enumerator of E.
168\item Looks for a name e in the context with expression type E. If such name e exists, \CFA replace @countof(e)@ with function call @Countof(e)@.
169\item If 1-4 fail, \CFA reports a type error on expression @countof(e)@.
170\end{enumerate}
171
172With the @Bounded@ and @Serial@, a loop over enumeration can be implemented in the following ways:
173\begin{cfa}
174enum() E { ... }
175for( unsigned i = 0; i < countof(E); i++ ) { ... }
176for( E e = lowerBound(); ; e = succ(e) ) { ...; if (e == upperBound()) break; }
177
178forall( T ) {
179        for( unsigned i = 0; i < countof(T); i++ ) { ... }
180        for( T e = lowerBound(); ; e = succ(e) ) { ...; if (e == upperBound()) break; }
181}
182\end{cfa}
183
184Finally, there is an associated trait defining comparison operators among enumerators.
185\begin{cfa}
186forall( E, T | CfaEnum( E, T ) ) {
187        // comparison
188        int ?==?( E l, E r );           $\C{// true if l and r are same enumerators}$
189        int ?!=?( E l, E r );           $\C{// true if l and r are different enumerators}$
190        int ?!=?( E l, zero_t );        $\C{// true if l is not the first enumerator}$
191        int ?<?( E l, E r );            $\C{// true if l is an enumerator before r}$
192        int ?<=?( E l, E r );           $\C{// true if l before or the same as r}$
193        int ?>?( E l, E r );            $\C{// true if l is an enumerator after r}$
194        int ?>=?( E l, E r );           $\C{// true if l after or the same as r}$         
195}
196\end{cfa}
197
198As an alternative, users can define the boolean conversion for CfaEnum:
199
200\begin{cfa}
201forall(E | CfaEnum(E))
202bool ?!=?(E lhs, zero_t) {
203        return posn(lhs) != 0;
204}
205\end{cfa}
206which effectively turns the first enumeration as a logical zero and non-zero for others.
207
208\begin{cfa}
209Count variable_a = First, variable_b = Second, variable_c = Third, variable_d = Fourth;
210p(variable_a); // 0
211p(variable_b); // 1
212p(variable_c); // "Third"
213p(variable_d); // 3
214\end{cfa}
215
216
217\section{Iteration and Range}
218
219It is convenient to iterate over a \CFA enumeration value, \eg:
220\begin{cfa}[label=lst:range_functions]
221for ( Alphabet alph; Alphabet ) { sout | alph; }
222>>> A B C ... D
223\end{cfa}
224The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
225@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
226
227\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
228\begin{cfa}[label=lst:range_functions]
229for ( Alphabet alph ) { sout | alph; }
230>>> A B C ... D
231\end{cfa}
232
233The 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.
234
235\textbullet\ H is implicit up-to exclusive range [0, H).
236\begin{cfa}[label=lst:range_function_1]
237for ( alph; Alphabet.D ) { sout | alph; }
238>>> A B C
239\end{cfa}
240
241\textbullet\ ~= H is implicit up-to inclusive range [0,H].
242\begin{cfa}[label=lst:range_function_2]
243for ( alph; ~= Alphabet.D ) { sout | alph; }
244>>> A B C D
245\end{cfa}
246
247\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
248\begin{cfa}[label=lst:range_function_3]
249for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
250// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
251>>> B C
252\end{cfa}
253
254\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
255\begin{cfa}[label=lst:range_function_4]
256for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
257>>> B C D
258\end{cfa}
259
260\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
261\begin{cfa}[label=lst:range_function_5]
262for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
263>>> D C
264\end{cfa}
265
266\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
267\begin{cfa}[label=lst:range_function_6]
268for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
269>>> D C B
270\end{cfa}
271
272A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
273\begin{cfa}[label=lst:range_function_stepping]
274enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
275for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
276>>> 10 12 14 16 18
277for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
278>>> 10 11 12 13 14 15 16 17 18
279\end{cfa}
280The 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
281\begin{cfa}[label=lst:range_function_stepping_converted]
282for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
283>>> 10 11 12 13 14 15 16 17 18
284\end{cfa}
285
286% \PAB{Explain what each loop does.}
287
288It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
289\begin{cfa}[label=lst:range_functions_label_implicit]
290for ( char * alph; Alphabet )
291\end{cfa}
292This 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.
293If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
294\begin{cfa}[label=lst:range_functions_label_implicit]
295for ( char * ch; labels( Alphabet ) )
296\end{cfa}
Note: See TracBrowser for help on using the repository browser.