source: doc/theses/jiada_liang_MMath/trait.tex @ 6740533e

Last change on this file since 6740533e was 6740533e, checked in by JiadaL <j82liang@…>, 40 hours ago

Add a discussion on Static Type information

  • Property mode set to 100644
File size: 14.8 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\section{Discussion: Static Type Information}
100@CfaEnum@ and @TypedEnum@ are approximations to \CFA Enumerations and Typed Enumerations: they are not
101assertions on a type being an enumerated type,
102but rather types being shared an interfaces with \CFA enumerations.
103\CC's @type_traits@ is fundamentally different than \CFA's traits: \CC's @type_traits@ are descriptions
104of compile time type information
105\footnote{Concepts can check if a \CC class implement a certain method,
106but it is to probe a static type information of a class having a such member.}
107, while \CFA's trait describe how a type can be used,
108which is a closer paradigm to a trait system in languages such as Scala and Rust.
109However, Scala and Rust's traits are nominative:
110a type explicitly declare a named traits to be of its type; while in \CFA,
111type implements all functions declares in a trait to implicitly be of the trait type.
112
113If to support static type information, \CFA needs new piece of syntax to distinguish static type
114query from function calls, for example:
115\begin{cfa}
116forall(T | { T::is_enum; });
117\end{cfa}
118When to call a polymorphic function @foo(T)@ with assertions set @S@ and function call argument @a@, \CFA 
119determines if there is an overloaded name @a@ that has non-zero conversion cost to all assertions in @S@.
120As a consequence, @is_enum@ can be a \CFA directive that immediately trim down the search space of @a@ to
121be some enumerated types. In fact, because \CFA stores symbols maps to enumeration in a standalone data structure.
122Limiting search space to enumeration improve on \CFA resolution speed.
123
124While assertion on static type information seems improvement on expressivity, it is a challenge to
125extend its capability without a fully functional pre-processsor that evaluate constant expression as \CC 
126compilers does. The described @is_enum@ manipulate compiler behaviour, which cannot be easily extended to
127other usage cases. Therefore, \CFA currently does not support @is_enum@ and utalizes traits as a workaround.
128
129
130\section{Bounded and Serial}
131A bounded type defines a lower bound and a upper bound.
132\begin{cfa}
133forall( E ) trait Bounded {
134        E lowerBound();
135        E lowerBound();
136};
137
138\end{cfa}
139Both Bounded functions are implement for \CFA enumerations, with @lowerBound()@ returning the first enumerator and @upperBound()@ returning
140the last enumerator.
141\begin{cfa}
142Workday day = lowerBound();                                     $\C{// Mon}$
143Planet outermost = upperBound();                                $\C{// NEPTUNE}$
144\end{cfa}
145
146The lowerBound() and upperBound() are functions overloaded on return type only, means their type resolution solely depend on the outer context,
147including expected type as a function argument, or the left hand size of an assignment expression.
148Calling either function without a context results in a type ambiguity, except in the rare case where the type environment has only one
149type overloads the functions, including \CFA enumerations, which has Bounded functions automatic defined.
150\begin{cfa}
151@lowerBound();@                 $\C{// ambiguous as both Workday and Planet implement Bounded}$
152sout | @lowerBound()@;
153Workday day = first();          $\C{// day provides type Workday}$
154void foo( Planet p );
155foo( last() );                      $\C{// argument provides type Planet}$
156\end{cfa}
157
158@Serial@ is a subset of @Bounded@, with functions maps elements against integers, as well implements a sequential order between members.
159\begin{cfa}
160forall( E | Bounded( E ) ) trait Serial {
161        unsigned fromInstance( E e );
162        E fromInt( unsigned int i );
163        E succ( E e );
164        E pred( E e );
165        unsigned Countof( E e );
166};
167\end{cfa}
168
169% A Serail type can project to an unsigned @int@ type, \ie an instance of type T has a corresponding integer value.
170Function @fromInstance()@ projects a @Bounded@ member to a number and @fromInt@ is the inverser. Function @succ()@ take an element, returns the "next"
171member in sequential order and @pred()@ returns the "last" member.
172
173A 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}.
174Calling @succ()@ on @upperBound@ or @pred()@ on @lowerBound()@ results in out of bound.
175
176\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.
177Unlike a cast, conversion between \CFA enumeration and integer with @Serial@ interface is type safe.
178Specifically for @fromInt@, \CFA abort if input i smaller than @fromInstance(lowerBound())@ or greater than @fromInstance(upperBound())@
179
180Function @Countof@ takes an object as a parameter and returns the number of elements in the Serial type, which is @fromInstance( upper ) - fromInstance( lower ) + 1@.
181@Countof@ does not use its arugment as procedural input; it needs
182an argument to anchor its polymorphic type T.
183
184\CFA has an expression @countof@ (lower case) that returns the number of enumerators defined for enumerations.
185\begin{cfa}
186enum RGB {Red, Green, Blue};
187countof( RGB ); // (1)
188countof( Red ); // (2)
189\end{cfa}
190Both expressions from the previous example are converted to constant expression @3@ with no function call at runtime.
191@countof@ also works for any type T that defines @Countof@ and @lowerBound@, for which it turns into
192a function call @Countof( T )@. The resolution step on expression @countof(e)@ works as the following with priority ordered:
193\begin{enumerate}
194\item Looks for an enumeration named e, such as @enum e {... }@.
195If such an enumeration e exists, \CFA replace @countof(e)@  with constant expression with number of enumerator of e.
196\item Looks for a non-enumeration type named e that defines @Countof@ and @lowerBound@, including e being a polymorphic type, such as @forall(e)@.
197If type e exists, \CFA replaces it with @Countof(lowerBound())@, where lowerBound() is bounded to type e. 
198\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.
199\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)@.
200\item If 1-4 fail, \CFA reports a type error on expression @countof(e)@.
201\end{enumerate}
202
203With the @Bounded@ and @Serial@, a loop over enumeration can be implemented in the following ways:
204\begin{cfa}
205enum() E { ... }
206for( unsigned i = 0; i < countof(E); i++ ) { ... }
207for( E e = lowerBound(); ; e = succ(e) ) { ...; if (e == upperBound()) break; }
208
209forall( T ) {
210        for( unsigned i = 0; i < countof(T); i++ ) { ... }
211        for( T e = lowerBound(); ; e = succ(e) ) { ...; if (e == upperBound()) break; }
212}
213\end{cfa}
214
215Finally, there is an associated trait defining comparison operators among enumerators.
216\begin{cfa}
217forall( E, T | CfaEnum( E, T ) ) {
218        // comparison
219        int ?==?( E l, E r );           $\C{// true if l and r are same enumerators}$
220        int ?!=?( E l, E r );           $\C{// true if l and r are different enumerators}$
221        int ?!=?( E l, zero_t );        $\C{// true if l is not the first enumerator}$
222        int ?<?( E l, E r );            $\C{// true if l is an enumerator before r}$
223        int ?<=?( E l, E r );           $\C{// true if l before or the same as r}$
224        int ?>?( E l, E r );            $\C{// true if l is an enumerator after r}$
225        int ?>=?( E l, E r );           $\C{// true if l after or the same as r}$         
226}
227\end{cfa}
228
229As an alternative, users can define the boolean conversion for CfaEnum:
230
231\begin{cfa}
232forall(E | CfaEnum(E))
233bool ?!=?(E lhs, zero_t) {
234        return posn(lhs) != 0;
235}
236\end{cfa}
237which effectively turns the first enumeration as a logical zero and non-zero for others.
238
239\begin{cfa}
240Count variable_a = First, variable_b = Second, variable_c = Third, variable_d = Fourth;
241p(variable_a); // 0
242p(variable_b); // 1
243p(variable_c); // "Third"
244p(variable_d); // 3
245\end{cfa}
246
247
248\section{Iteration and Range}
249
250It is convenient to iterate over a \CFA enumeration value, \eg:
251\begin{cfa}[label=lst:range_functions]
252for ( Alphabet alph; Alphabet ) { sout | alph; }
253>>> A B C ... D
254\end{cfa}
255The for-loop uses the enumeration type @Alphabet@ its range, and iterates through all enumerators in the order defined in the enumeration.
256@alph@ is the iterating enumeration object, which returns the value of an @Alphabet@ in this context according to the precedence rule.
257
258\textbullet\ \CFA offers a shorthand for iterating all enumeration constants:
259\begin{cfa}[label=lst:range_functions]
260for ( Alphabet alph ) { sout | alph; }
261>>> A B C ... D
262\end{cfa}
263
264The 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.
265
266\textbullet\ H is implicit up-to exclusive range [0, H).
267\begin{cfa}[label=lst:range_function_1]
268for ( alph; Alphabet.D ) { sout | alph; }
269>>> A B C
270\end{cfa}
271
272\textbullet\ ~= H is implicit up-to inclusive range [0,H].
273\begin{cfa}[label=lst:range_function_2]
274for ( alph; ~= Alphabet.D ) { sout | alph; }
275>>> A B C D
276\end{cfa}
277
278\textbullet\ L ~ H is explicit up-to exclusive range [L,H).
279\begin{cfa}[label=lst:range_function_3]
280for ( alph; Alphabet.B ~ Alphabet.D  ) { sout | alph; }
281// for ( Alphabet alph = Alphabet.B; alph < Alphabet.D; alph += 1  ); 1 is one_t
282>>> B C
283\end{cfa}
284
285\textbullet\ L ~= H is explicit up-to inclusive range [L,H].
286\begin{cfa}[label=lst:range_function_4]
287for ( alph; Alphabet.B ~= Alphabet.D  ) { sout | alph; }
288>>> B C D
289\end{cfa}
290
291\textbullet\ L -~ H is explicit down-to exclusive range [H,L), where L and H are implicitly interchanged to make the range down-to.
292\begin{cfa}[label=lst:range_function_5]
293for ( alph; Alphabet.D -~ Alphabet.B  ) { sout | alph; }
294>>> D C
295\end{cfa}
296
297\textbullet\ L -~= H is explicit down-to exclusive range [H,L], where L and H are implicitly interchanged to make the range down-to.
298\begin{cfa}[label=lst:range_function_6]
299for ( alph; Alphabet.D -~= Alphabet.B  ) { sout | alph; }
300>>> D C B
301\end{cfa}
302
303A user can specify the ``step size'' of an iteration. There are two different stepping schemes of enumeration for-loop.
304\begin{cfa}[label=lst:range_function_stepping]
305enum(int) Sequence { A = 10, B = 12, C = 14, D = 16, D  = 18 };
306for ( s; Sequence.A ~= Sequence.D ~ 1  ) { sout | alph; }
307>>> 10 12 14 16 18
308for ( s; Sequence.A ~= Sequence.D; s+=1  ) { sout | alph; }
309>>> 10 11 12 13 14 15 16 17 18
310\end{cfa}
311The 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
312\begin{cfa}[label=lst:range_function_stepping_converted]
313for ( typeof( value(Sequence.A) ) s=value( Sequence.A ); s <= Sequence.D; s+=1  ) { sout | alph; }
314>>> 10 11 12 13 14 15 16 17 18
315\end{cfa}
316
317% \PAB{Explain what each loop does.}
318
319It is also possible to iterate over an enumeration's labels, implicitly or explicitly:
320\begin{cfa}[label=lst:range_functions_label_implicit]
321for ( char * alph; Alphabet )
322\end{cfa}
323This 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.
324If the value can also be resolved as the @char *@, you might iterate the labels explicitly with the array iteration.
325\begin{cfa}[label=lst:range_functions_label_implicit]
326for ( char * ch; labels( Alphabet ) )
327\end{cfa}
Note: See TracBrowser for help on using the repository browser.