- Timestamp:
- Apr 12, 2017, 9:14:39 AM (7 years ago)
- Branches:
- ADT, aaron-thesis, arm-eh, ast-experimental, cleanup-dtors, deferred_resn, demangler, enum, forall-pointer-decay, jacob/cs343-translation, jenkins-sandbox, master, new-ast, new-ast-unique-expr, new-env, no_list, persistent-indexer, pthread-emulation, qualifiedEnum, resolv-new, with_gc
- Children:
- f3be342
- Parents:
- da1c772
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
doc/generic_types/generic_types.tex
rda1c772 r3720bf8f 19 19 \newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@commentstyle{#2}}} 20 20 \newcommand{\CRT}{\global\columnposn=\gcolumnposn} 21 22 \newcommand{\TODO}[1]{\textbf{TODO}: {\itshape #1}} % TODO included 23 %\newcommand{\TODO}[1]{} % TODO elided 24 % Latin abbreviation 25 \newcommand{\abbrevFont}{\textit} % set empty for no italics 26 \newcommand*{\eg}{% 27 \@ifnextchar{,}{\abbrevFont{e}.\abbrevFont{g}.}% 28 {\@ifnextchar{:}{\abbrevFont{e}.\abbrevFont{g}.}% 29 {\abbrevFont{e}.\abbrevFont{g}.,\xspace}}% 30 }% 31 \newcommand*{\ie}{% 32 \@ifnextchar{,}{\abbrevFont{i}.\abbrevFont{e}.}% 33 {\@ifnextchar{:}{\abbrevFont{i}.\abbrevFont{e}.}% 34 {\abbrevFont{i}.\abbrevFont{e}.,\xspace}}% 35 }% 36 \newcommand*{\etc}{% 37 \@ifnextchar{.}{\abbrevFont{etc}}% 38 {\abbrevFont{etc}.\xspace}% 39 }% 40 \newcommand{\etal}{% 41 \@ifnextchar{.}{\abbrevFont{et~al}}% 42 {\abbrevFont{et al}.\xspace}% 43 }% 44 % \newcommand{\eg}{\textit{e}.\textit{g}.,\xspace} 45 % \newcommand{\ie}{\textit{i}.\textit{e}.,\xspace} 46 % \newcommand{\etc}{\textit{etc}.,\xspace} 21 47 \makeatother 22 48 … … 30 56 \newcommand{\CS}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace} 31 57 \newcommand{\Textbf}[1]{{\color{red}\textbf{#1}}} 32 33 \newcommand{\TODO}[1]{\textbf{TODO}: {\itshape #1}} % TODO included34 %\newcommand{\TODO}[1]{} % TODO elided35 \newcommand{\eg}{\textit{e}.\textit{g}.,\xspace}36 \newcommand{\ie}{\textit{i}.\textit{e}.,\xspace}37 \newcommand{\etc}{\textit{etc}.,\xspace}38 58 39 59 % CFA programming language, based on ANSI C (with some gcc additions) … … 155 175 (4) Extensions introduced by \CFA must be translated in the most efficient way possible. 156 176 These goals ensure existing C code-bases can be converted to \CFA incrementally with minimal effort, and C programmers can productively generate \CFA code without training beyond the features being used. 157 We claim \CC is diverging from C, and hence, incremental additions of language features require significant effort and training, while suffering from historically poor design choices.177 Unfortunately, \CC is actively diverging from C, so incremental additions require significant effort and training, coupled with multiple legacy design-choices that cannot be updated. 158 178 159 179 \CFA is currently implemented as a source-to-source translator from \CFA to the GCC-dialect of C~\citep{GCCExtensions}, allowing it to leverage the portability and code optimizations provided by GCC, meeting goals (1)-(3). Ultimately, a compiler is necessary for advanced features and optimal performance. … … 179 199 int val = twice( twice( 3.7 ) ); 180 200 \end{lstlisting} 181 which works for any type @T@ with a matching addition operator. The polymorphism is achieved by creating a wrapper function for calling @+@ with @T@ bound to @double@, then passing this function to the first call of @twice@. There is now the option of using the same @twice@ and converting the result to @int@ on assignment, or creating another @twice@ with type parameter @T@ bound to @int@ because \CFA uses the return type (as in~\cite{Ada})in its type analysis.201 which works for any type @T@ with a matching addition operator. The polymorphism is achieved by creating a wrapper function for calling @+@ with @T@ bound to @double@, then passing this function to the first call of @twice@. There is now the option of using the same @twice@ and converting the result to @int@ on assignment, or creating another @twice@ with type parameter @T@ bound to @int@ because \CFA uses the return type, as in~\cite{Ada}, in its type analysis. 182 202 The first approach has a late conversion from @double@ to @int@ on the final assignment, while the second has an eager conversion to @int@. \CFA minimizes the number of conversions and their potential to lose information, so it selects the first approach, which corresponds with C-programmer intuition. 183 203 … … 187 207 \begin{lstlisting} 188 208 void * bsearch( const void * key, const void * base, size_t nmemb, size_t size, 189 int (* compar)( const void *, const void *));209 int (* compar)( const void *, const void * )); 190 210 int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 : 191 211 *(double *)t2 < *(double *)t1 ? 1 : 0; } … … 205 225 int posn = bsearch( 5.0, vals, 10 ); 206 226 \end{lstlisting} 207 The nested routine@comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.208 Providing a hidden @comp@ routinein \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.227 The nested function @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result. 228 Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope. 209 229 As well, an alternate kind of return is made available: position versus pointer to found element. 210 230 \CC's type-system cannot disambiguate between the two versions of @bsearch@ because it does not use the return type in overload resolution, nor can \CC separately compile a templated @bsearch@. … … 250 270 Hence, the single name @MAX@ replaces all the C type-specific names: @SHRT_MAX@, @INT_MAX@, @DBL_MAX@. 251 271 As well, restricted constant overloading is allowed for the values @0@ and @1@, which have special status in C, \eg the value @0@ is both an integer and a pointer literal, so its meaning depends on context. 252 In addition, several operations are defined in terms values @0@ and @1@. 253 For example, 272 In addition, several operations are defined in terms values @0@ and @1@, \eg: 254 273 \begin{lstlisting} 255 274 int x; … … 278 297 \end{lstlisting} 279 298 280 In fact, the set of operators is incomplete, \eg no assignment, but @otype@ is syntactic sugar for the following implicit trait:299 In fact, the set of trait operators is incomplete, as there is no assignment requirement for type @T@, but @otype@ is syntactic sugar for the following implicit trait: 281 300 \begin{lstlisting} 282 301 trait otype( dtype T | sized(T) ) { // sized is a pseudo-trait for types with known size and alignment … … 308 327 % \end{lstlisting} 309 328 310 The \CFA type-system uses \emph{nominal typing} for concrete types, matching with the C type-system.and \emph{structural typing} for polymorphic types.329 In summation, the \CFA type-system uses \emph{nominal typing} for concrete types, matching with the C type-system and \emph{structural typing} for polymorphic types. 311 330 Hence, trait names play no part in type equivalence; 312 331 the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites. … … 344 363 \section{Generic Types} 345 364 346 One of the known shortcomings of standard C is that it does not provide reusable type-safe abstractions for generic data structures and algorithms. Broadly speaking, there are three approaches to create data structures in C. One approach is to write bespoke data structures for each context in which they are needed. While this approach is flexible and supports integration with the C type-checker and tooling, it is also tedious and error-prone, especially for more complex data structures. A second approach is to use @void *@--based polymorphism. This approach is taken by the C standard library functions @bsearch@ and @qsort@, and does allow the use of common code for common functionality. However, basing all polymorphism on @void *@ eliminates the type-checker's ability to ensure that argument types are properly matched, often requiring a number of extra function parameters, pointer indirection, and dynamic allocation that would not otherwise be needed. A third approach to generic code is to use pre-processor macros, which does allow the generated code to be both generic and type-checked, but errors may be difficult to interpret. Furthermore, writing and using preprocessor macros can be unnatural and inflexible. 365 One of the known shortcomings of standard C is that it does not provide reusable type-safe abstractions for generic data structures and algorithms. Broadly speaking, there are three approaches to create data structures in C. One approach is to write bespoke data structures for each context in which they are needed. While this approach is flexible and supports integration with the C type-checker and tooling, it is also tedious and error-prone, especially for more complex data structures. 366 A second approach is to use @void *@--based polymorphism, \eg the C standard-library functions @bsearch@ and @qsort@, and does allow the use of common code for common functionality. However, basing all polymorphism on @void *@ eliminates the type-checker's ability to ensure that argument types are properly matched, often requiring a number of extra function parameters, pointer indirection, and dynamic allocation that would not otherwise be needed. 367 A third approach to generic code is to use preprocessor macros, which does allow the generated code to be both generic and type-checked, but errors may be difficult to interpret. Furthermore, writing and using preprocessor macros can be unnatural and inflexible. 347 368 348 369 Other languages use \emph{generic types}, \eg \CC and Java, to produce type-safe abstract data-types. \CFA also implements generic types that integrate efficiently and naturally with the existing polymorphic functions, while retaining backwards compatibility with C and providing separate compilation. However, for known concrete parameters, the generic type can be inlined, like \CC templates. … … 359 380 pair( const char *, int ) p = { "magic", 42 }; 360 381 int magic = value( p ); 361 362 382 pair( void *, int * ) q = { 0, &p.second }; 363 383 magic = value_p( q ); 364 365 384 double d = 1.0; 366 385 pair( double *, double * ) r = { &d, &d }; … … 368 387 \end{lstlisting} 369 388 370 \CFA classifies generic types as either \emph{concrete} or \emph{dynamic}. Concrete have a fixed memory layout regardless of type parameters, while dynamic vary in memory layout depending on their type parameters. A type may have polymorphic parameters but still be concrete, arecalled \emph{dtype-static}. Polymorphic pointers are an example of dtype-static types, \eg @forall(dtype T) T *@ is a polymorphic type, but for any @T@, @T *@ is a fixed-sized pointer, and therefore, can be represented by a @void *@ in code generation.389 \CFA classifies generic types as either \emph{concrete} or \emph{dynamic}. Concrete have a fixed memory layout regardless of type parameters, while dynamic vary in memory layout depending on their type parameters. A type may have polymorphic parameters but still be concrete, called \emph{dtype-static}. Polymorphic pointers are an example of dtype-static types, \eg @forall(dtype T) T *@ is a polymorphic type, but for any @T@, @T *@ is a fixed-sized pointer, and therefore, can be represented by a @void *@ in code generation. 371 390 372 391 \CFA generic types also allow checked argument-constraints. For example, the following declaration of a sorted set-type ensures the set key supports equality and relational comparison: … … 378 397 \subsection{Concrete Generic-Types} 379 398 380 The \CFA translator template-expands concrete generic-types into new structure types, affording maximal inlining. To enable inter-operation among equivalent instantiations of a generic type, the translator saves the set of instantiations currently in scope and reuses the generated structure declarations where appropriate. For example, a function declaration that accepts or returns a concrete generic 399 The \CFA translator template-expands concrete generic-types into new structure types, affording maximal inlining. To enable inter-operation among equivalent instantiations of a generic type, the translator saves the set of instantiations currently in scope and reuses the generated structure declarations where appropriate. For example, a function declaration that accepts or returns a concrete generic-type produces a declaration for the instantiated struct in the same scope, which all callers may reuse. For example, the concrete instantiation for @pair( const char *, int )@ is: 381 400 \begin{lstlisting} 382 401 struct _pair_conc1 { … … 386 405 \end{lstlisting} 387 406 388 A concrete generic 407 A concrete generic-type with dtype-static parameters is also expanded to a structure type, but this type is used for all matching instantiations. In the above example, the @pair( F *, T * )@ parameter to @value_p@ is such a type; its expansion is below and it is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate: 389 408 \begin{lstlisting} 390 409 struct _pair_conc0 { … … 397 416 \subsection{Dynamic Generic-Types} 398 417 399 Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types. As mentioned in Section~\ref{sec:poly-fns}, @otype@ function parameters (in fact all @sized@ polymorphic parameters) come with implicit size and alignment parameters provided by the caller. Dynamic generic-types also have an \emph{offset array} containing structure member-offsets. Dynamic generic-union needs no such offset array, as all members are at offset 0 but size and alignment are still necessary. Access to members of a dynamic structure is provided at runtime via base-displacement addressing with the structure pointer and the member offset (similar to the @offsetof@ macro), moving a compile-time offset calculation to runtime. 400 401 The offset arrays are statically generated where possible. If a dynamic generic-type is declared to be passed or returned by value from a polymorphic function, the translator can safely assume the generic type is complete (\ie has a known layout) at any call-site, and the offset array is passed from the caller; if the generic type is concrete at the call site the elements of this offset array can even be statically generated using the C @offsetof@ macro. As an example, @p.second@ in the @value@ function above is implemented as @*(p + _offsetof_pair[1])@, where @p@ is a @void *@, and @_offsetof_pair@ is the offset array passed into @value@ for @pair( const char *, T )@. The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) };@. 402 403 In some cases the offset arrays cannot be statically generated. For instance, modularity is generally provided in C by including an opaque forward-declaration of a struct and associated accessor and mutator routines in a header file, with the actual implementations in a separately-compiled @.c@ file. \CFA supports this pattern for generic types, but caller does not know the actual layout or size of the dynamic generic-type, and only holds it by a pointer. The \CFA translator automatically generates \emph{layout functions} for cases where the size, alignment, and offset array of a generic struct cannot be passed into a function from that function's caller. These layout functions take as arguments pointers to size and alignment variables and a caller-allocated array of member offsets, as well as the size and alignment of all @sized@ parameters to the generic structure (un-@sized@ parameters are forbidden from the language from being used in a context that affects layout). Results of these layout functions are cached so that they are only computed once per type per function. %, as in the example below for @pair@. 418 Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types. 419 As mentioned in Section~\ref{sec:poly-fns}, @otype@ function parameters (in fact all @sized@ polymorphic parameters) come with implicit size and alignment parameters provided by the caller. 420 Dynamic generic-types also have an \emph{offset array} containing structure member-offsets. 421 A dynamic generic-union needs no such offset array, as all members are at offset 0 but size and alignment are still necessary. 422 Access to members of a dynamic structure is provided at runtime via base-displacement addressing with the structure pointer and the member offset (similar to the @offsetof@ macro), moving a compile-time offset calculation to runtime. 423 424 The offset arrays are statically generated where possible. 425 If a dynamic generic-type is declared to be passed or returned by value from a polymorphic function, the translator can safely assume the generic type is complete (\ie has a known layout) at any call-site, and the offset array is passed from the caller; 426 if the generic type is concrete at the call site, the elements of this offset array can even be statically generated using the C @offsetof@ macro. 427 As an example, @p.second@ in the @value@ function above is implemented as @*(p + _offsetof_pair[1])@, where @p@ is a @void *@, and @_offsetof_pair@ is the offset array passed into @value@ for @pair( const char *, T )@. 428 The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) }@. 429 430 In some cases the offset arrays cannot be statically generated. For instance, modularity is generally provided in C by including an opaque forward-declaration of a structure and associated accessor and mutator functions in a header file, with the actual implementations in a separately-compiled @.c@ file. 431 \CFA supports this pattern for generic types, but the caller does not know the actual layout or size of the dynamic generic-type, and only holds it by a pointer. 432 The \CFA translator automatically generates \emph{layout functions} for cases where the size, alignment, and offset array of a generic struct cannot be passed into a function from that function's caller. 433 These layout functions take as arguments pointers to size and alignment variables and a caller-allocated array of member offsets, as well as the size and alignment of all @sized@ parameters to the generic structure (un@sized@ parameters are forbidden from being used in a context that affects layout). 434 Results of these layout functions are cached so that they are only computed once per type per function. %, as in the example below for @pair@. 404 435 % \begin{lstlisting} 405 436 % static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair, … … 425 456 % } 426 457 % \end{lstlisting} 427 Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature. For instance, a function that strips duplicate values from an unsorted @vector(T)@ would likely have a pointer to the vector as its only explicit parameter, but use some sort of @set(T)@ internally to test for duplicate values. This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function. 428 429 Whether a type is concrete, dtype-static, or dynamic is decided solely on the type parameters and @forall@ clause on a declaration. This design allows opaque forward declarations of generic types, \eg @forall(otype T) struct Box@ -- like in C, all uses of @Box(T)@ can be separately compiled, and callers from other translation units know the proper calling conventions to use. If the definition of a structure type is included in deciding whether a generic type is dynamic or concrete, some further types may be recognized as dtype-static (\eg @forall(otype T) struct unique_ptr { T* p };@ does not depend on @T@ for its layout, but the existence of an @otype@ parameter means that it \emph{could}.), but preserving separate compilation (and the associated C compatibility) in the existing design is judged to be an appropriate trade-off. 458 Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature. 459 For instance, a function that strips duplicate values from an unsorted @vector(T)@ would likely have a pointer to the vector as its only explicit parameter, but use some sort of @set(T)@ internally to test for duplicate values. 460 This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function. 461 462 Whether a type is concrete, dtype-static, or dynamic is decided solely on the type parameters and @forall@ clause on a declaration. 463 This design allows opaque forward declarations of generic types, \eg @forall(otype T) struct Box@ -- like in C, all uses of @Box(T)@ can be separately compiled, and callers from other translation units know the proper calling conventions to use. 464 If the definition of a structure type is included in deciding whether a generic type is dynamic or concrete, some further types may be recognized as dtype-static (\eg @forall(otype T) struct unique_ptr { T* p }@ does not depend on @T@ for its layout, but the existence of an @otype@ parameter means that it \emph{could}.), but preserving separate compilation (and the associated C compatibility) in the existing design is judged to be an appropriate trade-off. 430 465 431 466 … … 435 470 The reuse of dtype-static structure instantiations enables useful programming patterns at zero runtime cost. The most important such pattern is using @forall(dtype T) T *@ as a type-checked replacement for @void *@, \eg creating a lexicographic comparison for pairs of pointers used by @bsearch@ or @qsort@: 436 471 \begin{lstlisting} 437 forall(dtype T) int lexcmp( pair( T *, T * ) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {472 forall(dtype T) int lexcmp( pair( T *, T * ) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) { 438 473 int c = cmp( a->first, b->first ); 439 474 if ( c == 0 ) c = cmp( a->second, b->second ); … … 441 476 } 442 477 \end{lstlisting} 443 Since @pair(T *, T *)@ is a concrete type, there are no implicit parameters passed to @lexcmp@, so the generated code is identical to a function written in standard C using @void *@, yet the \CFA version is type-checked to ensure the fields of both pairs and the arguments to the comparison function match in type. 444 445 Another useful pattern enabled by reused dtype-static type instantiations is zero-cost ``tag'' structures. Sometimes a particular bit of information is only useful for type-checking, and can be omitted at runtime. Tag structs can be used to provide this information to the compiler without further runtime overhead, as in the following example: 478 Since @pair(T *, T * )@ is a concrete type, there are no implicit parameters passed to @lexcmp@, so the generated code is identical to a function written in standard C using @void *@, yet the \CFA version is type-checked to ensure the fields of both pairs and the arguments to the comparison function match in type. 479 480 Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \emph{tag-structures}. 481 Sometimes information is only used for type-checking and can be omitted at runtime, \eg: 446 482 \begin{lstlisting} 447 483 forall(dtype Unit) struct scalar { unsigned long value; }; 448 449 484 struct metres {}; 450 485 struct litres {}; … … 453 488 return (scalar(U)){ a.value + b.value }; 454 489 } 455 456 490 scalar(metres) half_marathon = { 21093 }; 457 491 scalar(litres) swimming_pool = { 2500000 }; 458 459 492 scalar(metres) marathon = half_marathon + half_marathon; 460 493 scalar(litres) two_pools = swimming_pool + swimming_pool; 461 494 marathon + swimming_pool; $\C{// compilation ERROR}$ 462 495 \end{lstlisting} 463 @scalar@ is a dtype-static type, so all uses have a single structure definition, containing a single @unsigned long@, and can share the same implementations of common routines like @?+?@ -- these implementations may even be separately compiled, unlike \CC template functions. However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume. 496 @scalar@ is a dtype-static type, so all uses have a single structure definition, containing @unsigned long@, and can share the same implementations of common functions like @?+?@. 497 These implementations may even be separately compiled, unlike \CC template functions. 498 However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume. 464 499 465 500 \section{Tuples} … … 468 503 The @pair(R, S)@ generic type used as an example in the previous section can be considered a special case of a more general \emph{tuple} data structure. The authors have implemented tuples in \CFA, with a design particularly motivated by two use cases: \emph{multiple-return-value functions} and \emph{variadic functions}. 469 504 470 In standard C, functions can return at most one value. This restriction results in code that emulates functions with multiple return values by \emph{aggregation} or by \emph{aliasing}. In the former situation, the function designer creates a record type that combines all of the return values into a single type. Unfortunately, the designer must come up with a name for the return type and for each of its fields. Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model. As such, this technique is effective when used sparingly, but can quickly get out of hand if many functions need to return different combinations of types. In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters. The pointer parameters are assigned inside of the routine body to emulate a return. Using this approach, the caller is directly responsible for allocating storage for the additional temporary return values. This responsibility complicates the call site with a sequence of variable declarations leading up to the call. Also, while a disciplined use of @const@ can give clues about whether a pointer parameter is going to be used as an out parameter, it is not immediately obvious from only the routine signature whether the callee expects such a parameter to be initialized before the call. Furthermore, while many C routines that accept pointers are designed so that it is safe to pass @NULL@ as a parameter, there are many C routines that are not null-safe. On a related note, C does not provide a standard mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler.505 In standard C, functions can return at most one value. This restriction results in code that emulates functions with multiple return values by \emph{aggregation} or by \emph{aliasing}. In the former situation, the function designer creates a record type that combines all of the return values into a single type. Unfortunately, the designer must come up with a name for the return type and for each of its fields. Unnecessary naming is a common programming language issue, introducing verbosity and a complication of the user's mental model. As such, this technique is effective when used sparingly, but can quickly get out of hand if many functions need to return different combinations of types. In the latter approach, the designer simulates multiple return values by passing the additional return values as pointer parameters. The pointer parameters are assigned inside of the function body to emulate a return. Using this approach, the caller is directly responsible for allocating storage for the additional temporary return values. This responsibility complicates the call site with a sequence of variable declarations leading up to the call. Also, while a disciplined use of @const@ can give clues about whether a pointer parameter is going to be used as an out parameter, it is not immediately obvious from only the function signature whether the callee expects such a parameter to be initialized before the call. Furthermore, while many C functions that accept pointers are designed so that it is safe to pass @NULL@ as a parameter, there are many C functions that are not null-safe. On a related note, C does not provide a standard mechanism to state that a parameter is going to be used as an additional return value, which makes the job of ensuring that a value is returned more difficult for the compiler. 471 506 472 507 C does provide a mechanism for variadic functions through manipulation of @va_list@ objects, but it is notoriously type-unsafe. A variadic function is one that contains at least one parameter, followed by @...@ as the last token in the parameter list. In particular, some form of \emph{argument descriptor} is needed to inform the function of the number of arguments and their types, commonly a format string or counter parameter. It is important to note that both of these mechanisms are inherently redundant, because they require the user to specify information that the compiler knows explicitly. This required repetition is error prone, because it is easy for the user to add or remove arguments without updating the argument descriptor. In addition, C requires the programmer to hard code all of the possible expected types. As a result, it is cumbersome to write a variadic function that is open to extension. For example, consider a simple function that sums $N$ @int@s: … … 491 526 In practice, compilers can provide warnings to help mitigate some of the problems. For example, GCC provides the @format@ attribute to specify that a function uses a format string, which allows the compiler to perform some checks related to the standard format specifiers. Unfortunately, this attribute does not permit extensions to the format string syntax, so a programmer cannot extend it to warn for mismatches with custom types. 492 527 528 493 529 \subsection{Tuple Expressions} 494 530 … … 497 533 \CFA allows declaration of \emph{tuple variables}, variables of tuple type. For example: 498 534 \begin{lstlisting} 499 [int, char] most_frequent(const char *);535 [int, char] most_frequent(const char * ); 500 536 501 537 const char* str = "hello, world!"; … … 741 777 Unlike C, it is not necessary to hard code the expected type. This code is naturally open to extension, in that any user-defined type with a @?+?@ operator is automatically able to be used with the @sum@ function. That is to say, the programmer who writes @sum@ does not need full program knowledge of every possible data type, unlike what is necessary to write an equivalent function using the standard C mechanisms. Summing arbitrary heterogeneous lists is possible with similar code by adding the appropriate type variables and addition operators. 742 778 743 It is also possible to write a type-safe variadic print routinewhich can replace @printf@:779 It is also possible to write a type-safe variadic print function which can replace @printf@: 744 780 \begin{lstlisting} 745 781 struct S { int x, y; }; … … 756 792 print("s = ", (S){ 1, 2 }, "\n"); 757 793 \end{lstlisting} 758 This example routine showcases a variadic-template-like decomposition of the provided argument list. The individual @print@ routines allow printing a single element of a type. The polymorphic @print@ allows printing any list of types, as long as each individual type has a @print@ function. The individual print functions can be used to build up more complicated @print@ routines, such as for @S@, which is something that cannot be done with @printf@ in C.794 This example function showcases a variadic-template-like decomposition of the provided argument list. The individual @print@ functions allow printing a single element of a type. The polymorphic @print@ allows printing any list of types, as long as each individual type has a @print@ function. The individual print functions can be used to build up more complicated @print@ functions, such as for @S@, which is something that cannot be done with @printf@ in C. 759 795 760 796 It is also possible to use @ttype@ polymorphism to provide arbitrary argument forwarding functions. For example, it is possible to write @new@ as a library function:
Note: See TracChangeset
for help on using the changeset viewer.