- Timestamp:
- Aug 8, 2024, 10:39:40 PM (4 months ago)
- Branches:
- master
- Children:
- acab1bd
- Parents:
- c1c0efdb
- Location:
- doc/theses/jiada_liang_MMath
- Files:
-
- 10 edited
Legend:
- Unmodified
- Added
- Removed
-
doc/theses/jiada_liang_MMath/CFAenum.tex
rc1c0efdb r7568e5c 1 1 \chapter{\texorpdfstring{\CFA}{Cforall} Enumeration} 2 2 3 \CFA extends C-Style enumeration by adding a number of new features that bring enumerations in line with other modern programming languages.4 Any enumeration extensions must be intuitive to C programmers bothin syntax and semantics.5 The following sections detail all ofmy 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. 4 Any enumeration extensions must be intuitive to C programmers in syntax and semantics. 5 The following sections detail my new contributions to enumerations in \CFA. 6 6 7 7 8 8 \section{Syntax} 9 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: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. 11 11 \begin{cfa}[identifierstyle=\linespread{0.9}\it] 12 12 $\it enum$-specifier: … … 43 43 A A @0@ 3 44 44 \end{cfa} 45 Finally, there is an additional enumeration pseudo-function @countof@ (like @sizeof@, @typeof@) that returns the number of enumerators in an enumeration.45 Finally, \CFA introduces an additional enumeration pseudo-function @countof@ (like @sizeof@, @typeof@) that returns the number of enumerators in an enumeration. 46 46 \begin{cfa} 47 47 enum(int) E { A, B, C, D } e; … … 49 49 countof( e ); // 4, variable argument 50 50 \end{cfa} 51 This buil din function replaces the C idiom for automatically computing the number of enumerators \see{\VRef{s:Usage}}.51 This built-in function replaces the C idiom for automatically computing the number of enumerators \see{\VRef{s:Usage}}. 52 52 \begin{cfa} 53 53 enum E { A, B, C, D, @N@ }; // N == 4 … … 56 56 The underlying representation of \CFA enumeration object is its position, saved as an integral type. 57 57 Therefore, 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 isstored 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 backward scompatibility means the necessary backing data structures cannot be supplied.58 Attribute function @posn@ performs type substitution on an expression from \CFA type to an integral type. 59 The 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. 60 These operations do not apply to C Enums because backward compatibility means the necessary backing data structures cannot be supplied. 61 61 62 62 … … 64 64 \label{s:OpaqueEnum} 65 65 66 When an enumeration type is empty is itan \newterm{opaque} enumeration.66 When an enumeration type is empty. it is an \newterm{opaque} enumeration. 67 67 \begin{cfa} 68 68 enum@()@ Mode { O_RDONLY, O_WRONLY, O_CREAT, O_TRUNC, O_APPEND }; 69 69 \end{cfa} 70 Here, the internal representation is chosen by the compiler andhidden, so the enumerators cannot be initialized.71 Compared to the C enum, opaque enums are more restrictive in terms oftyping and cannot be implicitly converted to integers.70 Here, the compiler chooses the internal representation, which is hidden, so the enumerators cannot be initialized. 71 Compared to the C enum, opaque enums are more restrictive regarding typing and cannot be implicitly converted to integers. 72 72 \begin{cfa} 73 73 Mode mode = O_RDONLY; 74 74 int www @=@ mode; $\C{// disallowed}$ 75 75 \end{cfa} 76 Opaque enumerations have only two attribute properties @label@ and @posn@.76 Opaque enumerations have only two attribute properties, @label@ and @posn@. 77 77 \begin{cfa} 78 78 char * s = label( O_TRUNC ); $\C{// "O\_TRUNC"}$ 79 79 int open = posn( O_WRONLY ); $\C{// 1}$ 80 80 \end{cfa} 81 The equality and relational operations are available.81 Equality and relational operations are available. 82 82 \begin{cfa} 83 83 if ( mode @==@ O_CREAT ) ... … … 89 89 \label{s:EnumeratorTyping} 90 90 91 When an enumeration type is specified, all enumerators have that type and can be initialized with constants of that type or compile-time convert able 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 valuesused to set the enumerator constants.93 Note ,the use of the synonyms @Liz@ and @Beth@ in the last declaration.91 When 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. 92 Figure~\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. 93 Note the use of the synonyms @Liz@ and @Beth@ in the last declaration. 94 94 Because enumerators are constants, the enumeration type is implicitly @const@, so all the enumerator types in Figure~\ref{f:EumeratorTyping} are logically rewritten with @const@. 95 95 … … 132 132 }; 133 133 \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.134 Note 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. 135 135 136 136 While the enumeration type can be any C aggregate, the aggregate's \CFA constructors are \emph{not} used to evaluate an enumerator's value. … … 164 164 bar( x ); $\C{// costs (1, 0, 0, 0, 0, 0, 0, 0) or (0, 1, 0, 0, 0, 0, 0, 0)}$ 165 165 \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@. 166 Here, 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@, 167 which is a more expensive conversion. 167 168 Hence, @bar( x )@ resolves @x@ as type @Math@. 168 169 … … 177 178 178 179 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: 181 182 % 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-13184 %\end{cfa}183 \begin{cfa} 184 enum Week { Mon, Tue, Wed, Thu@ = 10@, Fri, Sat, Sun }; // 0-2, 10-13 185 \end{cfa} 185 186 % 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 187 188 % 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} 191 struct S { int i; }; 192 S ?+?( S & s, one_t ) { return s.i++; } 193 void ?{}( S & s, zero_t ) { s.i = 0; } 194 enum(S) E { A, B, C, D }; 195 \end{cfa} 196 For \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 196 202 % Unfortunately, constant expressions in C are not powerful and \CFA is only a transpiler, relying on generated C code to perform the detail work. 197 203 % 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. … … 219 225 bar( A ); $\C{// {\color{red}disallowed}}$ 220 226 \end{cfa} 221 Hence, @Letter@ enumerators are not type compatible with the @Greek@ enumerationbut the reverse is true.227 Hence, @Letter@ enumerators are not type-compatible with the @Greek@ enumeration, but the reverse is true. 222 228 223 229 … … 241 247 242 248 Inheritance 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 inherits244 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 a245 common supertype (the diamond problem) ,since such would unavoidably introduce duplicate enumerator labels.249 However, 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 250 from multiple enumeration that has overlapping enumerator labels. Consequently, a new type cannot inherit from an enumeration and its supertype or two enumerations with a 251 common supertype (the diamond problem) since such would unavoidably introduce duplicate enumerator labels. 246 252 247 253 The 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 254 When an enumeration inherits enumerators from another enumeration, it copies the enumerators' @value@ and @label@, even if the @value@ is auto-initialized. 249 255 However, the position of the underlying representation is the order of the enumerator in the new enumeration. 250 256 \begin{cfa} … … 334 340 The 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. 335 341 The 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 incrementby one.342 If a member is an enumerator of @dst@, the positions of all subsequent members are incremented by one. 337 343 If the current member is @dst@, the function returns true indicating \emph{found} and the accumulated offset. 338 344 Otherwise, the algorithm recurses into the current @CFAEnum@ @m@ to check if its @src@ is convertible to @m@. … … 467 473 \VRef[Figure]{f:EnumerationI/O} show \CFA enumeration input based on the enumerator labels. 468 474 When 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 string sconstants can be quoted or unquoted.475 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 string constants can be quoted or unquoted. 470 476 471 477 \begin{figure} -
doc/theses/jiada_liang_MMath/background.tex
rc1c0efdb r7568e5c 1 1 \chapter{Background} 2 2 3 This chapter covers background material for C enumerations and \CFA features used in later discussion .3 This chapter covers background material for C enumerations and \CFA features used in later discussions. 4 4 5 5 … … 14 14 \begin{enumerate}[leftmargin=*] 15 15 \item 16 For @#define@, the programmer has toexplicitly 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.16 For @#define@, the programmer must explicitly manage the constant name and value. 17 Furthermore, these C preprocessor macro names are outside the C type system and can incorrectly change random text in a program. 18 18 \item 19 19 The 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.20 C 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. 21 21 \begin{clang} 22 22 $\$$ nm test.o … … 87 87 enum { Size = 20, Max = 10, MaxPlus10 = Max + 10, @Max10Plus1@, Fred = -7 }; 88 88 \end{clang} 89 Here, the aliased constants are :20, 10, 20, 21, and -7.90 Direct initialization is by a compile-time expression generatinga constant value.89 Here, the aliased constants are 20, 10, 20, 21, and -7. 90 Direct initialization is achieved by a compile-time expression that generates a constant value. 91 91 Indirect 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@. 92 92 Because multiple independent enumerators can be combined, enumerators with the same values can occur. 93 The enumerators are rvalues, soassignment is disallowed.93 The enumerators are @rvalues@, so the assignment is disallowed. 94 94 Finally, 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 requiredbecause there is no type name for scoped qualification.96 97 As noted, this kind ofaliasing declaration is not an enumeration, even though it is declared using an @enum@ in C.95 This semantic is required for unnamed enumerations because there is no type name for scoped qualification. 96 97 As noted, this aliasing declaration is not an enumeration, even though it is declared using an @enum@ in C. 98 98 While the semantics is misleading, this enumeration form matches with aggregate types: 99 99 \begin{cfa} … … 121 121 }; 122 122 \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{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{ 124 124 A terminating comma appears in other C syntax, \eg the initializer list.} 125 125 This feature allows enumerator lines to be interchanged without moving a comma. … … 130 130 \label{s:CenumImplementation} 131 131 132 In theory, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerator values.132 Theoretically, a C enumeration \emph{variable} is an implementation-defined integral type large enough to hold all enumerator values. 133 133 In 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). 134 134 However, type @int@ is defined as: … … 137 137 \end{quote} 138 138 However, @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.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 on 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. 142 142 Note 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 )@. 143 143 … … 168 168 \label{s:Usage} 169 169 170 C proves an implicit \emph{bidirectional} conversion between an enumeration and its integral type ,and between two different enumerations.170 C proves an implicit \emph{bidirectional} conversion between an enumeration and its integral type and between two different enumerations. 171 171 \begin{clang} 172 172 enum Week week = Mon; $\C{// week == 0}$ … … 178 178 @week = Winter;@ $\C{// UNDEFINED! implicit conversion to Week}$ 179 179 \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.180 While 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. 181 181 182 182 Enumerators can appear in @switch@ and looping statements. … … 194 194 \end{cfa} 195 195 For 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 thatallows incrementing @day@: @day@ is converted to @int@, integer @1@ is added, and the result is converted back to @Week@ for the assignment to @day@.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 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@. 198 198 For safety, \CC does not support the bidirectional conversion, and hence, an unsafe cast is necessary to increment @day@: @day = (Week)(day + 1)@. 199 199 200 There is a C idiom t o automatically compute the number of enumerators in an enumeration.200 There is a C idiom that computes the number of enumerators in an enumeration automatically. 201 201 \begin{cfa} 202 202 enum E { A, B, C, D, @N@ }; // N == 4 203 203 for ( enum E e = A; e < @N@; e += 1 ) ... 204 204 \end{cfa} 205 Here, serendipitouslythe auto-incrementing counts the number of enumerators and puts the total into the last enumerator @N@.205 Serendipitously, the auto-incrementing counts the number of enumerators and puts the total into the last enumerator @N@. 206 206 This @N@ is often used as the dimension for an array associated with the enumeration. 207 207 \begin{cfa} … … 226 226 \end{cfa} 227 227 However, 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 bestindicated by a comment before the enumeration.228 The requirement to harmonize is, at best, indicated by a comment before the enumeration. 229 229 This issue is exacerbated if enumeration and companion array are in different translation units. 230 230 231 231 \bigskip 232 While C provides a true enumeration, it is restricted, has unsafe semantics, and does not provide useful/advanced enumeration features foundin other programming languages.232 While C provides a true enumeration, it is restricted, has unsafe semantics, and does not provide helpful/advanced enumeration features in other programming languages. 233 233 234 234 235 235 \section{\texorpdfstring{\CFA}{Cforall}} 236 236 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. 238 238 The 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.239 Other \CFA features are presented in situ with short or no explanation because the feature is obvious to C programmers. 240 240 241 241 242 242 \subsection{Overloading} 243 243 244 Overloading allows programmers to use the most meaningful names without fear of name clashes within a program or from external sources , like includefiles.244 Overloading allows programmers to use the most meaningful names without fear of name clashes within a program or from external sources like included files. 245 245 \begin{quote} 246 246 There are only two hard things in Computer Science: cache invalidation and naming things. --- Phil Karlton … … 269 269 \subsection{Function Overloading} 270 270 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.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. 272 272 \begin{cfa} 273 273 void f( void ); $\C[1.75in]{// (1): no parameter}$ … … 277 277 \end{cfa} 278 278 In 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 thearguments.280 Here, the re is a perfect match for the call, @f( 'A' )@ withthe 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.279 The type system examines each call size and selects the best match based on the number and types of arguments. 280 Here, the call @f( 'A' )@ is a perfect match for the number and parameter type of function (2). 281 282 Ada, Scala, and \CFA type-systems also use the return type to pinpoint the best-overloaded name in resolving a call. 283 283 \begin{cfa} 284 284 int f( void ); $\C[1.75in]{// (4); overloaded on return type}$ … … 302 302 } 303 303 \end{cfa} 304 The \CFA type system simplytreats overloaded variables as an overloaded function returning a value with no parameters.304 The \CFA type system treats overloaded variables as an overloaded function returning a value with no parameters. 305 305 Hence, no significant effort is required to support this feature. 306 306 … … 312 312 313 313 All 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. 315 315 Like \CC, \CFA has multiple auto-generated constructors for every type. 316 316 317 317 The 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.318 The first parameter is logically the \lstinline[language=C++]{this} or \lstinline[language=Python]{self} in other object-oriented languages and implicitly passed. 319 319 \VRef[Figure]{f:CFAConstructorDestructor} shows an example of creating and using a constructor and destructor. 320 320 Both constructor and destructor can be explicitly called to reuse a variable. … … 350 350 351 351 The 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 )@; 353 353 @1@ is an additive identity in unary operators @++@ and @--@. 354 354 Aware of their significance, \CFA provides a special type @zero_t@ and @one_t@ for custom types. … … 385 385 bar( s ); 386 386 \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.387 The 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. 388 388 Unlike 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. 389 389 … … 392 392 393 393 A @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.394 A common practice is refactoring the assertions into a named \newterm{trait}, similar to other languages like Go and Rust. 395 395 \begin{cfa} 396 396 forall(T) trait @Bird@ { … … 407 407 bird_fly( 23, robin ); 408 408 \end{cfa} 409 Grouping type assertions into a named trait effectively creates a reusable interface for parametric -polymorphic types.409 Grouping type assertions into a named trait effectively creates a reusable interface for parametric polymorphic types. 410 410 411 411 … … 417 417 418 418 The \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;419 Finding an exact match is not discussed here, because the mechanism is fairly straightforward, even when the search space is ample; 420 420 only finding a non-exact match is discussed in detail. 421 421 … … 425 425 426 426 Most 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 withprogrammer's expectations.428 C is an aggressive language as it provides conversions among almost all of thebasic types, even when the conversion is potentially unsafe or not meaningful, \ie @float@ to @bool@.427 otherwise, the program becomes littered with many explicit casts which do not match the programmer's expectations. 428 C 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@. 429 429 C 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, acommon 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}.430 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}. 431 431 432 432 \CFA generalizes ``usual arithmetic conversion'' to \newterm{conversion cost}. … … 438 438 @poly@ is the number of polymorphic function parameters, and 439 439 \item 440 @safe@ is sum of the degree of safe (widening) conversions.440 @safe@ is the sum of the degree of safe (widening) conversions. 441 441 \end{enumerate} 442 442 Sum of degree is a method to quantify C's integer and floating-point rank. 443 443 Every 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 distancefrom @int@ to @long long int@ is 2.444 For example, the distance from @char@ to @int@ is 2, from @int@ to @long@ is 1, and from @int@ to @long long int@ is 2. 445 445 This 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.446 For example, the @char@ and @signed char@ ranks are the same in C, but the distance from @char@ to @signed char@ is assigned 1. 447 447 @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 choosea 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 :448 Among 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 450 For example, assume the overloaded function @foo@ is called with two @int@ parameters. 451 The cost for every overloaded @foo@ has been listed along with the following: 452 452 \begin{cfa} 453 453 void foo( char, char ); $\C[2.5in]{// (1) (2, 0, 0)}$ … … 479 479 \CFA favours candidates with more restrictions on polymorphism, so @forall( T ) void foo( T, T )@ has lower cost. 480 480 @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 mean smore constraints on argument types, making the function less generic.481 For every type assertion in the @forall@ clause (no assertions in the above example), \CFA subtracts one from @specialization@. 482 More type assertions mean more constraints on argument types, making the function less generic. 483 483 484 484 \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 t wo types.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 the two types. 486 486 For example, the conversion cost from @int@ to a @struct S@ is @infinite@. 487 487 488 488 In \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 toa 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 ainfinite conversion cost and a non-infinite cast cost.489 For most cast-expression resolutions, a cast cost equals 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 as having an infinite conversion cost and a non-infinite cast cost. -
doc/theses/jiada_liang_MMath/conclusion.tex
rc1c0efdb r7568e5c 50 50 enum( wchar_t * ) { Jack = L"John" }; 51 51 \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. 52 There are several new features have been proposed or are developing in parallel with enumerations. 53 Two closely related features are iterator and namespace. 54 55 Enumerating features, and range loops in particular, are currently implemented as loops unique to \CFA enumeration and do not align with the 56 general iterator pattern. They can be adapted to the iterator interface when it comes to maturity. 57 58 Currently, \CFA implements a namespace feature for enumerated types only. There is recently a proposal by Andrew to 59 generalize the concept of namespace to other types. The enumeration scope will be revisited to follow the same semantics 60 as other types. Also to improve the granularity of scope control, we propose the following extension: 55 61 \begin{cfa} 56 62 enum E1 { @!@A, @^@B, C }; -
doc/theses/jiada_liang_MMath/test.adb
rc1c0efdb r7568e5c 2 2 -- with Ada.Standard; use Ada.Standard; 3 3 procedure test is 4 type GBR is ( Green, Blue, Red ); 4 5 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 ); 6 7 Colour : RGB := Red; 7 8 … … 95 96 96 97 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 ) ) & " " ); 97 104 end test; 98 105 -
doc/theses/jiada_liang_MMath/test.cc
rc1c0efdb r7568e5c 61 61 eca[A] = EC::A; 62 62 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; 64 66 Week day = Mon; 65 67 if ( day <= Fri ) cout << "weekday" << endl; -
doc/theses/jiada_liang_MMath/test.go
rc1c0efdb r7568e5c 20 20 21 21 22 const ( R = 0; G = 3; B ) // implicit: 0 0 022 const ( R = 0; G = 3; B = 3; TT = 3 ) // implicit: 0 3 3 23 23 const ( Fred = "Fred"; Mary = "Mary"; Jane = "Jane" ) // Fred Mary Jane 24 24 const ( H = 0; Jack = "Jack"; J; K = 0; I ) // type change, implicit: 0 Jack Jack 25 25 const ( C = iota + G; M = iota; Y ) 26 26 const ( Mon = iota; Tue; Wed; // 0, 1, 2 27 Thu = 10; Fri = iota - Wed + Thu - 1; Sat; Sun = iota) // 10, 11, 12, 1327 Thu = 10; Fri = iota - Wed + Thu - 1; Sat; Sun = 0 ) // 10, 11, 12, 13 28 28 const ( O1 = iota + 1; _; O3; _; O5 ) // 1, 3, 5 29 29 const ( V1 = iota; V2; V3 = 7; V4 = iota + 1; V5 ) … … 34 34 35 35 func main() { 36 fmt.Println( "Go:") 36 37 if 3 == R {}; 37 38 fmt.Println( R, G, B ) … … 45 46 46 47 day := Mon; 48 day = Sun; 49 47 50 switch day { 48 51 case Mon, Tue, Wed, Thu, Fri: 49 52 fmt.Println( "weekday" ); 50 case Sat , Sun:53 case Sat: 51 54 fmt.Println( "weekend" ); 52 55 } … … 54 57 fmt.Println( i ) 55 58 } 59 fmt.Println(B < TT); 60 } // main 56 61 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 4 4 Weekday = Mon..Fri; 5 5 Weekend = Sat..Sun; 6 type Count = ( Zero, One, Two, Ten = 10, Eleven ); 6 type Count = ( Zero, One, Two, Ten = 10, Eleven=10 ); 7 type RR = ( A, B, C ); 8 7 9 var day : Week; 8 10 wday : Weekday; … … 10 12 lunch : array[Week] of Integer; 11 13 cnt : Count; 14 // procedure P1(v:Week); 15 // begin 16 // Writeln('Week'); 17 // end; 18 procedure P1(v:Weekday); 19 begin 20 Writeln('Weekday'); 21 end; 22 procedure P1(v:RR); 23 begin 24 Writeln('RR'); 25 end; 12 26 begin 13 27 day := Sat; … … 40 54 Writeln(); 41 55 for day := Mon to Sat do 56 lunch[day] := ord(day) * 10; 57 for day := Mon to Sun do 42 58 Write( lunch[day], ' ' ); 43 59 Writeln(); … … 45 61 Write( ord( cnt ), ' ' ); 46 62 end; 63 day := Tue; 64 P1( day ); 47 65 Writeln(); 66 67 case (day) of 68 Mon: writeln('Excellent!' ); 69 Tue: writeln('Well done' ); 70 end; 48 71 end. 49 72 -
doc/theses/jiada_liang_MMath/test.py
rc1c0efdb r7568e5c 25 25 # Mon = 1; Tue = 2; Wed = 3; Thu = 10; Fri = 10; Sat = 16; Sun = 17 26 26 class Week(OrderedEnum): 27 Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 727 Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; Sat = 6; Sun = 0 28 28 def isWeekday(self): 29 29 return Week(self.value) <= Week.Fri … … 34 34 return cls(date.isoweekday()) 35 35 36 day : Week = Week.Tue ;36 day : Week = Week.Tue 37 37 print( "weekday:", day.isWeekday() ) 38 38 print( "weekend:", day.isWeekend() ) 39 39 print( "today:", Week.today(date.today())) 40 40 41 print( Week.Thu.value == 4 ) ;42 print( Week.Thu.name == "Thu" ) ;43 print( Week( 4 ) == Week.Thu ) ;44 print( Week["Thu"].value == 4 ) ;41 print( Week.Thu.value == 4 ) 42 print( Week.Thu.name == "Thu" ) 43 print( Week( 4 ) == Week.Thu ) 44 print( Week["Thu"].value == 4 ) 45 45 46 46 if day <= Week.Fri : 47 print( "weekday" ) ;47 print( "weekday" ) 48 48 match day: 49 49 case Week.Mon | Week.Tue | Week.Wed | Week.Thu | Week.Fri: 50 print( "weekday" ) ;50 print( "weekday" ) 51 51 case Week.Sat | Week.Sun: 52 print( "weekend" ) ;52 print( "weekend" ) 53 53 54 54 for day in Week: … … 80 80 print( isinstance(Week.Fri, Week) ) 81 81 82 class WeekE(OrderedEnum): pass ;82 class WeekE(OrderedEnum): pass 83 83 class WeekDay(WeekE): Mon = 1; Tue = 2; Wed = 3; Thu = 4; Fri = 5; 84 84 class WeekEnd(WeekE): Sat = 6; Sun = 7 … … 121 121 Weekend = Sat | Sun 122 122 print( f"0x{repr(WeekF.Weekday.value)} 0x{repr(WeekF.Weekend.value)}" ) 123 day : WeekF = WeekF.Mon | WeekF.Tue ;123 day : WeekF = WeekF.Mon | WeekF.Tue 124 124 print( type(day) ) 125 125 for day in WeekF: … … 164 164 match diffval: 165 165 case Diff.Int: 166 print( "diffval", diffval.value ) ;166 print( "diffval", diffval.value ) 167 167 case Diff.Float: 168 print( "diffval", diffval.value ) ;168 print( "diffval", diffval.value ) 169 169 case Diff.Str: 170 print( "diffval", diffval.value ) ;170 print( "diffval", diffval.value ) 171 171 for i in Diff: 172 172 print( f"Diff type {type(i)}, {i}, {i.name}, {i.value} : " ) … … 197 197 return G * self.mass / (self.radius * self.radius) 198 198 def surfaceWeight(self, otherMass): 199 return otherMass * self.surfaceGravity(); 199 return otherMass * self.surfaceGravity() 200 201 class Cats(Enum): 202 pass 203 200 204 201 205 earthWeight : float = 100 202 earthMass : float = earthWeight / ( Planet.EARTH.surfaceGravity() ) ;206 earthMass : float = earthWeight / ( Planet.EARTH.surfaceGravity() ) 203 207 204 208 p = by_position( Planet, random.randrange(8) ) # select a random orbiting body -
doc/theses/jiada_liang_MMath/test.swift
rc1c0efdb r7568e5c 59 59 60 60 enum WeekInt: Int, CaseIterable { 61 case Mon, Tue, Wed, Thu = 10, Fri ,61 case Mon, Tue, Wed, Thu = 10, Fri = 14, 62 62 Sat = 4, Sun // auto-incrementing 63 63 }; -
doc/theses/jiada_liang_MMath/test1.java
rc1c0efdb r7568e5c 3 3 public class test1 { 4 4 enum Weekday { 5 Mon(7), Tue(6), Wed(5), Thu(3), Fri( 3), Sat(3), Sun(1); // must appear first5 Mon(7), Tue(6), Wed(5), Thu(3), Fri(4), Sat(3), Sun(7); // must appear first 6 6 private long day; 7 7 private Weekday( long d ) { day = d; } … … 27 27 } 28 28 for ( Weekday icday : Weekday.values() ) { // position 29 System.out.print ( icday + " " + icday.ordinal() + " " + icday.day + " " + icday.name() + ", " ); // label29 System.out.println( icday + " " + icday.ordinal() + " " + icday.day + " " + icday.name() + ", " ); // label 30 30 } 31 31 System.out.println(); 32 33 if (Weekday.Fri == Weekday.Sat) { 34 System.out.println( "Alias "); 35 } 32 36 } 33 37 }
Note: See TracChangeset
for help on using the changeset viewer.