Changes in / [4f57930:da1c772]


Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/generic_types/generic_types.tex

    r4f57930 rda1c772  
    137137                & 2017  & 2012  & 2007  & 2002  & 1997  & 1992  & 1987          \\
    138138\hline
    139 Java    & 1             & 1             & 1             & 3             & 13    & -             & -                     \\
     139Java    & 1             & 1             & 1             & 1             & 12    & -             & -                     \\
    140140\hline
    141 \Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \Textbf{1}& \Textbf{1}& \Textbf{1}    \\
     141\Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \Textbf{1}& \Textbf{1}    \\
    142142\hline
    143143\CC             & 3             & 3             & 3             & 3             & 2             & 2             & 4                     \\
     
    179179int val = twice( twice( 3.7 ) );
    180180\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. The first approach has a late conversion from @int@ to @double@ 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.
     181which 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.
     182The 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.
    182183
    183184Crucial to the design of a new programming language are the libraries to access thousands of external software features.
     
    204205int posn = bsearch( 5.0, vals, 10 );
    205206\end{lstlisting}
    206 The nested routine @comp@ (impossible in \CC as lambdas do not use C calling conventions) provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
     207The nested routine @comp@ provides the hidden interface from typed \CFA to untyped (@void *@) C, plus the cast of the result.
     208Providing a hidden @comp@ routine in \CC is awkward as lambdas do not use C calling-conventions and template declarations cannot appear at block scope.
    207209As well, an alternate kind of return is made available: position versus pointer to found element.
    208210\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@.
     
    275277        return total; }
    276278\end{lstlisting}
    277 A trait name plays no part in type equivalence; it is solely a macro for a list of assertions.
    278 Traits may overlap assertions without conflict, and therefore, do not form a hierarchy.
    279279
    280280In fact, the set of operators is incomplete, \eg no assignment, but @otype@ is syntactic sugar for the following implicit trait:
     
    308308% \end{lstlisting}
    309309
    310 Traits may be used for many of the same purposes as interfaces in Java or abstract base classes in \CC. Unlike Java interfaces or \CC base classes, \CFA types do not explicitly state any inheritance relationship to traits they satisfy, which is a form of structural inheritance, similar to the implementation of an interface in Go~\citep{Go}, as opposed to the nominal inheritance model of Java and \CC.
    311 
    312 Nominal inheritance can be simulated with traits using marker variables or functions:
    313 \begin{lstlisting}
    314 trait nominal(otype T) {
    315     T is_nominal;
     310The \CFA type-system uses \emph{nominal typing} for concrete types, matching with the C type-system. and \emph{structural typing} for polymorphic types.
     311Hence, trait names play no part in type equivalence;
     312the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
     313Nevertheless, trait names form a logical subtype-hierarchy with @dtype@ at the top, where traits often contain overlapping assertions.
     314Traits are used like interfaces in Java or abstract base-classes in \CC, but without the nominal inheritance-relationships.
     315Instead, each polymorphic function (or generic type) defines the structural type needed for its execution (polymorphic type-key), and this key is fulfilled at each call site from the lexical environment, which is similar to Go~\citep{Go} interfaces.
     316Hence, new lexical scopes and nested functions are used extensively to create local subtypes, as in the @qsort@ example, without having to manage a nominal-inheritance hierarchy.
     317(Nominal inheritance can be approximated with traits using marker variables or functions, as is done in Go.)
     318
     319% Nominal inheritance can be simulated with traits using marker variables or functions:
     320% \begin{lstlisting}
     321% trait nominal(otype T) {
     322%     T is_nominal;
     323% };
     324% int is_nominal;                                                               $\C{// int now satisfies the nominal trait}$
     325% \end{lstlisting}
     326%
     327% Traits, however, are significantly more powerful than nominal-inheritance interfaces; most notably, traits may be used to declare a relationship \emph{among} multiple types, a property that may be difficult or impossible to represent in nominal-inheritance type systems:
     328% \begin{lstlisting}
     329% trait pointer_like(otype Ptr, otype El) {
     330%     lvalue El *?(Ptr);                                                $\C{// Ptr can be dereferenced into a modifiable value of type El}$
     331% }
     332% struct list {
     333%     int value;
     334%     list *next;                                                               $\C{// may omit "struct" on type names as in \CC}$
     335% };
     336% typedef list *list_iterator;
     337%
     338% lvalue int *?( list_iterator it ) { return it->value; }
     339% \end{lstlisting}
     340% In the example above, @(list_iterator, int)@ satisfies @pointer_like@ by the user-defined dereference function, and @(list_iterator, list)@ also satisfies @pointer_like@ by the built-in dereference operator for pointers. Given a declaration @list_iterator it@, @*it@ can be either an @int@ or a @list@, with the meaning disambiguated by context (\eg @int x = *it;@ interprets @*it@ as an @int@, while @(*it).value = 42;@ interprets @*it@ as a @list@).
     341% While a nominal-inheritance system with associated types could model one of those two relationships by making @El@ an associated type of @Ptr@ in the @pointer_like@ implementation, few such systems could model both relationships simultaneously.
     342
     343
     344\section{Generic Types}
     345
     346One 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.
     347
     348Other 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.
     349
     350A generic type can be declared by placing a @forall@ specifier on a @struct@ or @union@ declaration, and instantiated using a parenthesized list of types after the type name:
     351\begin{lstlisting}
     352forall( otype R, otype S ) struct pair {
     353        R first;
     354        S second;
    316355};
    317 int is_nominal;                                                         $\C{// int now satisfies the nominal trait}$
    318 \end{lstlisting}
    319 
    320 Traits, however, are significantly more powerful than nominal-inheritance interfaces; most notably, traits may be used to declare a relationship \emph{among} multiple types, a property that may be difficult or impossible to represent in nominal-inheritance type systems:
    321 \begin{lstlisting}
    322 trait pointer_like(otype Ptr, otype El) {
    323     lvalue El *?(Ptr);                                          $\C{// Ptr can be dereferenced into a modifiable value of type El}$
    324 }
    325 struct list {
    326     int value;
    327     list *next;                                                         $\C{// may omit "struct" on type names as in \CC}$
    328 };
    329 typedef list *list_iterator;
    330 
    331 lvalue int *?( list_iterator it ) { return it->value; }
    332 \end{lstlisting}
    333 
    334 In the example above, @(list_iterator, int)@ satisfies @pointer_like@ by the user-defined dereference function, and @(list_iterator, list)@ also satisfies @pointer_like@ by the built-in dereference operator for pointers. Given a declaration @list_iterator it@, @*it@ can be either an @int@ or a @list@, with the meaning disambiguated by context (\eg @int x = *it;@ interprets @*it@ as an @int@, while @(*it).value = 42;@ interprets @*it@ as a @list@).
    335 While a nominal-inheritance system with associated types could model one of those two relationships by making @El@ an associated type of @Ptr@ in the @pointer_like@ implementation, few such systems could model both relationships simultaneously.
    336 
    337 \section{Generic Types}
    338 
    339 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 @qsort@ and @bsearch@, 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 requires a number of extra function parameters, and also adds pointer indirection and dynamic allocation to algorithms and data structures that would not otherwise require them. A third approach to generic code is to use pre-processor macros to generate it -- this approach does allow the generated code to be both generic and type-checked, though any errors produced may be difficult to interpret. Furthermore, writing and invoking C code as preprocessor macros is unnatural and somewhat inflexible.
    340 
    341 Other C-like languages such as \CC and Java use \emph{generic types} to produce type-safe abstract data types. \CFA implements generic types with some care taken that the generic types design for \CFA integrates efficiently and naturally with the existing polymorphic functions in \CFA while retaining backwards compatibility with C; maintaining separate compilation is a particularly important constraint on the design. However, where the concrete parameters of the generic type are known, there is no extra overhead for the use of a generic type, as for \CC templates.
    342 
    343 A generic type can be declared by placing a @forall@ specifier on a @struct@ or @union@ declaration, and instantiated using a parenthesized list of types after the type name:
    344 \begin{lstlisting}
    345 forall(otype R, otype S) struct pair {
    346     R first;
    347     S second;
    348 };
    349 
    350 forall(otype T)
    351 T value( pair(const char*, T) p ) { return p.second; }
    352 
    353 forall(dtype F, otype T)
    354 T value_p( pair(F*, T*) p ) { return *p.second; }
    355 
    356 pair(const char*, int) p = { "magic", 42 };
     356forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; }
     357forall( dtype F, otype T ) T value_p( pair( F *, T * ) p ) { return *p.second; }
     358
     359pair( const char *, int ) p = { "magic", 42 };
    357360int magic = value( p );
    358361
    359 pair(void*, int*) q = { 0, &p.second };
     362pair( void *, int * ) q = { 0, &p.second };
    360363magic = value_p( q );
     364
    361365double d = 1.0;
    362 pair(double*, double*) r = { &d, &d };
     366pair( double *, double * ) r = { &d, &d };
    363367d = value_p( r );
    364368\end{lstlisting}
    365369
    366 \CFA classifies generic types as either \emph{concrete} or \emph{dynamic}. Concrete generic types have a fixed memory layout regardless of type parameters, while dynamic generic types vary in their in-memory layout depending on their type parameters. A type may have polymorphic parameters but still be concrete; in \CFA such types are called \emph{dtype-static}. Polymorphic pointers are an example of dtype-static types -- @forall(dtype T) T*@ is a polymorphic type, but for any @T@ chosen, @T*@ has exactly the same in-memory representation as a @void*@, and can therefore be represented by a @void*@ in code generation.
    367 
    368 \CFA generic types may also specify constraints on their argument type to be checked by the compiler. For example, consider the following declaration of a sorted set-type, which ensures that the set key supports equality and relational comparison:
    369 \begin{lstlisting}
    370 forall(otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); })
    371   struct sorted_set;
    372 \end{lstlisting}
    373 
    374 \subsection{Concrete Generic Types}
    375 
    376 The \CFA translator instantiates concrete generic types by template-expanding them to fresh struct types; concrete generic types can therefore be used with zero runtime overhead. 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 struct 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 that can see that declaration may reuse. As an example of the expansion, the concrete instantiation for @pair(const char*, int)@ looks like this:
     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.
     371
     372\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:
     373\begin{lstlisting}
     374forall( otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); } ) struct sorted_set;
     375\end{lstlisting}
     376
     377
     378\subsection{Concrete Generic-Types}
     379
     380The \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:
    377381\begin{lstlisting}
    378382struct _pair_conc1 {
    379         const char* first;
     383        const char * first;
    380384        int second;
    381385};
    382386\end{lstlisting}
    383387
    384 A concrete generic type with dtype-static parameters is also expanded to a struct type, but this struct type is used for all matching instantiations. In the example above, the @pair(F*, T*)@ parameter to @value_p@ is such a type; its expansion looks something like this, and is used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate:
     388A 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:
    385389\begin{lstlisting}
    386390struct _pair_conc0 {
    387         void* first;
    388         void* second;
     391        void * first;
     392        void * second;
    389393};
    390394\end{lstlisting}
    391395
    392396
    393 \subsection{Dynamic Generic Types}
    394 
    395 Though \CFA implements concrete generic types efficiently, it also has a fully general system for computing with 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 structs also have implicit size and alignment parameters, and also an \emph{offset array} which contains the offsets of each member of the struct\footnote{Dynamic generic unions need no such offset array, as all members are at offset 0; the size and alignment parameters are still provided for dynamic unions, however.}. Access to members\footnote{The \lstinline@offsetof@ macro is implemented similarly.} of a dynamic generic struct is provided by adding the corresponding member of the offset array to the struct pointer at runtime, essentially moving a compile-time offset calculation to runtime where necessary.
    396 
    397 These 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 that the generic type is complete (that is, 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 in to @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) };@.
    398 
    399 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 \texttt{.c} file. \CFA supports this pattern for generic types, and in this instance the caller does not know the actual layout or size of the dynamic generic type, and only holds it by 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 in to 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 struct (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@.
     397\subsection{Dynamic Generic-Types}
     398
     399Though \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
     401The 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
     403In 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@.
    400404% \begin{lstlisting}
    401405% static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair,
     
    403407%     *_szeof_pair = 0; // default values
    404408%     *_alignof_pair = 1;
    405 
     409%
    406410%       // add offset, size, and alignment of first field
    407411%     _offsetof_pair[0] = *_szeof_pair;
    408412%     *_szeof_pair += _szeof_R;
    409413%     if ( *_alignof_pair < _alignof_R ) *_alignof_pair = _alignof_R;
    410 
     414%
    411415%       // padding, offset, size, and alignment of second field
    412416%     if ( *_szeof_pair & (_alignof_S - 1) )
     
    415419%     *_szeof_pair += _szeof_S;
    416420%     if ( *_alignof_pair < _alignof_S ) *_alignof_pair = _alignof_S;
    417 
     421%
    418422%       // pad to struct alignment
    419423%     if ( *_szeof_pair & (*_alignof_pair - 1) )
     
    421425% }
    422426% \end{lstlisting}
    423 
    424427Layout 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.
    425428
    426 Whether a type is concrete, dtype-static, or dynamic is decided based solely on the type parameters and @forall@ clause on the struct declaration. This design allows opaque forward declarations of generic types like @forall(otype T) struct Box;@ -- like in C, all uses of @Box(T)@ can be in a separately compiled translation unit, and callers from other translation units know the proper calling conventions to use. If the definition of a struct type was included in the decision of 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.
     429Whether 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.
     430
    427431
    428432\subsection{Applications}
    429433\label{sec:generic-apps}
    430434
    431 The reuse of dtype-static struct instantiations enables some 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*@, as in this example, which takes a @qsort@ or @bsearch@-compatible comparison routine and creates a similar lexicographic comparison for pairs of pointers:
    432 \begin{lstlisting}
    433 forall(dtype T)
    434 int lexcmp( pair(T*, T*)* a, pair(T*, T*)* b, int (*cmp)(T*, T*) ) {
    435         int c = cmp(a->first, b->first);
    436         if ( c == 0 ) c = cmp(a->second, b->second);
     435The 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\begin{lstlisting}
     437forall(dtype T) int lexcmp( pair( T *, T *) * a, pair( T *, T * ) * b, int (* cmp)( T *, T * ) ) {
     438        int c = cmp( a->first, b->first );
     439        if ( c == 0 ) c = cmp( a->second, b->second );
    437440        return c;
    438441}
    439442\end{lstlisting}
    440 Since @pair(T*, T*)@ is a concrete type, there are no added implicit parameters to @lexcmp@, so the code generated by \CFA is effectively identical to a version of this function written in standard C using @void*@, yet the \CFA version is type-checked to ensure that the fields of both pairs and the arguments to the comparison function match in type.
    441 
    442 Another useful pattern enabled by reused dtype-static type instantiations is zero-cost ``tag'' structs. 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:
     443Since @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
     445Another 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:
    443446\begin{lstlisting}
    444447forall(dtype Unit) struct scalar { unsigned long value; };
     
    447450struct litres {};
    448451
    449 forall(dtype U)
    450 scalar(U) ?+?(scalar(U) a, scalar(U) b) {
     452forall(dtype U) scalar(U) ?+?( scalar(U) a, scalar(U) b ) {
    451453        return (scalar(U)){ a.value + b.value };
    452454}
     
    457459scalar(metres) marathon = half_marathon + half_marathon;
    458460scalar(litres) two_pools = swimming_pool + swimming_pool;
    459 marathon + swimming_pool; // ERROR -- caught by compiler
    460 \end{lstlisting}
    461 @scalar@ is a dtype-static type, so all uses of it use a single struct definition, containing only 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 that matching types are used by all calls to @?+?@, preventing nonsensical computations like adding the length of a marathon to the volume of an olympic pool.
     461marathon + swimming_pool;                       $\C{// compilation ERROR}$
     462\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.
    462464
    463465\section{Tuples}
     
    475477  int ret = 0;
    476478  while(N) {
    477     ret += va_arg(args, int);  // must specify type
    478     N--;
     479        ret += va_arg(args, int);  // must specify type
     480        N--;
    479481  }
    480482  va_end(args);
     
    793795  forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2))
    794796  struct _tuple3 {  // generated before the first 3-tuple
    795     T0 field_0;
    796     T1 field_1;
    797     T2 field_2;
     797        T0 field_0;
     798        T1 field_1;
     799        T2 field_2;
    798800  };
    799801  _tuple3_(int, double, int) y;
Note: See TracChangeset for help on using the changeset viewer.