Changes in / [da1c772:4f57930]


Ignore:
File:
1 edited

Legend:

Unmodified
Added
Removed
  • doc/generic_types/generic_types.tex

    rda1c772 r4f57930  
    137137                & 2017  & 2012  & 2007  & 2002  & 1997  & 1992  & 1987          \\
    138138\hline
    139 Java    & 1             & 1             & 1             & 1             & 12    & -             & -                     \\
     139Java    & 1             & 1             & 1             & 3             & 13    & -             & -                     \\
    140140\hline
    141 \Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \Textbf{1}& \Textbf{1}    \\
     141\Textbf{C}      & \Textbf{2}& \Textbf{2}& \Textbf{2}& \Textbf{1}& \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.
    182 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.
     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. 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.
    183182
    184183Crucial to the design of a new programming language are the libraries to access thousands of external software features.
     
    205204int posn = bsearch( 5.0, vals, 10 );
    206205\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.
     206The 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.
    209207As well, an alternate kind of return is made available: position versus pointer to found element.
    210208\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@.
     
    277275        return total; }
    278276\end{lstlisting}
     277A trait name plays no part in type equivalence; it is solely a macro for a list of assertions.
     278Traits 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 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 Hence, trait names play no part in type equivalence;
    312 the names are simply macros for a list of polymorphic assertions, which are expanded at usage sites.
    313 Nevertheless, trait names form a logical subtype-hierarchy with @dtype@ at the top, where traits often contain overlapping assertions.
    314 Traits are used like interfaces in Java or abstract base-classes in \CC, but without the nominal inheritance-relationships.
    315 Instead, 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.
    316 Hence, 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 
     310Traits 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
     312Nominal inheritance can be simulated with traits using marker variables or functions:
     313\begin{lstlisting}
     314trait nominal(otype T) {
     315    T is_nominal;
     316};
     317int is_nominal;                                                         $\C{// int now satisfies the nominal trait}$
     318\end{lstlisting}
     319
     320Traits, 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}
     322trait pointer_like(otype Ptr, otype El) {
     323    lvalue El *?(Ptr);                                          $\C{// Ptr can be dereferenced into a modifiable value of type El}$
     324}
     325struct list {
     326    int value;
     327    list *next;                                                         $\C{// may omit "struct" on type names as in \CC}$
     328};
     329typedef list *list_iterator;
     330
     331lvalue int *?( list_iterator it ) { return it->value; }
     332\end{lstlisting}
     333
     334In 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@).
     335While 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.
    343336
    344337\section{Generic Types}
    345338
    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.
    347 
    348 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.
     339One 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
     341Other 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.
    349342
    350343A 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:
    351344\begin{lstlisting}
    352 forall( otype R, otype S ) struct pair {
    353         R first;
    354         S second;
     345forall(otype R, otype S) struct pair {
     346    R first;
     347    S second;
    355348};
    356 forall( otype T ) T value( pair( const char *, T ) p ) { return p.second; }
    357 forall( dtype F, otype T ) T value_p( pair( F *, T * ) p ) { return *p.second; }
    358 
    359 pair( const char *, int ) p = { "magic", 42 };
     349
     350forall(otype T)
     351T value( pair(const char*, T) p ) { return p.second; }
     352
     353forall(dtype F, otype T)
     354T value_p( pair(F*, T*) p ) { return *p.second; }
     355
     356pair(const char*, int) p = { "magic", 42 };
    360357int magic = value( p );
    361358
    362 pair( void *, int * ) q = { 0, &p.second };
     359pair(void*, int*) q = { 0, &p.second };
    363360magic = value_p( q );
    364 
    365361double d = 1.0;
    366 pair( double *, double * ) r = { &d, &d };
     362pair(double*, double*) r = { &d, &d };
    367363d = value_p( r );
    368364\end{lstlisting}
    369365
    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}
    374 forall( otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); } ) struct sorted_set;
    375 \end{lstlisting}
    376 
    377 
    378 \subsection{Concrete Generic-Types}
    379 
    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:
     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}
     370forall(otype Key | { _Bool ?==?(Key, Key); _Bool ?<?(Key, Key); })
     371  struct sorted_set;
     372\end{lstlisting}
     373
     374\subsection{Concrete Generic Types}
     375
     376The \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:
    381377\begin{lstlisting}
    382378struct _pair_conc1 {
    383         const char * first;
     379        const char* first;
    384380        int second;
    385381};
    386382\end{lstlisting}
    387383
    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:
     384A 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:
    389385\begin{lstlisting}
    390386struct _pair_conc0 {
    391         void * first;
    392         void * second;
     387        void* first;
     388        void* second;
    393389};
    394390\end{lstlisting}
    395391
    396392
    397 \subsection{Dynamic Generic-Types}
    398 
    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@.
     393\subsection{Dynamic Generic Types}
     394
     395Though \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
     397These 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
     399In 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@.
    404400% \begin{lstlisting}
    405401% static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair,
     
    407403%     *_szeof_pair = 0; // default values
    408404%     *_alignof_pair = 1;
    409 %
     405
    410406%       // add offset, size, and alignment of first field
    411407%     _offsetof_pair[0] = *_szeof_pair;
    412408%     *_szeof_pair += _szeof_R;
    413409%     if ( *_alignof_pair < _alignof_R ) *_alignof_pair = _alignof_R;
    414 %
     410
    415411%       // padding, offset, size, and alignment of second field
    416412%     if ( *_szeof_pair & (_alignof_S - 1) )
     
    419415%     *_szeof_pair += _szeof_S;
    420416%     if ( *_alignof_pair < _alignof_S ) *_alignof_pair = _alignof_S;
    421 %
     417
    422418%       // pad to struct alignment
    423419%     if ( *_szeof_pair & (*_alignof_pair - 1) )
     
    425421% }
    426422% \end{lstlisting}
     423
    427424Layout 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.
    428425
    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.
    430 
     426Whether 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.
    431427
    432428\subsection{Applications}
    433429\label{sec:generic-apps}
    434430
    435 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 \begin{lstlisting}
    437 forall(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 );
     431The 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}
     433forall(dtype T)
     434int 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);
    440437        return c;
    441438}
    442439\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:
     440Since @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
     442Another 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:
    446443\begin{lstlisting}
    447444forall(dtype Unit) struct scalar { unsigned long value; };
     
    450447struct litres {};
    451448
    452 forall(dtype U) scalar(U) ?+?( scalar(U) a, scalar(U) b ) {
     449forall(dtype U)
     450scalar(U) ?+?(scalar(U) a, scalar(U) b) {
    453451        return (scalar(U)){ a.value + b.value };
    454452}
     
    459457scalar(metres) marathon = half_marathon + half_marathon;
    460458scalar(litres) two_pools = swimming_pool + swimming_pool;
    461 marathon + 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.
     459marathon + 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.
    464462
    465463\section{Tuples}
     
    477475  int ret = 0;
    478476  while(N) {
    479         ret += va_arg(args, int);  // must specify type
    480         N--;
     477    ret += va_arg(args, int);  // must specify type
     478    N--;
    481479  }
    482480  va_end(args);
     
    795793  forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2))
    796794  struct _tuple3 {  // generated before the first 3-tuple
    797         T0 field_0;
    798         T1 field_1;
    799         T2 field_2;
     795    T0 field_0;
     796    T1 field_1;
     797    T2 field_2;
    800798  };
    801799  _tuple3_(int, double, int) y;
Note: See TracChangeset for help on using the changeset viewer.