Changeset 3720bf8f for doc


Ignore:
Timestamp:
Apr 12, 2017, 9:14:39 AM (8 years ago)
Author:
Peter A. Buhr <pabuhr@…>
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
Message:

more cleanup for pages 1-8

File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/generic_types/generic_types.tex

    rda1c772 r3720bf8f  
    1919\newcommand{\C}[2][\@empty]{\ifx#1\@empty\else\global\setlength{\columnposn}{#1}\global\columnposn=\columnposn\fi\hfill\makebox[\textwidth-\columnposn][l]{\lst@commentstyle{#2}}}
    2020\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}
    2147\makeatother
    2248
     
    3056\newcommand{\CS}{C\raisebox{-0.7ex}{\Large$^\sharp$}\xspace}
    3157\newcommand{\Textbf}[1]{{\color{red}\textbf{#1}}}
    32 
    33 \newcommand{\TODO}[1]{\textbf{TODO}: {\itshape #1}} % TODO included
    34 %\newcommand{\TODO}[1]{} % TODO elided
    35 \newcommand{\eg}{\textit{e}.\textit{g}.,\xspace}
    36 \newcommand{\ie}{\textit{i}.\textit{e}.,\xspace}
    37 \newcommand{\etc}{\textit{etc}.,\xspace}
    3858
    3959% CFA programming language, based on ANSI C (with some gcc additions)
     
    155175(4) Extensions introduced by \CFA must be translated in the most efficient way possible.
    156176These 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.
     177Unfortunately, \CC is actively diverging from C, so incremental additions require significant effort and training, coupled with multiple legacy design-choices that cannot be updated.
    158178
    159179\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.
     
    179199int val = twice( twice( 3.7 ) );
    180200\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.
     201which 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.
    182202The 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.
    183203
     
    187207\begin{lstlisting}
    188208void * 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 * ));
    190210int comp( const void * t1, const void * t2 ) { return *(double *)t1 < *(double *)t2 ? -1 :
    191211                                *(double *)t2 < *(double *)t1 ? 1 : 0; }
     
    205225int posn = bsearch( 5.0, vals, 10 );
    206226\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@ routine in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
     227The nested function @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
     228Providing a hidden @comp@ function in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
    209229As well, an alternate kind of return is made available: position versus pointer to found element.
    210230\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@.
     
    250270Hence, the single name @MAX@ replaces all the C type-specific names: @SHRT_MAX@, @INT_MAX@, @DBL_MAX@.
    251271As 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,
     272In addition, several operations are defined in terms values @0@ and @1@, \eg:
    254273\begin{lstlisting}
    255274int x;
     
    278297\end{lstlisting}
    279298
    280 In fact, the set of operators is incomplete, \eg no assignment, but @otype@ is syntactic sugar for the following implicit trait:
     299In 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:
    281300\begin{lstlisting}
    282301trait otype( dtype T | sized(T) ) {  // sized is a pseudo-trait for types with known size and alignment
     
    308327% \end{lstlisting}
    309328
    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.
     329In 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.
    311330Hence, trait names play no part in type equivalence;
    312331the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
     
    344363\section{Generic Types}
    345364
    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.
     365One 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.
     366A 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.
     367A 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.
    347368
    348369Other 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.
     
    359380pair( const char *, int ) p = { "magic", 42 };
    360381int magic = value( p );
    361 
    362382pair( void *, int * ) q = { 0, &p.second };
    363383magic = value_p( q );
    364 
    365384double d = 1.0;
    366385pair( double *, double * ) r = { &d, &d };
     
    368387\end{lstlisting}
    369388
    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, are 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.
     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.
    371390
    372391\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:
     
    378397\subsection{Concrete Generic-Types}
    379398
    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 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:
     399The \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:
    381400\begin{lstlisting}
    382401struct _pair_conc1 {
     
    386405\end{lstlisting}
    387406
    388 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:
     407A 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:
    389408\begin{lstlisting}
    390409struct _pair_conc0 {
     
    397416\subsection{Dynamic Generic-Types}
    398417
    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@.
     418Though \CFA implements concrete generic-types efficiently, it also has a fully general system for dynamic generic types.
     419As 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.
     420Dynamic generic-types also have an \emph{offset array} containing structure member-offsets.
     421A dynamic generic-union needs no such offset array, as all members are at offset 0 but size and alignment are still necessary.
     422Access 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
     424The offset arrays are statically generated where possible.
     425If 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;
     426if 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.
     427As 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 )@.
     428The offset array @_offsetof_pair@ is generated at the call site as @size_t _offsetof_pair[] = { offsetof(_pair_conc1, first), offsetof(_pair_conc1, second) }@.
     429
     430In 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.
     432The \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.
     433These 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).
     434Results of these layout functions are cached so that they are only computed once per type per function. %, as in the example below for @pair@.
    404435% \begin{lstlisting}
    405436% static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair,
     
    425456% }
    426457% \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.
     458Layout functions also allow generic types to be used in a function definition without reflecting them in the function signature.
     459For 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.
     460This function could acquire the layout for @set(T)@ by calling its layout function with the layout of @T@ implicitly passed into the function.
     461
     462Whether a type is concrete, dtype-static, or dynamic is decided solely on the type parameters and @forall@ clause on a declaration.
     463This 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.
     464If 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.
    430465
    431466
     
    435470The 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@:
    436471\begin{lstlisting}
    437 forall(dtype T) int lexcmp( pair( T *, T *) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {
     472forall(dtype T) int lexcmp( pair( T *, T * ) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {
    438473        int c = cmp( a->first, b->first );
    439474        if ( c == 0 ) c = cmp( a->second, b->second );
     
    441476}
    442477\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:
     478Since @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
     480Another useful pattern enabled by reused dtype-static type instantiations is zero-cost \emph{tag-structures}.
     481Sometimes information is only used for type-checking and can be omitted at runtime, \eg:
    446482\begin{lstlisting}
    447483forall(dtype Unit) struct scalar { unsigned long value; };
    448 
    449484struct metres {};
    450485struct litres {};
     
    453488        return (scalar(U)){ a.value + b.value };
    454489}
    455 
    456490scalar(metres) half_marathon = { 21093 };
    457491scalar(litres) swimming_pool = { 2500000 };
    458 
    459492scalar(metres) marathon = half_marathon + half_marathon;
    460493scalar(litres) two_pools = swimming_pool + swimming_pool;
    461494marathon + swimming_pool;                       $\C{// compilation ERROR}$
    462495\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 @?+?@.
     497These implementations may even be separately compiled, unlike \CC template functions.
     498However, the \CFA type-checker ensures matching types are used by all calls to @?+?@, preventing nonsensical computations like adding a length to a volume.
    464499
    465500\section{Tuples}
     
    468503The @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}.
    469504
    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.
     505In 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.
    471506
    472507C 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:
     
    491526In 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.
    492527
     528
    493529\subsection{Tuple Expressions}
    494530
     
    497533\CFA allows declaration of \emph{tuple variables}, variables of tuple type. For example:
    498534\begin{lstlisting}
    499 [int, char] most_frequent(const char*);
     535[int, char] most_frequent(const char * );
    500536
    501537const char* str = "hello, world!";
     
    741777Unlike 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.
    742778
    743 It is also possible to write a type-safe variadic print routine which can replace @printf@:
     779It is also possible to write a type-safe variadic print function which can replace @printf@:
    744780\begin{lstlisting}
    745781struct S { int x, y; };
     
    756792print("s = ", (S){ 1, 2 }, "\n");
    757793\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.
     794This 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.
    759795
    760796It 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.