Changeset 7568e5c for doc


Ignore:
Timestamp:
Aug 8, 2024, 10:39:40 PM (4 months ago)
Author:
JiadaL <j82liang@…>
Branches:
master
Children:
acab1bd
Parents:
c1c0efdb
Message:

Minor update on the thesis (add auto initialization and update future work

Location:
doc/theses/jiada_liang_MMath
Files:
10 edited

Legend:

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

    rc1c0efdb r7568e5c  
    11\chapter{\texorpdfstring{\CFA}{Cforall} Enumeration}
    22
    3 \CFA extends C-Style enumeration by adding a number of new features that bring enumerations inline with other modern programming languages.
    4 Any enumeration extensions must be intuitive to C programmers both in syntax and semantics.
    5 The following sections detail all of my new contributions to enumerations in \CFA.
     3\CFA extends C-Style enumeration by adding a number of new features that bring enumerations in line with other modern programming languages.
     4Any enumeration extensions must be intuitive to C programmers in syntax and semantics.
     5The following sections detail my new contributions to enumerations in \CFA.
    66
    77
    88\section{Syntax}
    99
    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:CFAInheritance}} using an @inline@ to another enumeration type.
     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:CFAInheritance}} using an @inline@ to another enumeration type.
    1111\begin{cfa}[identifierstyle=\linespread{0.9}\it]
    1212$\it enum$-specifier:
     
    4343A A @0@ 3
    4444\end{cfa}
    45 Finally, there is an additional enumeration pseudo-function @countof@ (like @sizeof@, @typeof@) that returns the number of enumerators in an enumeration.
     45Finally, \CFA introduces an additional enumeration pseudo-function @countof@ (like @sizeof@, @typeof@) that returns the number of enumerators in an enumeration.
    4646\begin{cfa}
    4747enum(int) E { A, B, C, D } e;
     
    4949countof( e );  // 4, variable argument
    5050\end{cfa}
    51 This buildin function replaces the C idiom for automatically computing the number of enumerators \see{\VRef{s:Usage}}.
     51This built-in function replaces the C idiom for automatically computing the number of enumerators \see{\VRef{s:Usage}}.
    5252\begin{cfa}
    5353enum E { A, B, C, D, @N@ };  // N == 4
     
    5656The underlying representation of \CFA enumeration object is its position, saved as an integral type.
    5757Therefore, the size of a \CFA enumeration is consistent with a C enumeration.
    58 Attribute function @posn@ performs type substitution on an expression from \CFA type to integral type.
    59 The 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.
    60 These operations do not apply to C Enums because backwards compatibility means the necessary backing data structures cannot be supplied.
     58Attribute function @posn@ performs type substitution on an expression from \CFA type to an integral type.
     59The label and value of an enumerator are stored in a global data structure for each enumeration, where attribute functions @label@/@value@ map an \CFA enumeration object to the corresponding data.
     60These operations do not apply to C Enums because backward compatibility means the necessary backing data structures cannot be supplied.
    6161
    6262
     
    6464\label{s:OpaqueEnum}
    6565
    66 When an enumeration type is empty is it an \newterm{opaque} enumeration.
     66When an enumeration type is empty. it is an \newterm{opaque} enumeration.
    6767\begin{cfa}
    6868enum@()@ Mode { O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC, O_APPEND };
    6969\end{cfa}
    70 Here, the internal representation is chosen by the compiler and hidden, so the enumerators cannot be initialized.
    71 Compared to the C enum, opaque enums are more restrictive in terms of typing and cannot be implicitly converted to integers.
     70Here, the compiler chooses the internal representation, which is hidden, so the enumerators cannot be initialized.
     71Compared to the C enum, opaque enums are more restrictive regarding typing and cannot be implicitly converted to integers.
    7272\begin{cfa}
    7373Mode mode = O_RDONLY;
    7474int www @=@ mode;                                               $\C{// disallowed}$
    7575\end{cfa}
    76 Opaque enumerations have only two attribute properties @label@ and @posn@.
     76Opaque enumerations have only two attribute properties, @label@ and @posn@.
    7777\begin{cfa}
    7878char * s = label( O_TRUNC );                    $\C{// "O\_TRUNC"}$
    7979int open = posn( O_WRONLY );                    $\C{// 1}$
    8080\end{cfa}
    81 The equality and relational operations are available.
     81Equality and relational operations are available.
    8282\begin{cfa}
    8383if ( mode @==@ O_CREAT ) ...
     
    8989\label{s:EnumeratorTyping}
    9090
    91 When 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.
    92 Figure~\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.
    93 Note, the use of the synonyms @Liz@ and @Beth@ in the last declaration.
     91When an enumeration type is specified, all enumerators have that type and can be initialized with constants of that type or compile-time convertible to that type.
     92Figure~\ref{f:EumeratorTyping} shows a series of examples illustrating that all \CFA types can be used with an enumeration, and each type's values are used to set the enumerator constants.
     93Note the use of the synonyms @Liz@ and @Beth@ in the last declaration.
    9494Because enumerators are constants, the enumeration type is implicitly @const@, so all the enumerator types in Figure~\ref{f:EumeratorTyping} are logically rewritten with @const@.
    9595
     
    132132};
    133133\end{cfa}
    134 Note, 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.
     134Note that 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.
    135135
    136136While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are \emph{not} used to evaluate an enumerator's value.
     
    164164bar( x );                                       $\C{// costs (1, 0, 0, 0, 0, 0, 0, 0) or (0, 1, 0, 0, 0, 0, 0, 0)}$
    165165\end{cfa}
    166 Here, candidate (1) has a value conversion cost to convert to the base type, while candidate (2) has an unsafe conversion from @double@ to @int@.
     166Here, the candidate (1) has a @value@ conversion cost to convert to the base type, while the candidate (2) has an @unsafe@ conversion from @double@ to @int@,
     167which is a more expensive conversion.
    167168Hence, @bar( x )@ resolves @x@ as type @Math@.
    168169
     
    177178
    178179
    179 % \section{Auto Initialization}
    180 %
     180\section{Auto Initialization}
     181\CFA implements auto-initialization for both C enumerations and \CFA enumerations. For the first category, the semantics is consistent with C:
    181182% A partially implemented feature is auto-initialization, which works for the C integral type with constant expressions.
    182 % \begin{cfa}
    183 % enum Week { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun }; // 0-2, 10-13
    184 % \end{cfa}
     183\begin{cfa}
     184enum Week { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun }; // 0-2, 10-13
     185\end{cfa}
    185186% The 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.
    186 %
     187
    187188% If \CFA had powerful compilation expression evaluation, auto initialization would be implemented as follows.
    188 % \begin{cfa}
    189 % enum E(T) { A, B, C };
    190 % \end{cfa}
    191 % \begin{enumerate}
    192 % \item the first enumerator, @A@, is initialized with @T@'s @zero_t@.
    193 % \item otherwise, the next enumerator is initialized with the previous enumerator's value using operator @?++@, where @?++( T )@ can be overloaded for any type @T@.
    194 % \end{enumerate}
    195 %
     189
     190\begin{cfa}
     191struct S { int i; };
     192S ?+?( S & s, one_t ) { return s.i++; }
     193void ?{}( S & s, zero_t ) { s.i = 0; }
     194enum(S) E { A, B, C, D };
     195\end{cfa}
     196For \CFA enumeration, the semantics is the following:
     197\begin{enumerate}
     198\item the first enumerator, @A@, is initialized with @T@'s @zero_t@.
     199\item otherwise, the next enumerator is initialized with the previous enumerator's value using the operator @?+?(T, one_t)@, which can be overloaded for any type @T@.
     200\end{enumerate}
     201
    196202% Unfortunately, constant expressions in C are not powerful and \CFA is only a transpiler, relying on generated C code to perform the detail work.
    197203% It 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.
     
    219225bar( A );                                                       $\C{// {\color{red}disallowed}}$
    220226\end{cfa}
    221 Hence, @Letter@ enumerators are not type compatible with the @Greek@ enumeration but the reverse is true.
     227Hence, @Letter@ enumerators are not type-compatible with the @Greek@ enumeration, but the reverse is true.
    222228
    223229
     
    241247
    242248Inheritance can be nested, and a \CFA enumeration can inline enumerators from more than one \CFA enumeration, forming a tree-like hierarchy.
    243 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
    244 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
    245 common supertype (the diamond problem), since such would unavoidably introduce duplicate enumerator labels.
     249However, the uniqueness of the enumeration name applies to enumerators, including those from supertypes, meaning an enumeration cannot name an enumerator with the same label as its subtype's members or inherits
     250from multiple enumeration that has overlapping enumerator labels. Consequently, a new type cannot inherit from an enumeration and its supertype or two enumerations with a
     251common supertype (the diamond problem) since such would unavoidably introduce duplicate enumerator labels.
    246252
    247253The base type must be consistent between subtype and supertype.
    248 When an enumeration inherits enumerators from another enumeration, it copies the enumerators' @value@ and @label@, even if the @value@ is auto initialized.
     254When an enumeration inherits enumerators from another enumeration, it copies the enumerators' @value@ and @label@, even if the @value@ is auto-initialized.
    249255However, the position of the underlying representation is the order of the enumerator in the new enumeration.
    250256\begin{cfa}
     
    334340The algorithm takes two @CFAEnums@ parameters, @src@ and @dst@, with @src@ being the type of expression the conversion applies to, and @dst@ being the type the expression is cast to.
    335341The algorithm iterates over the members in @dst@ to find @src@.
    336 If a member is an enumerator of @dst@, the positions of all subsequent members is increment by one.
     342If a member is an enumerator of @dst@, the positions of all subsequent members are incremented by one.
    337343If the current member is @dst@, the function returns true indicating \emph{found} and the accumulated offset.
    338344Otherwise, the algorithm recurses into the current @CFAEnum@ @m@ to check if its @src@ is convertible to @m@.
     
    467473\VRef[Figure]{f:EnumerationI/O} show \CFA enumeration input based on the enumerator labels.
    468474When the enumerator labels are packed together in the input stream, the input algorithm scans for the longest matching string.
    469 For 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.
     475For 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 string constants can be quoted or unquoted.
    470476
    471477\begin{figure}
  • doc/theses/jiada_liang_MMath/background.tex

    rc1c0efdb r7568e5c  
    11\chapter{Background}
    22
    3 This chapter covers background material for C enumerations and \CFA features used in later discussion.
     3This chapter covers background material for C enumerations and \CFA features used in later discussions.
    44
    55
     
    1414\begin{enumerate}[leftmargin=*]
    1515\item
    16 For @#define@, the programmer has to explicitly manage the constant name and value.
    17 Furthermore, these C preprocessor macro names are outside of the C type-system and can incorrectly change random text in a program.
     16For @#define@, the programmer must explicitly manage the constant name and value.
     17Furthermore, these C preprocessor macro names are outside the C type system and can incorrectly change random text in a program.
    1818\item
    1919The same explicit management is true for the @const@ declaration, and the @const@ variable cannot appear in constant-expression locations, like @case@ labels, array dimensions,\footnote{
    20 C allows variable-length array-declarations (VLA), so this case does work, but it fails in \CC, which does not support VLAs, unless it is \lstinline{g++}.} immediate oper\-ands of assembler instructions, and occupies storage.
     20C allows variable-length array declarations (VLA), so this case does work. Still, it fails in \CC, which does not support VLAs, unless it is \lstinline{g++}.} immediate oper\-ands of assembler instructions and occupies storage.
    2121\begin{clang}
    2222$\$$ nm test.o
     
    8787enum { Size = 20, Max = 10, MaxPlus10 = Max + 10, @Max10Plus1@, Fred = -7 };
    8888\end{clang}
    89 Here, the aliased constants are: 20, 10, 20, 21, and -7.
    90 Direct initialization is by a compile-time expression generating a constant value.
     89Here, the aliased constants are 20, 10, 20, 21, and -7.
     90Direct initialization is achieved by a compile-time expression that generates a constant value.
    9191Indirect initialization (without an initializer, @Max10Plus1@) is called \newterm{auto-initialization}, where enumerators are assigned values from left to right, starting at zero or the next explicitly initialized constant, incrementing by @1@.
    9292Because multiple independent enumerators can be combined, enumerators with the same values can occur.
    93 The enumerators are rvalues, so assignment is disallowed.
     93The enumerators are @rvalues@, so the assignment is disallowed.
    9494Finally, enumerators are \newterm{unscoped}, \ie enumerators declared inside of an @enum@ are visible (projected) outside into the enclosing scope of the @enum@ type.
    95 For unnamed enumerations, this semantic is required because there is no type name for scoped qualification.
    96 
    97 As noted, this kind of aliasing declaration is not an enumeration, even though it is declared using an @enum@ in C.
     95This semantic is required for unnamed enumerations because there is no type name for scoped qualification.
     96
     97As noted, this aliasing declaration is not an enumeration, even though it is declared using an @enum@ in C.
    9898While the semantics is misleading, this enumeration form matches with aggregate types:
    9999\begin{cfa}
     
    121121};
    122122\end{clang}
    123 Note, the comma in the enumerator list can be a terminator or a separator, allowing the list to end with a dangling comma.\footnote{
     123Note the comma in the enumerator list can be a terminator or a separator, allowing the list to end with a dangling comma.\footnote{
    124124A terminating comma appears in other C syntax, \eg the initializer list.}
    125125This feature allows enumerator lines to be interchanged without moving a comma.
     
    130130\label{s:CenumImplementation}
    131131
    132 In theory, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerator values.
     132Theoretically, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerator values.
    133133In practice, C defines @int@~\cite[\S~6.4.4.3]{C11} as the underlying type for enumeration variables, restricting initialization to integral constants, which have type @int@ (unless qualified with a size suffix).
    134134However, type @int@ is defined as:
     
    137137\end{quote}
    138138However, @int@ means 4 bytes on both 32/64-bit architectures, which does not seem like the ``natural'' size for a 64-bit architecture.
    139 Whereas, @long int@ means 4 bytes on a 32-bit and 8 bytes on 64-bit architectures, and @long long int@ means 8 bytes on both 32/64-bit architectures, where 64-bit operations are simulated on 32-bit architectures.
    140 \VRef[Figure]{f:gccEnumerationStorageSize} shows both @gcc@ and @clang@ partially ignore this specification and type the integral size of an enumerator based its initialization.
    141 Hence, initialization in the range @INT_MIN@..@INT_MAX@ results in a 4-byte enumerator, and outside this range the enumerator is 8 bytes.
     139Whereas @long int@ means 4 bytes on a 32-bit and 8 bytes on 64-bit architectures, and @long long int@ means 8 bytes on both 32/64-bit architectures, where 64-bit operations are simulated on 32-bit architectures.
     140\VRef[Figure]{f:gccEnumerationStorageSize} shows both @gcc@ and @clang@ partially ignore this specification and type the integral size of an enumerator based on its initialization.
     141Hence, initialization in the range @INT_MIN@..@INT_MAX@ results in a 4-byte enumerator, and outside this range, the enumerator is 8 bytes.
    142142Note that @sizeof( typeof( IMin ) ) != sizeof( E )@, making the size of an enumerator different than is containing enumeration type, which seems inconsistent, \eg @sizeof( typeof( 3 ) ) == sizeof( int )@.
    143143
     
    168168\label{s:Usage}
    169169
    170 C proves an implicit \emph{bidirectional} conversion between an enumeration and its integral type, and between two different enumerations.
     170C proves an implicit \emph{bidirectional} conversion between an enumeration and its integral type and between two different enumerations.
    171171\begin{clang}
    172172enum Week week = Mon;                           $\C{// week == 0}$
     
    178178@week = Winter;@                                        $\C{// UNDEFINED! implicit conversion to Week}$
    179179\end{clang}
    180 While converting an enumerator to its underlying type is useful, the implicit conversion from the base or another enumeration type to an enumeration is a common source of error.
     180While converting an enumerator to its underlying type is sound, the implicit conversion from the base or another enumeration type to an enumeration is a common source of error.
    181181
    182182Enumerators can appear in @switch@ and looping statements.
     
    194194\end{cfa}
    195195For iterating using arithmetic to make sense, the enumerator values \emph{must} have a consecutive ordering with a fixed step between values.
    196 For example, a previous gap introduced by @Thu = 10@, results in iterating over the values 0--13, where values 3--9 are not @Week@ values.
    197 Note, it is the bidirectional conversion that allows incrementing @day@: @day@ is converted to @int@, integer @1@ is added, and the result is converted back to @Week@ for the assignment to @day@.
     196For example, a previous gap introduced by @Thu = 10@ results in iterating over the values 0--13, where values 3--9 are not @Week@ values.
     197Note that the bidirectional conversion allows incrementing @day@: @day@ is converted to @int@, integer @1@ is added, and the result is converted back to @Week@ for the assignment to @day@.
    198198For safety, \CC does not support the bidirectional conversion, and hence, an unsafe cast is necessary to increment @day@: @day = (Week)(day + 1)@.
    199199
    200 There is a C idiom to automatically compute the number of enumerators in an enumeration.
     200There is a C idiom that computes the number of enumerators in an enumeration automatically.
    201201\begin{cfa}
    202202enum E { A, B, C, D, @N@ };  // N == 4
    203203for ( enum E e = A; e < @N@; e += 1 ) ...
    204204\end{cfa}
    205 Here, serendipitously the auto-incrementing counts the number of enumerators and puts the total into the last enumerator @N@.
     205Serendipitously, the auto-incrementing counts the number of enumerators and puts the total into the last enumerator @N@.
    206206This @N@ is often used as the dimension for an array associated with the enumeration.
    207207\begin{cfa}
     
    226226\end{cfa}
    227227However, the companion idiom results in the \emph{harmonizing} problem because an update to the enumeration @Integral_Type@ often requires a corresponding update to the companion array \snake{Integral_Name}.
    228 The requirement to harmonize is at best indicated by a comment before the enumeration.
     228The requirement to harmonize is, at best, indicated by a comment before the enumeration.
    229229This issue is exacerbated if enumeration and companion array are in different translation units.
    230230
    231231\bigskip
    232 While C provides a true enumeration, it is restricted, has unsafe semantics, and does not provide useful/advanced enumeration features found in other programming languages.
     232While C provides a true enumeration, it is restricted, has unsafe semantics, and does not provide helpful/advanced enumeration features in other programming languages.
    233233
    234234
    235235\section{\texorpdfstring{\CFA}{Cforall}}
    236236
    237 \CFA in \emph{not} an object-oriented programming-language, \ie functions cannot be nested in aggregate types, and hence, there is no \newterm{receiver} notation for calling functions, \eg @obj.method(...)@, where the first argument proceeds the call and becomes an implicit first (\lstinline[language=C++]{this}) parameter.
     237\CFA in \emph{not} an object-oriented programming language, \ie functions cannot be nested in aggregate types, and hence, there is no \newterm{receiver} notation for calling functions, \eg @obj.method(...)@, where the first argument proceeds the call and becomes an implicit first (\lstinline[language=C++]{this}) parameter.
    238238The following sections provide short descriptions of \CFA features needed further in the thesis.
    239 Other \CFA features are presented in-situ with short explanations, or no explanation because the feature is obvious to C programmers.
     239Other \CFA features are presented in situ with short or no explanation because the feature is obvious to C programmers.
    240240
    241241
    242242\subsection{Overloading}
    243243
    244 Overloading allows programmers to use the most meaningful names without fear of name clashes within a program or from external sources, like include files.
     244Overloading allows programmers to use the most meaningful names without fear of name clashes within a program or from external sources like included files.
    245245\begin{quote}
    246246There are only two hard things in Computer Science: cache invalidation and naming things. --- Phil Karlton
     
    269269\subsection{Function Overloading}
    270270
    271 Both \CFA and \CC allow function names to be overloaded, as long as their prototypes differ in the number and type of parameters and returns.
     271Both \CFA and \CC allow function names to be overloaded as long as their prototypes differ in the number and type of parameters and returns.
    272272\begin{cfa}
    273273void f( void );                 $\C[1.75in]{// (1): no parameter}$
     
    277277\end{cfa}
    278278In this case, the name @f@ is overloaded depending on the number and parameter types.
    279 The type system examines each call size and selects the best match based on the number and types of the arguments.
    280 Here, there is a perfect match for the call, @f( 'A' )@ with the number and parameter type of function (2).
    281 
    282 Ada, Scala, and \CFA type-systems also use the return type in resolving a call, to pinpoint the best overloaded name.
     279The type system examines each call size and selects the best match based on the number and types of arguments.
     280Here, the call @f( 'A' )@ is a perfect match for the number and parameter type of function (2).
     281
     282Ada, Scala, and \CFA type-systems also use the return type to pinpoint the best-overloaded name in resolving a call.
    283283\begin{cfa}
    284284int f( void );                  $\C[1.75in]{// (4); overloaded on return type}$
     
    302302}
    303303\end{cfa}
    304 The \CFA type system simply treats overloaded variables as an overloaded function returning a value with no parameters.
     304The \CFA type system treats overloaded variables as an overloaded function returning a value with no parameters.
    305305Hence, no significant effort is required to support this feature.
    306306
     
    312312
    313313All objects in \CFA are initialized by @constructors@ \emph{after} allocation and de-initialized \emph{before} deallocation.
    314 \CC cannot have constructors for basic-types because they have no aggregate type \lstinline[language=C++]{struct/class} in which to insert a constructor definition.
     314\CC cannot have constructors for basic types because they have no aggregate type \lstinline[language=C++]{struct/class} in which to insert a constructor definition.
    315315Like \CC, \CFA has multiple auto-generated constructors for every type.
    316316
    317317The prototype for the constructor/destructor are @void ?{}( T &, ... )@ and @void ^?{}( T &, ... )@, respectively.
    318 The first parameter is logically the \lstinline[language=C++]{this} or \lstinline[language=Python]{self} in other object-oriented languages, and implicitly passed.
     318The first parameter is logically the \lstinline[language=C++]{this} or \lstinline[language=Python]{self} in other object-oriented languages and implicitly passed.
    319319\VRef[Figure]{f:CFAConstructorDestructor} shows an example of creating and using a constructor and destructor.
    320320Both constructor and destructor can be explicitly called to reuse a variable.
     
    350350
    351351The C constants @0@ and @1@ have special meaning.
    352 @0@ is the null pointer and used in conditional expressions, where @if ( p )@ is rewritten @if ( p != 0 )@;
     352@0@ is the null pointer and is used in conditional expressions, where @if ( p )@ is rewritten @if ( p != 0 )@;
    353353@1@ is an additive identity in unary operators @++@ and @--@.
    354354Aware of their significance, \CFA provides a special type @zero_t@ and @one_t@ for custom types.
     
    385385bar( s );
    386386\end{cfa}
    387 The assertion on @T@ restricts the range of types that can be manipulated by @bar@ to only those that have an implementation of @foo@ with the matching signature, allowing @bar@'s call to @foo@ in its body.
     387The assertion on @T@ restricts the range of types that can be manipulated by @bar@ to only those that implement @foo@ with the matching signature, allowing @bar@'s call to @foo@ in its body.
    388388Unlike templates in \CC, which are macro expansions at the call site, \CFA polymorphic functions are compiled, passing the call-site assertion functions as hidden parameters.
    389389
     
    392392
    393393A @forall@ clause can assert many restrictions on multiple types.
    394 A common practice is to refactor the assertions into a named \newterm{trait}, similar to other languages, like Go and Rust.
     394A common practice is refactoring the assertions into a named \newterm{trait}, similar to other languages like Go and Rust.
    395395\begin{cfa}
    396396forall(T) trait @Bird@ {
     
    407407bird_fly( 23, robin );
    408408\end{cfa}
    409 Grouping type assertions into a named trait effectively creates a reusable interface for parametric-polymorphic types.
     409Grouping type assertions into a named trait effectively creates a reusable interface for parametric polymorphic types.
    410410
    411411
     
    417417
    418418The \CFA resolver attempts to identify the best candidate based on: first, the number of parameters and types, and second, when no exact match exists, the fewest implicit conversions and polymorphic variables.
    419 Finding an exact match is not discussed here, because the mechanism is fairly straightforward, even when the search space is large;
     419Finding an exact match is not discussed here, because the mechanism is fairly straightforward, even when the search space is ample;
    420420only finding a non-exact match is discussed in detail.
    421421
     
    425425
    426426Most programming languages perform some implicit conversions among basic types to facilitate mixed-mode arithmetic;
    427 otherwise, the program becomes littered with many explicit casts, which does not match with programmer's expectations.
    428 C is an aggressive language as it provides conversions among almost all of the basic types, even when the conversion is potentially unsafe or not meaningful, \ie @float@ to @bool@.
     427otherwise, the program becomes littered with many explicit casts which do not match the programmer's expectations.
     428C is an aggressive language, providing conversions among almost all basic types, even when the conversion is potentially unsafe or not meaningful, \ie @float@ to @bool@.
    429429C defines the resolution pattern as ``usual arithmetic conversion''~\cite[\S~6.3.1.8]{C11}, in which C looks for a \newterm{common type} between operands, and converts one or both operands to the common type.
    430 Loosely defined, a common type is the smallest type in terms of the size of representation that both operands can be converted into without losing their precision, called a \newterm{widening} or \newterm{safe conversion}.
     430A common type is the smallest type in terms of the size of representation that both operands can be converted into without losing their precision, called a \newterm{widening} or \newterm{safe conversion}.
    431431
    432432\CFA generalizes ``usual arithmetic conversion'' to \newterm{conversion cost}.
     
    438438@poly@ is the number of polymorphic function parameters, and
    439439\item
    440 @safe@ is sum of the degree of safe (widening) conversions.
     440@safe@ is the sum of the degree of safe (widening) conversions.
    441441\end{enumerate}
    442442Sum of degree is a method to quantify C's integer and floating-point rank.
    443443Every pair of widening conversion types is assigned a \newterm{distance}, and the distance between the two same types is 0.
    444 For example, the distance from @char@ to @int@ is 2, the distance from @int@ to @long@ is 1, and the distance from @int@ to @long long int@ is 2.
     444For example, the distance from @char@ to @int@ is 2, from @int@ to @long@ is 1, and from @int@ to @long long int@ is 2.
    445445This distance does not mirror C's rank system.
    446 For example, the rank of @char@ and @signed char@ are the same in C, but the distance from @char@ to @signed char@ is assigned 1.
     446For example, the @char@ and @signed char@ ranks are the same in C, but the distance from @char@ to @signed char@ is assigned 1.
    447447@safe@ cost is summing all pairs of arguments to parameter safe conversion distances.
    448 Among the three costs in Bilson's model, @unsafe@ is the most significant cost and @safe@ is the least significant, with an implication that \CFA always choose a candidate with the lowest @unsafe@, if possible.
    449 
    450 For example, assume the overloaded function @foo@ is called with two @int@ parameter.
    451 The cost for every overloaded @foo@ has been listed along:
     448Among the three costs in Bilson's model, @unsafe@ is the most significant cost, and @safe@ is the least significant, implying that \CFA always chooses a candidate with the lowest @unsafe@, if possible.
     449
     450For example, assume the overloaded function @foo@ is called with two @int@ parameters.
     451The cost for every overloaded @foo@ has been listed along with the following:
    452452\begin{cfa}
    453453void foo( char, char );                         $\C[2.5in]{// (1) (2, 0, 0)}$
     
    479479\CFA favours candidates with more restrictions on polymorphism, so @forall( T ) void foo( T, T )@ has lower cost.
    480480@specialization@ is an arbitrary count-down value starting at zero.
    481 For every type assertion in @forall@ clause (no assertions in the above example), \CFA subtracts one from @specialization@.
    482 More type assertions means more constraints on argument types, making the function less generic.
     481For every type assertion in the @forall@ clause (no assertions in the above example), \CFA subtracts one from @specialization@.
     482More type assertions mean more constraints on argument types, making the function less generic.
    483483
    484484\CFA defines two special cost values: @zero@ and @infinite@.
    485 A conversion cost is @zero@ when the argument and parameter have an exact match, and a conversion cost is @infinite@ when there is no defined conversion between two types.
     485A conversion cost is @zero@ when the argument and parameter have an exact match, and a conversion cost is @infinite@ when there is no defined conversion between the two types.
    486486For example, the conversion cost from @int@ to a @struct S@ is @infinite@.
    487487
    488488In \CFA, the meaning of a C-style cast is determined by its @Cast Cost@.
    489 For most cast-expression resolutions, a cast cost is equal to a conversion cost.
    490 Cast cost exists as an independent matrix for conversion that cannot happen implicitly, while being possible with an explicit cast.
    491 These conversions are often defined to have a infinite conversion cost and a non-infinite cast cost.
     489For most cast-expression resolutions, a cast cost equals a conversion cost.
     490Cast cost exists as an independent matrix for conversion that cannot happen implicitly while being possible with an explicit cast.
     491These conversions are often defined as having an infinite conversion cost and a non-infinite cast cost.
  • doc/theses/jiada_liang_MMath/conclusion.tex

    rc1c0efdb r7568e5c  
    5050enum( wchar_t * ) { Jack = L"John" };
    5151\end{cfa}
    52 \item
    53 Currently enumeration scoping is all or nothing.
    54 In some cases, it might be useful to increase the scoping granularity to individual enumerators.
     52There are several new features have been proposed or are developing in parallel with enumerations.
     53Two closely related features are iterator and namespace.
     54
     55Enumerating features, and range loops in particular, are currently implemented as loops unique to \CFA enumeration and do not align with the
     56general iterator pattern. They can be adapted to the iterator interface when it comes to maturity.
     57
     58Currently, \CFA implements a namespace feature for enumerated types only. There is recently a proposal by Andrew to
     59generalize the concept of namespace to other types. The enumeration scope will be revisited to follow the same semantics
     60as other types. Also to improve the granularity of scope control, we propose the following extension:
    5561\begin{cfa}
    5662enum E1 { @!@A, @^@B, C };
  • doc/theses/jiada_liang_MMath/test.adb

    rc1c0efdb r7568e5c  
    22-- with Ada.Standard; use Ada.Standard;
    33procedure test is
     4        type GBR is (  Green, Blue, Red );
    45        type RGB is ( Red, Green, Blue );
    5         for RGB use ( Red => 10, Green => 20, Blue => 30 );
     6        for RGB use ( Red => 10, Green => 20, Blue => 21 );
    67        Colour : RGB := Red;
    78       
     
    9596       
    9697        if B then null; end if;
     98
     99        B := False;
     100        Colour := Green;
     101
     102        Put_Line ( Boolean'Image( B ) & " " );
     103        Put_Line ( RGB'Image( RGB'Enum_Val( 10 ) ) & " " );
    97104end test;
    98105
  • doc/theses/jiada_liang_MMath/test.cc

    rc1c0efdb r7568e5c  
    6161        eca[A] = EC::A;
    6262
    63         enum Week { Mon, Tue, Wed, Thu = 10, Fri, Sat, Sun };
     63        enum Week { Mon, Tue, Wed, Thu = 10, Fri, Sat = 8, Sun };
     64        if ( Fri < Sat ) cout << "hmm" << endl;
     65        else cout << "ahh" << std::endl;
    6466        Week day = Mon;
    6567        if ( day <= Fri ) cout << "weekday" << endl;
  • doc/theses/jiada_liang_MMath/test.go

    rc1c0efdb r7568e5c  
    2020
    2121
    22 const ( R = 0; G = 3; B ) // implicit: 0 0 0
     22const ( R = 0; G = 3; B = 3; TT = 3 ) // implicit: 0 3 3
    2323const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) // Fred Mary Jane
    2424const ( H = 0; Jack = "Jack"; J; K = 0; I ) // type change, implicit: 0 Jack Jack
    2525const ( C = iota + G; M = iota; Y )
    2626const ( Mon = iota; Tue; Wed; // 0, 1, 2
    27         Thu = 10; Fri = iota - Wed + Thu - 1; Sat; Sun = iota ) // 10, 11, 12, 13
     27        Thu = 10; Fri = iota - Wed + Thu - 1; Sat; Sun = 0 ) // 10, 11, 12, 13
    2828const ( O1 = iota + 1; _; O3; _; O5 ) // 1, 3, 5
    2929const ( V1 = iota; V2; V3 = 7; V4 = iota + 1; V5 )
     
    3434
    3535func main() {
     36        fmt.Println( "Go:")
    3637        if 3 == R {};
    3738        fmt.Println( R, G, B )
     
    4546
    4647        day := Mon;
     48        day = Sun;
     49
    4750        switch day {
    4851          case Mon, Tue, Wed, Thu, Fri:
    4952                fmt.Println( "weekday" );
    50           case Sat, Sun:
     53          case Sat:
    5154                fmt.Println( "weekend" );
    5255        }
     
    5457            fmt.Println( i )
    5558        }
     59        fmt.Println(B < TT);
     60} // main
    5661
    57         var ar[Sun] int
    58         ar[Mon] = 3
    59 } // main
     62// go build test.go
  • doc/theses/jiada_liang_MMath/test.pas

    rc1c0efdb r7568e5c  
    44        Weekday = Mon..Fri;
    55        Weekend = Sat..Sun;
    6 type Count = ( Zero, One, Two, Ten = 10, Eleven );
     6type Count = ( Zero, One, Two, Ten = 10, Eleven=10 );
     7type RR = ( A, B, C );
     8
    79var day   : Week;
    810        wday  : Weekday;
     
    1012        lunch : array[Week] of Integer;
    1113        cnt       :  Count;
     14// procedure P1(v:Week);
     15// begin
     16//      Writeln('Week');
     17// end;
     18procedure P1(v:Weekday);
     19begin
     20        Writeln('Weekday');
     21end;
     22procedure P1(v:RR);
     23begin
     24        Writeln('RR');
     25end;
    1226begin
    1327        day := Sat;
     
    4054        Writeln();
    4155        for day := Mon to Sat do
     56                lunch[day] := ord(day) * 10;
     57        for day := Mon to Sun do
    4258                Write( lunch[day], ' ' );
    4359        Writeln();
     
    4561                Write( ord( cnt ), ' ' );
    4662        end;
     63        day := Tue;
     64        P1( day );
    4765        Writeln();
     66
     67        case (day) of
     68                Mon: writeln('Excellent!' );
     69                Tue: writeln('Well done' );
     70        end;
    4871end.
    4972
  • doc/theses/jiada_liang_MMath/test.py

    rc1c0efdb r7568e5c  
    2525#       Mon = 1; Tue = 2; Wed = 3; Thu = 10; Fri = 10; Sat = 16; Sun = 17
    2626class Week(OrderedEnum):
    27         Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 7
     27        Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 0
    2828        def isWeekday(self):
    2929                return Week(self.value) <= Week.Fri
     
    3434                return cls(date.isoweekday())
    3535
    36 day : Week = Week.Tue;
     36day : Week = Week.Tue
    3737print( "weekday:", day.isWeekday() )
    3838print( "weekend:", day.isWeekend() )
    3939print( "today:", Week.today(date.today()))
    4040
    41 print( Week.Thu.value == 4 );
    42 print( Week.Thu.name == "Thu" );
    43 print( Week( 4 ) == Week.Thu );
    44 print( Week["Thu"].value == 4 );
     41print( Week.Thu.value == 4 )
     42print( Week.Thu.name == "Thu" )
     43print( Week( 4 ) == Week.Thu )
     44print( Week["Thu"].value == 4 )
    4545
    4646if day <= Week.Fri :
    47         print( "weekday" );
     47        print( "weekday" )
    4848match day:
    4949        case Week.Mon | Week.Tue | Week.Wed | Week.Thu | Week.Fri:
    50                 print( "weekday" );
     50                print( "weekday" )
    5151        case Week.Sat | Week.Sun:
    52                 print( "weekend" );
     52                print( "weekend" )
    5353
    5454for day in Week:
     
    8080print( isinstance(Week.Fri, Week) )
    8181
    82 class WeekE(OrderedEnum): pass;
     82class WeekE(OrderedEnum): pass
    8383class WeekDay(WeekE): Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5;
    8484class WeekEnd(WeekE): Sat = 6; Sun = 7
     
    121121      Weekend = Sat | Sun
    122122print( f"0x{repr(WeekF.Weekday.value)} 0x{repr(WeekF.Weekend.value)}" )
    123 day : WeekF = WeekF.Mon | WeekF.Tue;
     123day : WeekF = WeekF.Mon | WeekF.Tue
    124124print( type(day) )
    125125for day in WeekF:
     
    164164match diffval:
    165165        case Diff.Int:
    166                 print( "diffval", diffval.value );
     166                print( "diffval", diffval.value )
    167167        case Diff.Float:
    168                 print( "diffval", diffval.value );
     168                print( "diffval", diffval.value )
    169169        case Diff.Str:
    170                 print( "diffval", diffval.value );
     170                print( "diffval", diffval.value )
    171171for i in Diff:
    172172        print( f"Diff type {type(i)}, {i}, {i.name}, {i.value} : " )
     
    197197                return G * self.mass / (self.radius * self.radius)
    198198        def surfaceWeight(self, otherMass):
    199                 return otherMass * self.surfaceGravity();
     199                return otherMass * self.surfaceGravity()
     200
     201class Cats(Enum):
     202        pass
     203
    200204
    201205earthWeight : float = 100
    202 earthMass : float = earthWeight / ( Planet.EARTH.surfaceGravity() );
     206earthMass : float = earthWeight / ( Planet.EARTH.surfaceGravity() )
    203207
    204208p = by_position( Planet, random.randrange(8) ) # select a random orbiting body
  • doc/theses/jiada_liang_MMath/test.swift

    rc1c0efdb r7568e5c  
    5959
    6060enum WeekInt: Int, CaseIterable {
    61         case Mon, Tue, Wed, Thu = 10, Fri,
     61        case Mon, Tue, Wed, Thu = 10, Fri = 14,
    6262                        Sat = 4, Sun // auto-incrementing
    6363};
  • doc/theses/jiada_liang_MMath/test1.java

    rc1c0efdb r7568e5c  
    33public class test1 {
    44        enum Weekday {
    5                 Mon(7), Tue(6), Wed(5), Thu(3), Fri(3), Sat(3), Sun(1); // must appear first
     5                Mon(7), Tue(6), Wed(5), Thu(3), Fri(4), Sat(3), Sun(7); // must appear first
    66                private long day;
    77                private Weekday( long d ) { day = d; }
     
    2727                }
    2828                for ( Weekday icday : Weekday.values() ) { // position
    29                         System.out.print( icday + " " + icday.ordinal() + " " + icday.day + " " +  icday.name() + ",  " ); // label
     29                        System.out.println( icday + " " + icday.ordinal() + " " + icday.day + " " +  icday.name() + ",  " ); // label
    3030                }
    3131                System.out.println();
     32
     33                if (Weekday.Fri == Weekday.Sat) {
     34                        System.out.println( "Alias ");
     35                }
    3236        }
    3337}
Note: See TracChangeset for help on using the changeset viewer.