Changes in / [da1c772:4f57930]
- File:
-
- 1 edited
-
doc/generic_types/generic_types.tex (modified) (12 diffs)
Legend:
- Unmodified
- Added
- Removed
-
doc/generic_types/generic_types.tex
rda1c772 r4f57930 137 137 & 2017 & 2012 & 2007 & 2002 & 1997 & 1992 & 1987 \\ 138 138 \hline 139 Java & 1 & 1 & 1 & 1 & 12& - & - \\139 Java & 1 & 1 & 1 & 3 & 13 & - & - \\ 140 140 \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} \\ 142 142 \hline 143 143 \CC & 3 & 3 & 3 & 3 & 2 & 2 & 4 \\ … … 179 179 int val = twice( twice( 3.7 ) ); 180 180 \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. 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. 183 182 184 183 Crucial to the design of a new programming language are the libraries to access thousands of external software features. … … 205 204 int posn = bsearch( 5.0, vals, 10 ); 206 205 \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. 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. 209 207 As well, an alternate kind of return is made available: position versus pointer to found element. 210 208 \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@. … … 277 275 return total; } 278 276 \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. 279 279 280 280 In fact, the set of operators is incomplete, \eg no assignment, but @otype@ is syntactic sugar for the following implicit trait: … … 308 308 % \end{lstlisting} 309 309 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 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; 316 }; 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. 343 336 344 337 \section{Generic Types} 345 338 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 andinflexible.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.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. 349 342 350 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: 351 344 \begin{lstlisting} 352 forall( otype R, otype S) struct pair {353 R first;354 S second;345 forall(otype R, otype S) struct pair { 346 R first; 347 S second; 355 348 }; 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 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 }; 360 357 int magic = value( p ); 361 358 362 pair( void *, int *) q = { 0, &p.second };359 pair(void*, int*) q = { 0, &p.second }; 363 360 magic = value_p( q ); 364 365 361 double d = 1.0; 366 pair( double *, double *) r = { &d, &d };362 pair(double*, double*) r = { &d, &d }; 367 363 d = value_p( r ); 368 364 \end{lstlisting} 369 365 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 ensuresthe 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} 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: 381 377 \begin{lstlisting} 382 378 struct _pair_conc1 { 383 const char * first;379 const char* first; 384 380 int second; 385 381 }; 386 382 \end{lstlisting} 387 383 388 A concrete generic type with dtype-static parameters is also expanded to a struct ure 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 itis used as the type of the variables @q@ and @r@ as well, with casts for member access where appropriate: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: 389 385 \begin{lstlisting} 390 386 struct _pair_conc0 { 391 void * first;392 void * second;387 void* first; 388 void* second; 393 389 }; 394 390 \end{lstlisting} 395 391 396 392 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 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@. 404 400 % \begin{lstlisting} 405 401 % static inline void _layoutof_pair(size_t* _szeof_pair, size_t* _alignof_pair, size_t* _offsetof_pair, … … 407 403 % *_szeof_pair = 0; // default values 408 404 % *_alignof_pair = 1; 409 % 405 410 406 % // add offset, size, and alignment of first field 411 407 % _offsetof_pair[0] = *_szeof_pair; 412 408 % *_szeof_pair += _szeof_R; 413 409 % if ( *_alignof_pair < _alignof_R ) *_alignof_pair = _alignof_R; 414 % 410 415 411 % // padding, offset, size, and alignment of second field 416 412 % if ( *_szeof_pair & (_alignof_S - 1) ) … … 419 415 % *_szeof_pair += _szeof_S; 420 416 % if ( *_alignof_pair < _alignof_S ) *_alignof_pair = _alignof_S; 421 % 417 422 418 % // pad to struct alignment 423 419 % if ( *_szeof_pair & (*_alignof_pair - 1) ) … … 425 421 % } 426 422 % \end{lstlisting} 423 427 424 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 425 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 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. 431 427 432 428 \subsection{Applications} 433 429 \label{sec:generic-apps} 434 430 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 ); 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); 440 437 return c; 441 438 } 442 439 \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 ensurethe 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'' struct ures. 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: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: 446 443 \begin{lstlisting} 447 444 forall(dtype Unit) struct scalar { unsigned long value; }; … … 450 447 struct litres {}; 451 448 452 forall(dtype U) scalar(U) ?+?( scalar(U) a, scalar(U) b ) { 449 forall(dtype U) 450 scalar(U) ?+?(scalar(U) a, scalar(U) b) { 453 451 return (scalar(U)){ a.value + b.value }; 454 452 } … … 459 457 scalar(metres) marathon = half_marathon + half_marathon; 460 458 scalar(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.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. 464 462 465 463 \section{Tuples} … … 477 475 int ret = 0; 478 476 while(N) { 479 ret += va_arg(args, int); // must specify type480 N--;477 ret += va_arg(args, int); // must specify type 478 N--; 481 479 } 482 480 va_end(args); … … 795 793 forall(dtype T0, dtype T1, dtype T2 | sized(T0) | sized(T1) | sized(T2)) 796 794 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; 800 798 }; 801 799 _tuple3_(int, double, int) y;
Note:
See TracChangeset
for help on using the changeset viewer.