Changeset c588acb


Ignore:
Timestamp:
Aug 5, 2024, 9:31:02 AM (18 hours ago)
Author:
Peter A. Buhr <pabuhr@…>
Branches:
master
Children:
cc077f4
Parents:
94643698
Message:

proofread CFA enumeration chapter

File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/theses/jiada_liang_MMath/CFAenum.tex

    r94643698 rc588acb  
    11\chapter{\CFA Enumeration}
    22
    3 % \CFA supports C enumeration using the same syntax and semantics for backwards compatibility.
    4 % \CFA also extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.
    5 % Any enumeration extensions must be intuitive to C programmers both in syntax and semantics.
    6 % The following sections detail all of my new contributions to enumerations in \CFA.
    7 \CFA extends the enumeration declaration by parameterizing with a type (like a generic type).
    8 
    9 
    10 \begin{cfa}[caption={CFA Enum},captionpos=b,label={l:CFAEnum}]
     3\CFA extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.
     4Any enumeration extensions must be intuitive to C programmers both in syntax and semantics.
     5The following sections detail all of my new contributions to enumerations in \CFA.
     6
     7
     8\section{Enumeration Syntax}
     9
     10\CFA extends the C enumeration declaration \see{\VRef{s:CEnumeration}} by parameterizing with a type (like a generic type), and adding Plan-9 inheritance \see{\VRef{s:EnumerationInheritance}} using an @inline@ to another enumeration type.
     11\begin{cfa}[identifierstyle=\linespread{0.9}\it]
    1112$\it enum$-specifier:
    1213        enum @(type-specifier$\(_{opt}\)$)@ identifier$\(_{opt}\)$ { cfa-enumerator-list }
     
    1516cfa-enumerator-list:
    1617        cfa-enumerator
    17         cfa-enumerator, cfa-enumerator-list
     18        cfa-enumerator-list, cfa-enumerator
    1819cfa-enumerator:
    1920        enumeration-constant
    20         $\it inline$ identifier
    21         enumeration-constant = expression
    22 \end{cfa}
    23 
    24 A \newterm{\CFA enumeration}, or \newterm{\CFA enum}, has an optional type declaration in the bracket next to the @enum@ keyword.
    25 Without optional type declarations, the syntax defines \newterm{opaque enums}.
    26 Otherwise, \CFA enum with type declaration are \newterm{typed enums}.
    27 
    28 \section{Opaque Enum}
     21        @inline $\color{red}enum$-type-name@
     22        enumeration-constant = constant-expression
     23\end{cfa}
     24
     25
     26\section{Enumeration Operations}
     27
     28\CFA enumerations have access to the three enumerations properties \see{\VRef{s:Terminology}}: label, order (position), and value via three overloaded functions @label@, @posn@, and @value@ \see{\VRef{c:trait} for details}.
     29\CFA auto-generates these functions for every \CFA enumeration.
     30\begin{cfa}
     31enum(int) E { A = 3 } e = A;
     32sout | A | @label@( A ) | @posn@( A ) | @value@( A );
     33sout | e | @label@( e ) | @posn@( e ) | @value@( e );
     34A A 0 3
     35A A 0 3
     36\end{cfa}
     37For output, the default is to print the label.
     38An alternate way to get an enumerator's position is to cast it to @int@.
     39\begin{cfa}
     40sout | A | label( A ) | @(int)A@ | value( A );
     41sout | A | label( A ) | @(int)A@ | value( A );
     42A A @0@ 3
     43A A @0@ 3
     44\end{cfa}
     45Finally, there is an additional enumeration routine @countof@ (like @sizeof@, @typeof@) that returns the number of enumerators in an enumeration.
     46\begin{cfa}
     47enum(int) E { A, B, C, D };
     48countof( E );  // 4
     49\end{cfa}
     50This auto-generated function replaces the C idiom for automatically computing the number of enumerators \see{\VRef{s:Usage}}.
     51\begin{cfa}
     52enum E { A, B, C, D, @N@ };  // N == 4
     53\end{cfa}
     54
     55The underlying representation of \CFA enumeration object is its position, saved as an integral type.
     56Therefore, the size of a \CFA enumeration is consistent with a C enumeration.
     57Attribute function @posn@ performs type substitution on an expression from \CFA type to integral type.
     58The label and value of an enumerator is stored in a global data structure for each enumeration, where attribute functions @label@/@value@ map an \CFA enumeration object to the corresponding data.
     59These operations do not apply to C Enums because backwards compatibility means the necessary backing data structures cannot be supplied.
     60
     61\section{Opaque Enumeration}
    2962\label{s:OpaqueEnum}
    30 Opaque enum is a special CFA enumeration type, where the internal representation is chosen by the compiler and hidden from users.
    31 Compared C enum, opaque enums are more restrictive in terms of typing, and cannot be implicitly converted to integers.
    32 Enumerators of opaque enum cannot have initializer. Declaring initializer in the body of opaque enum results in a compile time error.
    33 \begin{cfa}
    34 enum@()@ Planets { MERCURY, VENUS, EARTH, MARS, JUPITER, SATURN, URANUS, NEPTUNE };
    35 
    36 Planet p = URANUS;
    37 int i = VENUS; @// Error, VENUS cannot be converted into an integral type
    38 \end{cfa}
    39 % Each opaque enum has two @attributes@: @position@ and @label@. \CFA auto-generates @attribute functions@ @posn()@ and @label()@ for every \CFA enum to returns the respective attributes.
    40 Opaque enumerations have two defining properties: @label@ (name) and @order@ (position), exposed to users by predefined @attribute functions@ , with the following signatures:
    41 \begin{cfa}
    42 forall( E ) {
    43         unsigned posn(E e);
    44         const char * s label(E e);
    45 };
    46 \end{cfa}
    47 With polymorphic type parameter E being substituted by enumeration types such as @Planet@.
    48 
    49 \begin{cfa}
    50 unsigned i = posn(VENUS); // 1
    51 char * s = label(MARS); // "MARS"
    52 \end{cfa}
    53 
    54 \subsection{Representation}
    55 The underlying representation of \CFA enumeration object is its order, saved as an integral type. Therefore, the size of a \CFA enumeration is consistent with C enumeration.
    56 Attribute function @posn@ performs type substitution on an expression from \CFA type to integral type.
    57 Names of enumerators are stored in a global data structure, with @label@ maps \CFA enumeration object to corresponding data.
    58 
    59 \section{Typed Enum}
     63
     64When an enumeration type is empty is it an \newterm{opaque} enumeration.
     65\begin{cfa}
     66enum@()@ Mode { O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC, O_APPEND };
     67\end{cfa}
     68Here, the internal representation is chosen by the compiler and hidden, so the enumerators cannot be initialized.
     69Compared to the C enum, opaque enums are more restrictive in terms of typing and cannot be implicitly converted to integers.
     70\begin{cfa}
     71Mode mode = O_RDONLY;
     72int www @=@ mode;                                               $\C{// disallowed}$
     73\end{cfa}
     74Opaque enumerations have only two attribute properties @label@ and @posn@.
     75\begin{cfa}
     76char * s = label( O_TRUNC );                    $\C{// "O\_TRUNC"}$
     77int open = posn( O_WRONLY );                    $\C{// 1}$
     78\end{cfa}
     79The equality and relational operations are available.
     80\begin{cfa}
     81if ( mode @==@ O_CREAT ) ...
     82bool b = mode @<@ O_APPEND;
     83\end{cfa}
     84
     85
     86\section{Typed Enumeration}
    6087\label{s:EnumeratorTyping}
    6188
    62 \CFA extends the enumeration declaration by parameterizing with a type (like a generic type), allowing enumerators to be assigned any values from the declared type.
     89When an enumeration type is specified, all enumerators have that type and can be initialized with constants of that type or compile-time convertable to that type.
    6390Figure~\ref{f:EumeratorTyping} shows a series of examples illustrating that all \CFA types can be use with an enumeration and each type's values used to set the enumerator constants.
    64 Note, the synonyms @Liz@ and @Beth@ in the last declaration.
     91Note, the use of the synonyms @Liz@ and @Beth@ in the last declaration.
    6592Because enumerators are constants, the enumeration type is implicitly @const@, so all the enumerator types in Figure~\ref{f:EumeratorTyping} are logically rewritten with @const@.
    6693
     
    86113// aggregate
    87114        struct Person { char * name; int age, height; };
    88 @***@enum( @Person@ ) friends { @Liz@ = { "ELIZABETH", 22, 170 }, @Beth@ = Liz,
     115        enum( @Person@ ) friends { @Liz@ = { "ELIZABETH", 22, 170 }, @Beth@ = Liz,
    89116                                                                        Jon = { "JONATHAN", 35, 190 } };
    90117\end{cfa}
     118% synonym feature unimplemented
    91119\caption{Enumerator Typing}
    92120\label{f:EumeratorTyping}
     
    104132Note, the enumeration type can be a structure (see @Person@ in Figure~\ref{f:EumeratorTyping}), so it is possible to have the equivalent of multiple arrays of companion data using an array of structures.
    105133
    106 While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are not used to evaluate an enumerator's value.
     134While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are \emph{not} used to evaluate an enumerator's value.
    107135\CFA enumeration constants are compile-time values (static);
    108136calling constructors happens at runtime (dynamic).
    109137
    110 @value@ is an @attribute@ that defined for typed enum along with position and label. @values@ of a typed enum are stored in a global array of declared typed, initialized with
    111 value of enumerator initializers. @value()@ functions maps an enum to an elements of the array.
    112 
    113 
    114 \subsection{Value Conversion}
     138
     139\section{Value Conversion}
     140
    115141C has an implicit type conversion from an enumerator to its base type @int@.
    116 Correspondingly, \CFA has an implicit conversion from a typed enumerator to its base type, allowing typed enumeration to be seemlyless used as
    117 a value of its base type.
    118 \begin{cfa}
    119 char currency = Dollar;
    120 void foo( char * );
    121 foo( Fred );
    122 \end{cfa}
    123 
    124 % During the resolution of expression e with \CFA enumeration type, \CFA adds @value(e)@ as an additional candidate with an extra \newterm{value} cost.
    125 % For expression @char currency = Dollar@, the is no defined conversion from Dollar (\CFA enumeration) type to basic type and the conversion cost is @infinite@,
    126 % thus the only valid candidate is @value(Dollar)@.
    127 The implicit conversion induces a \newterm{value cost}, which is a new category in \CFA's conversion cost model to disambiguate function overloading over for both \CFA enumeration and its base type.
     142Correspondingly, \CFA has an implicit conversion from a typed enumerator to its base type, allowing typed enumeration to be seamlessly used as the value of its base type
     143For example, using type @Currency@ in \VRef[Figure]{f:EumeratorTyping}:
     144\begin{cfa}
     145char currency = Dollar;         $\C{// implicit conversion to base type}$
     146void foo( char );
     147foo( Dollar );                          $\C{// implicit conversion to base type}$
     148\end{cfa}
     149The implicit conversion induces a \newterm{value cost}, which is a new category (8 tuple) in \CFA's conversion cost model \see{\VRef{s:ConversionCost}} to disambiguate function overloading over a \CFA enumeration and its base type.
    128150\begin{cfa}
    129151void baz( char ch );            $\C{// (1)}$
    130152void baz( Currency cu );        $\C{// (2)}$
    131 
    132 baz( Cent );
    133 \end{cfa}
    134 While both baz are applicable to \CFA enumeration, using Cent as a char in @candiate (1)@ comes with a @value@ cost,
    135 while @candidate (2)@ has @zero@ cost. \CFA always choose a overloaded candidate implemented for a \CFA enumeration itself over a candidate applies on a base type.
    136 
    137 Value cost is defined to be a more significant factor than an @unsafe@ but weight less than @poly@.
    138 With @value@ being an additional category, the current \CFA conversion cost is a 8-tuple:
    139 @@(unsafe, value, poly, safe, sign, vars, specialization, reference)@@.
    140 
    141 \begin{cfa}
    142 void bar(int);
    143 enum(int) Month !{
    144         January=31, February=29, March=31, April=30, May=31, June-30,
    145         July=31, August=31, September=30, October=31, November=30, December=31
    146 };
    147 
    148 Month a = Februrary;    $\C{// (1), with cost (0, 1, 0, 0, 0, 0, 0, 0)}$
    149 double a = 5.5;                 $\C{// (2), with cost (1, 0, 0, 0, 0, 0, 0, 0)}$
    150 
    151 bar(a);
    152 \end{cfa}
    153 In the previous example, candidate (1) has an value cost to parameter type int, with is lower than (2) as an unsafe conversion from double to int.
    154 \CFA chooses value cost over unsafe cost and therefore @a@ of @bar(a)@ is resolved as an @Month@.
    155 
    156 \begin{cfa}
    157 forall(T | @CfaEnum(T)@) void bar(T);
    158 
    159 bar(a);                                 $\C{// (3), with cost (0, 0, 1, 0, 0, 0, 0, 0)}$
    160 \end{cfa}
    161 % @Value@ is designed to be less significant than @poly@ to allow function being generic over \CFA enumeration (see ~\ref{c:trait}).
    162 Being generic over @CfaEnum@ traits (a pre-defined interface for \CFA enums) is a practice in \CFA to implement functions over \CFA enumerations, as will see in chapter~\ref{c:trait}.
    163 @Value@ is a being a more significant cost than @poly@ implies if a overloaeded function defined for @CfaEnum@ (and other generic type), \CFA always
    164 try to resolve it as a @CfaEnum@, rather to insert a @value@ conversion.
    165 
    166 \subsection{Explicit Conversion}
    167 Explicit conversion is allowed on \CFA enumeration to an integral type, in which case \CFA converts \CFA enumeration into its underlying representation,
    168 which is its @position@.
    169 
    170 \section{Auto Initialization}
    171 
    172 C auto-initialization works for the integral type @int@ with constant expressions.
    173 \begin{cfa}
    174 enum Alphabet ! {
    175         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,
    176         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
    177 };
    178 \end{cfa}
    179 The 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.
    180 
    181 % The notion of auto-initialization is generalized in \CFA enumertation E with base type T in the following way:
    182 When an enumerator @e@ does not have a initializer, if @e@ has enumeration type @E@ with base type @T@, \CFA auto-initialize @e@ with the following scheme:
     153baz( Dollar );
     154\end{cfa}
     155While both @baz@ functions are applicable to the enumerator @Dollar@, @candidate (1)@ comes with a @value@ cost for the conversion to the enumeration's base type, while @candidate (2)@ has @zero@ cost.
     156Hence, \CFA chooses the exact match.
     157Value cost is defined to be a more significant factor than an @unsafe@ but less than the other conversion costs: @(unsafe,@ {\color{red}@value@}@, poly, safe, sign, vars, specialization,@ @reference)@.
     158\begin{cfa}
     159void bar( @int@ );
     160Math x = PI;                            $\C{// (1)}$
     161double x = 5.5;                         $\C{// (2)}$
     162bar( x );                                       $\C{// costs (1, 0, 0, 0, 0, 0, 0, 0) or (0, 1, 0, 0, 0, 0, 0, 0)}$
     163\end{cfa}
     164Here, candidate (1) has a value conversion cost to convert to the base type, while candidate (2) has an unsafe conversion from @double@ to @int@.
     165Hence, @bar( x )@ resolves @x@ as type @Math@.
     166
     167% \begin{cfa}
     168% forall(T | @CfaEnum(T)@) void bar(T);
     169%
     170% bar(a);                                       $\C{// (3), with cost (0, 0, 1, 0, 0, 0, 0, 0)}$
     171% \end{cfa}
     172% % @Value@ is designed to be less significant than @poly@ to allow function being generic over \CFA enumeration (see ~\ref{c:trait}).
     173% Being generic over @CfaEnum@ traits (a pre-defined interface for \CFA enums) is a practice in \CFA to implement functions over \CFA enumerations, as will see in chapter~\ref{c:trait}.
     174% @Value@ is a being a more significant cost than @poly@ implies if a overloaeded function defined for @CfaEnum@ (and other generic type), \CFA always try to resolve it as a @CfaEnum@, rather to insert a @value@ conversion.
     175
     176
     177\section{Auto Initialization}
     178
     179A partially implemented feature is auto-initialization, which works for the C integral type with constant expressions.
     180\begin{cfa}
     181enum Week { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun }; // 0-2, 10-13
     182\end{cfa}
     183The complexity of the constant expression depends on the level of 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.
     184
     185If \CFA had powerful compilation expression evaluation, auto initialization would be implemented as follows.
     186\begin{cfa}
     187enum E(T) { A, B, C };
     188\end{cfa}
    183189\begin{enumerate}
    184 % \item Enumerator e is the first enumerator of \CFA enumeration E with base type T. If e declares no no initializer, e is auto-initialized by the $zero\_t$ constructor of T.
    185 \item if e is first enumerator, e is initialized with T's @zero_t@.
    186 \item otherwise, if d is the enumerator defined just before e, with d has has been initialized with expression @l@ (@l@ can also be an auto-generated), e is initialized with @l++@.
    187 % \CFA reports a compile time error if T has no $zero\_t$ constructor.
    188 % Enumerator e is an enumerator of base-type T enumeration E that position i, where $i \neq 0$. And d is the enumerator with position @i-1@, e is auto-initialized with
    189 % the result of @value(d)++@. If operator @?++@ is not defined for type T, \CFA reports a compile time error.
    190 
    191 % Unfortunately, auto-initialization is not implemented because \CFA is only a transpiler, relying on generated C code to perform the detail work.
    192 % C 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.
    193 % Nevertheless, the necessary language concepts exist to support this feature.
     190\item the first enumerator, @A@, is initialized with @T@'s @zero_t@.
     191\item otherwise, the next enumerator is initialized with the previous enumerator's value using operator @?++@, where @?++( T )@ can be overloaded for any type @T@.
    194192\end{enumerate}
    195 while @?++( T )@ can be explicitly overloaded or implicitly overloaded with properly defined @one_t@ and @?+?(T, T)@.
    196 
    197 Unfortunately, auto-initialization with only constant expression is not enforced because \CFA is only a transpiler, relying on generated C code to perform the detail work.
    198 C 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.
     193
     194Unfortunately, constant expressions in C are not powerful and \CFA is only a transpiler, relying on generated C code to perform the detail work.
     195It is currently beyond the scope of the \CFA project to implement a complex runtime interpreter in the transpiler to evaluate complex expressions across multiple builtin and user-defined type.
    199196Nevertheless, the necessary language concepts exist to support this feature.
    200197
     198
    201199\section{Enumeration Inheritance}
     200\label{s:EnumerationInheritance}
    202201
    203202\CFA Plan-9 inheritance may be used with \CFA enumerations, where Plan-9 inheritance is containment inheritance with implicit unscoping (like a nested unnamed @struct@/@union@ in C).
    204 Containment is norminative: an enumeration inherits all enumerators from another enumeration by declaring an @inline statement@ in its enumerator lists.
    205 \begin{cfa}
    206 enum( char * ) Names { /* as above */ };
     203Containment is nominative: an enumeration inherits all enumerators from another enumeration by declaring an @inline statement@ in its enumerator lists.
     204\begin{cfa}
     205enum( char * ) Names { /* $\see{\VRef[Figure]{s:EnumerationInheritance}}$ */ };
    207206enum( char * ) Names2 { @inline Names@, Jack = "JACK", Jill = "JILL" };
    208207enum( char * ) Names3 { @inline Names2@, Sue = "SUE", Tom = "TOM" };
    209208\end{cfa}
    210209In the preceding example, @Names2@ is defined with five enumerators, three of which are from @Name@ through containment, and two are self-declared.
    211 @Names3@ inherits all five members from @Names2@ and declare two additional enumerators.
    212 
    213 Enumeration inheritance forms a subset relationship. Specifically, the inheritance relationship for the example above is:
     210@Names3@ inherits all five members from @Names2@ and declares two additional enumerators.
     211Hence, enumeration inheritance forms a subset relationship.
     212Specifically, the inheritance relationship for the example above is:
    214213\begin{cfa}
    215214Names $\(\subset\)$ Names2 $\(\subset\)$ Names3 $\C{// enum type of Names}$
     
    217216
    218217Inheritance can be nested, and a \CFA enumeration can inline enumerators from more than one \CFA enumeration, forming a tree-like hierarchy.
    219 However, the uniqueness of enumeration name applies to enumerators, including those from supertypes, meaning an enumeration cannot name enumerator with the same label as its subtype's members, or inherits
    220 from multiple enumeration that has overlapping enumerator label. As a consequence, a new type cannot inherits from both an enumeration and its supertype, or two enumerations with a
    221 common supertype (the diamond problem), since such would unavoidably introduce duplicate enumerator labels.
    222 
    223 
    224 % Enumeration @Name2@ inherits all the enumerators and their values from enumeration @Names@ by containment, and a @Names@ enumeration is a @subtype@ of enumeration @Name2@.
    225 % Note, that enumerators must be unique in inheritance but enumerator values may be repeated.
    226 
    227 
    228 
    229 % The enumeration type for the inheriting type must be the same as the inherited type;
    230 % hence the enumeration type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for @Name3@.
    231 % When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
    232 
    233 
    234 % The enumeration base for the subtype must be the same as the super type.
     218However, the uniqueness of enumeration name applies to enumerators, including those from supertypes, meaning an enumeration cannot name enumerator with the same label as its subtype's members, or inherits
     219from multiple enumeration that has overlapping enumerator label. As a consequence, a new type cannot inherits from both an enumeration and its supertype, or two enumerations with a
     220common supertype (the diamond problem), since such would unavoidably introduce duplicate enumerator labels.
     221
    235222The base type must be consistent between subtype and supertype.
    236 When an enumeration inherits enumerators from another enumeration, it copies the enumerators' @value@ and @label@, even if the @value@ was auto initialized. However, the @position@ as the underlying
    237 representation will be the order of the enumerator in new enumeration.
    238 % new enumeration @N@ copies all enumerators from @O@, including those @O@ obtains through inheritance. Enumerators inherited from @O@
    239 % keeps same @label@ and @value@, but @position@ may shift to the right if other enumerators or inline enumeration declared in prior of @inline A@.
    240 % hence the enumeration type may be omitted for the inheriting enumeration and it is inferred from the inherited enumeration, as for @Name3@.
    241 % When inheriting from integral types, automatic numbering may be used, so the inheritance placement left to right is important.
    242 
    243 \begin{cfa}
    244 enum() Phynchocephalia { Tuatara };
    245 enum() Squamata { Snake, Lizard };
    246 enum() Lepidosauromorpha { inline Phynchocephalia, inline Squamata, Kuehneosauridae };
    247 \end{cfa}
    248 Snake, for example, has the position 0 in Squamata, but 1 in Lepidosauromorpha as Tuatara inherited from Phynchocephalia is position 0 in Lepidosauromorpha.
     223When an enumeration inherits enumerators from another enumeration, it copies the enumerators' @value@ and @label@, even if the @value@ is auto initialized.
     224However, the position of the underlying representation is the order of the enumerator in the new enumeration.
     225\begin{cfa}
     226enum() E1 { A };
     227enum() E2 { B, C };
     228enum() E3 { inline E1, inline E2, D };
     229\end{cfa}
     230Here, @A@ has position 0 in @E1@ and @E3@.
     231@B@ has position 0 in @E2@ and 1 in @E3@.
     232@C@ has position 1 in @E2@ and position 2 in @E3@.
     233@D@ has position 3 in @E3@.
    249234
    250235A subtype enumeration can be casted, or implicitly converted into its supertype, with a @safe@ cost.
    251236\begin{cfa}
    252 enum Squamata squamata_lizard = Lizard;
    253 posn(quamata_lizard); // 1
    254 enum Lepidosauromorpha lepidosauromorpha_lizard = squamata_lizard;
    255 posn(lepidosauromorpha_lizard); // 2
    256 void foo( Lepidosauromorpha l );
    257 foo( squamata_lizard );
    258 posn( (Lepidosauromorpha) squamata_lizard ); // 2
    259 
    260 Lepidosauromorpha s = Snake;
    261 \end{cfa}
    262 The last expression in the preceding example is unambiguous. While both @Squamata.Snake@ and @Lepidosauromorpha.Snake@ are valid candidate, @Squamata.Snake@ has
    263 an associated safe cost and \CFA select the zero cost candidate @Lepidosauromorpha.Snake@.
    264 
    265 As discussed in \VRef{s:OpaqueEnum}, \CFA chooses position as a representation of \CFA enum. Conversion involves both change of typing
    266 and possibly @position@.
    267 
    268 When converting a subtype to a supertype, the position can only be a larger value. The difference between the position in subtype and in supertype is an "offset".
    269 \CFA runs a the following algorithm to determine the offset for an enumerator to a super type.
    270 % In a summary, \CFA loops over members (include enumerators and inline enums) of the supertype.
    271 % If the member is the matching enumerator, the algorithm returns its position.
    272 % If the member is a inline enumeration, the algorithm trys to find the enumerator in the inline enumeration. If success, it returns the position of enumerator in the inline enumeration, plus
    273 % the position in the current enumeration. Otherwises, it increase the offset by the size of inline enumeration.
    274 
     237enum E2 e2 = C;
     238posn( e2 );                     $\C[1.75in]{// 1}$
     239enum E3 e3 = e2;
     240posn( e2 );                     $\C{// 2}$
     241void foo( E3 e );
     242foo( e2 );
     243posn( (E3)e2 );         $\C{// 2}$
     244E3 e31 = B;
     245posn( e31 );            $\C{// 1}\CRT$
     246\end{cfa}
     247The last expression is unambiguous.
     248While both @E2.B@ and @E3.B@ are valid candidate, @E2.B@ has an associated safe cost and \CFA selects the zero cost candidate @E3.B@.
     249Hence, as discussed in \VRef{s:OpaqueEnum}, \CFA chooses position as a representation of the \CFA enum.
     250Therefore, conversion involves both a change of type and possibly position.
     251
     252When converting a subtype to a supertype, its position can only be a larger value.
     253The difference between the position in the subtype and in the supertype is its \newterm{offset}.
     254\VRef[Figure]{s:OffsetSubtypeSuperType} show the algorithm to determine the offset for an subtype enumerator to its super type.
     255\PAB{You need to explain the algorithm.}
     256
     257\begin{figure}
    275258\begin{cfa}
    276259struct Enumerator;
     
    280263pair<bool, int> calculateEnumOffset( CFAEnum dst, Enumerator e ) {
    281264        int offset = 0;
    282         for( auto v: dst.members ) {
     265        for ( auto v: dst.members ) {
    283266                if ( v.holds_alternative<Enumerator>() ) {
    284267                        auto m = v.get<Enumerator>();
     
    294277}
    295278\end{cfa}
    296 
    297 % \begin{cfa}
    298 % Names fred = Name.Fred;
    299 % (Names2) fred; (Names3) fred; (Name3) Names.Jack;  $\C{// cast to super type}$
    300 % Names2 fred2 = fred; Names3 fred3 = fred2; $\C{// assign to super type}$
    301 % \end{cfa}
     279\caption{Compute Offset from Subtype Enumerator to Super Type}
     280\label{s:OffsetSubtypeSuperType}
     281\end{figure}
     282
    302283For the given function prototypes, the following calls are valid.
    303284\begin{cquote}
     
    319300\end{cquote}
    320301Note, the validity of calls is the same for call-by-reference as for call-by-value, and @const@ restrictions are the same as for other types.
     302
    321303
    322304\section{Enumerator Control Structures}
     
    379361\begin{cfa}
    380362for ( cx; @Count@ ) { sout | cx | nonl; } sout | nl;
    381 for ( cx; +~= Count ) { sout | cx | nonl; } sout | nl;
     363for ( cx; ~= Count ) { sout | cx | nonl; } sout | nl;
    382364for ( cx; -~= Count ) { sout | cx | nonl; } sout | nl;
    383365First Second Third Fourth
     
    390372C has an idiom for @if@ and loop predicates of comparing the predicate result ``not equal to 0''.
    391373\begin{cfa}
    392 if ( x + y /* != 0 */ ) ...
    393 while ( p /* != 0 */ ) ...
     374if ( x + y /* != 0 */  ) ...
     375while ( p /* != 0 */  ) ...
    394376\end{cfa}
    395377This idiom extends to enumerations because there is a boolean conversion in terms of the enumeration value, if and only if such a conversion is available.
     
    412394\section{Enumeration Dimension}
    413395
    414 \VRef{s:EnumeratorTyping} introduced the harmonizing problem between an enumeration and secondary information.
     396\VRef{s:EnumeratorTyping} introduces the harmonizing problem between an enumeration and secondary information.
    415397When possible, using a typed enumeration for the secondary information is the best approach.
    416398However, there are times when combining these two types is not possible.
     
    422404enum E1 { A, B, C, N }; // possibly predefined
    423405enum(int) E2 { A, B, C };
    424 float H1[N] = { [A] :$\footnote{Note, C uses the symbol, @'='@ for designator initialization, but \CFA had to change to @':'@ because of problems with tuple syntax.}$ 3.4, [B] : 7.1, [C] : 0.01 }; // C
     406float H1[N] = { [A] :$\footnotemark$ 3.4, [B] : 7.1, [C] : 0.01 }; // C
    425407float H2[@E2@] = { [A] : 3.4, [B] : 7.1, [C] : 0.01 }; // CFA
    426408\end{cfa}
     409\footnotetext{C uses symbol \lstinline{'='} for designator initialization, but \CFA changes it to \lstinline{':'} because of problems with tuple syntax.}
    427410This approach is also necessary for a predefined typed enumeration (unchangeable), when additional secondary-information need to be added.
    428411
    429 The array subscript operator, namely ?[?], has been overloaded so that when a CFA enumerator is used as an array index, it implicitly converts
    430 to its position over value to sustain data hormonization. User can revert the behaviour by:
    431 \begin{cfa}
    432 float ?[?](float * arr, E2 index) { return arr[value(index)]; }
    433 \end{cfa}
    434 When an enumeration type is being used as an array dimension, \CFA add the enumeration type to initializer's context. As a result,
    435 @H2@'s array destinators @A@, @B@ and @C@ are resolved unambiguously to type E2. (H1's destinators are also resolved unambiguously to
    436 E1 because E2 has a @value@ cost to @int@).
     412The array subscript operator, namely @?[?]@, is overloaded so that when a \CFA enumerator is used as an array index, it implicitly converts to its position over value to sustain data harmonization.
     413This behaviour can be reverted by explicit overloading:
     414\begin{cfa}
     415float ?[?]( float * arr, E2 index ) { return arr[ value( index ) ]; }
     416\end{cfa}
     417When an enumeration type is being used as an array dimension, \CFA adds the enumeration type to the initializer's context.
     418As a result, @H2@'s array destinators @A@, @B@ and @C@ are resolved unambiguously to type @E2@.
     419(@H1@'s destinators are also resolved unambiguously to @E1@ because @E2@ has a @value@ cost.)
     420
    437421
    438422\section{Enumeration I/O}
     
    443427\VRef[Figure]{f:EnumerationI/O} show \CFA enumeration input based on the enumerator labels.
    444428When the enumerator labels are packed together in the input stream, the input algorithm scans for the longest matching string.
    445 For basic types in \CFA, the constants use to initialize a variable in a program are available to initialize a variable using input, where strings constants can be quoted or unquoted.
     429For basic types in \CFA, the rule is that the same constants used to initialize a variable in a program are available to initialize a variable using input, where strings constants can be quoted or unquoted.
    446430
    447431\begin{figure}
     
    509493\small
    510494\begin{cfa}
    511 struct MR { double mass, radius; };                     $\C{// planet definition}$
     495struct MR { double mass, radius; };                     $\C[3.5in]{// planet definition}$
    512496enum( @MR@ ) Planet {                                           $\C{// typed enumeration}$
    513497        //                      mass (kg)   radius (km)
     
    543527                sout | rp | "is not a planet";
    544528        }
    545         for ( @p; Planet@ ) {                                   $\C{// enumerate}$
     529        for ( @p; Planet@ ) {                                   $\C{// enumerate}\CRT$
    546530                sout | "Your weight on" | ( @p == MOON@ ? "the" : " " ) | p
    547531                           | "is" | wd( 1,1,  surfaceWeight( p, earthMass ) ) | "kg";
Note: See TracChangeset for help on using the changeset viewer.