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