1 | \chapter{Array} |
---|
2 | \label{c:Array} |
---|
3 | |
---|
4 | |
---|
5 | \section{Introduction} |
---|
6 | |
---|
7 | Arrays in C are possible the single most misunderstood and incorrectly used features in the language, resulting in the largest proportion of runtime errors and security violations. |
---|
8 | This chapter describes the new \CFA language and library features that introduce a length-checked array-type to the \CFA standard library~\cite{Cforall}. |
---|
9 | |
---|
10 | Specifically, a new \CFA array is declared: |
---|
11 | \begin{cfa} |
---|
12 | @array( float, 99 )@ x; $\C[2.75in]{// x contains 99 floats}$ |
---|
13 | \end{cfa} |
---|
14 | using generic type @array@ with arguments @float@ and @99@. |
---|
15 | A function @f@ is declared with an @array@ parameter of length @42@. |
---|
16 | \begin{cfa} |
---|
17 | void f( @array( float, 42 )@ & p ) {} $\C{// p accepts 42 floats}$ |
---|
18 | f( x ); $\C{// statically rejected: types are different, 99 != 42}$ |
---|
19 | |
---|
20 | test2.cfa:3:1 error: Invalid application of existing declaration(s) in expression. |
---|
21 | Applying untyped: Name: f ... to: Name: x |
---|
22 | \end{cfa} |
---|
23 | The call @f( x )@ is invalid because the @array@ lengths @99@ and @42@ do not match. |
---|
24 | |
---|
25 | Next, function @g@ introduces a @forall@ prefix on type parameter @T@ and arbitrary \emph{dimension parameter} @N@, the new feature that represents a count of elements managed by the type system. |
---|
26 | \begin{cfa} |
---|
27 | forall( T, @[N]@ ) |
---|
28 | void g( array( T, @N@ ) & p, int i ) { |
---|
29 | T elem = p[i]; $\C{// dynamically checked: requires 0 <= i < N}$ |
---|
30 | } |
---|
31 | g( x, 0 ); $\C{// T is float, N is 99, dynamic subscript check succeeds}$ |
---|
32 | g( x, 1000 ); $\C{// T is float, N is 99, dynamic subscript check fails}\CRT$ |
---|
33 | |
---|
34 | Cforall Runtime error: subscript 1000 exceeds dimension range [0,99) $for$ array 0x555555558020. |
---|
35 | \end{cfa} |
---|
36 | The call @g( x, 0 )@ is valid because @g@ accepts any length of array, where the type system infers @float@ for @T@ and length @99@ for @N@. |
---|
37 | Inferring values for @T@ and @N@ is implicit without programmer involvement. |
---|
38 | Furthermore, the runtime subscript @x[0]@ (parameter @i@ is @0@) in @g@ is valid because @0@ is in the dimension range $[0,99)$ of argument @x@. |
---|
39 | The call @g( x, 1000 )@ is also valid; |
---|
40 | however, the runtime subscript @x[1000]@ is invalid (generates a subscript error) because @1000@ is outside the dimension range $[0,99)$ of argument @x@. |
---|
41 | |
---|
42 | The generic @array@ type is similar to the C array type, which \CFA inherits from C. |
---|
43 | Its runtime characteristics are often identical, and some features are available in both. |
---|
44 | For example, assume a caller can instantiates @N@ with 42 in the following (details to follow). |
---|
45 | \begin{cfa} |
---|
46 | forall( [N] ) |
---|
47 | void declDemo() { |
---|
48 | float x1[N]; $\C{// built-in type ("C array")}$ |
---|
49 | array(float, N) x2; $\C{// type from library}$ |
---|
50 | } |
---|
51 | \end{cfa} |
---|
52 | Both of the locally-declared array variables, @x1@ and @x2@, have 42 elements, each element being a @float@. |
---|
53 | The two variables have identical size and layout; they both encapsulate 42-float, stack \vs heap allocations with no additional ``bookkeeping'' allocations or headers. |
---|
54 | Providing this explicit generic approach requires a significant extension to the \CFA type system to support a full-feature, safe, efficient (space and time) array-type, which forms the foundation for more complex array forms in \CFA. |
---|
55 | |
---|
56 | Admittedly, the @array@ library type (type for @x2@) is syntactically different from its C counterpart. |
---|
57 | A future goal (TODO xref) is to provide a built-in array type with syntax approaching C's (type for @x1@); |
---|
58 | then, the library @array@ type can be removed giving \CFA a largely uniform array type. |
---|
59 | At present, the C syntax @array@ is only partially supported, so the generic @array@ is used exclusively in the discussion; |
---|
60 | feature support and C compatibility are revisited in Section ? TODO. |
---|
61 | |
---|
62 | Offering the @array@ type, as a distinct alternative to the C array, is consistent with \CFA's goal of backwards compatibility, \ie virtually all existing C (@gcc@) programs can be compiled by \CFA with only a small number of changes, similar to \CC (@g++@). |
---|
63 | However, a few compatibility-breaking changes to the behaviour of the C array are necessary, both as an implementation convenience and to fix C's lax treatment of arrays. |
---|
64 | Hence, the @array@ type is an opportunity to start from a clean slate and show a cohesive selection of features, making it unnecessary to deal with every inherited complexity introduced by the C array TODO xref. |
---|
65 | |
---|
66 | My contributions in this chapter are: |
---|
67 | \begin{enumerate} |
---|
68 | \item A type system enhancement that lets polymorphic functions and generic types be parameterized by a numeric value: @forall( [N] )@. |
---|
69 | \item Provide a length-checked array-type in the \CFA standard library, where the array's length is statically managed and dynamically valued. |
---|
70 | \item Provide argument/parameter passing safety for arrays and subscript safety. |
---|
71 | \item TODO: general parking... |
---|
72 | \item Identify the interesting specific abilities available by the new @array@ type. |
---|
73 | \item Where there is a gap concerning this feature's readiness for prime-time, identification of specific workable improvements that are likely to close the gap. |
---|
74 | \end{enumerate} |
---|
75 | |
---|
76 | |
---|
77 | \section{Definitions and design considerations} |
---|
78 | |
---|
79 | |
---|
80 | \subsection{Dependent typing} |
---|
81 | |
---|
82 | |
---|
83 | \section{Features added} |
---|
84 | |
---|
85 | This section presents motivating examples for the new array type, demonstrating the syntax and semantics of the generic @array@. |
---|
86 | As stated, the core capability of the new array is tracking all dimensions in the type system, where dynamic dimensions are represented using type variables. |
---|
87 | |
---|
88 | The definition of type variables preceding object declarations makes the array dimension lexically referenceable where it is needed. |
---|
89 | For example, a declaration can share one length, @N@, among a pair of parameters and the return. |
---|
90 | \lstinput{10-17}{hello-array.cfa} |
---|
91 | Here, the function @f@ does a pointwise comparison, checking if each pair of numbers is within half a percent of each other, returning the answers in a newly allocated @bool@ array. |
---|
92 | The dynamic allocation of the @ret@ array by @alloc@ uses the parameterized dimension information in its implicit @_Alignof@ and @sizeof@ determinations, and casting the return type. |
---|
93 | \begin{cfa} |
---|
94 | static inline forall( T & | sized(T) ) |
---|
95 | T * alloc( size_t dim ) { |
---|
96 | if ( _Alignof(T) <= libAlign() ) return (T *)aalloc( dim, sizeof(T) ); // calloc without zero fill |
---|
97 | else return (T *)amemalign( _Alignof(T), dim, sizeof(T) ); // array memalign |
---|
98 | } |
---|
99 | \end{cfa} |
---|
100 | Here, the type system deduces from the left-hand side of the assignment the type @array(bool, N)@, and forwards it as the type variable @T@ for the generic @alloc@ function, making it available in its body. |
---|
101 | Hence, preexisting \CFA behaviour is leveraged here, both in the return-type polymorphism, and the @sized(T)@-aware standard-library @alloc@ routine. |
---|
102 | This example illustrates how the new @array@ type plugs into existing \CFA behaviour by implementing necessary @sized@ assertions needed by other types. |
---|
103 | (@sized@ implies a concrete \vs abstract type with a compile-time size.) |
---|
104 | As a result, there is significant programming safety by making the size accessible and implicit, compared with C's @calloc@ and non-array supporting @memalign@, which take an explicit length parameter not managed by the type system. |
---|
105 | |
---|
106 | \begin{figure} |
---|
107 | \lstinput{30-43}{hello-array.cfa} |
---|
108 | \lstinput{45-48}{hello-array.cfa} |
---|
109 | \caption{\lstinline{f} Harness} |
---|
110 | \label{f:fHarness} |
---|
111 | \end{figure} |
---|
112 | |
---|
113 | \VRef[Figure]{f:fHarness} shows a harness that uses function @f@ to illustrate how dynamic values are fed into the @array@ type. |
---|
114 | Here, the dimension of arrays @x@, @y@, and @result@ is specified from a command-line value, @dim@, and these arrays are allocated on the stack. |
---|
115 | Then the @x@ array is initialized with decreasing values, and the @y@ array with amounts offset by constant @0.005@, giving relative differences within tolerance initially and diverging for later values. |
---|
116 | The program main is run (see figure bottom) with inputs @5@ and @7@ for sequence lengths. |
---|
117 | The loops follow the familiar pattern of using the variable @dim@ to iterate through the arrays. |
---|
118 | Most importantly, the type system implicitly captures @dim@ at the call of @f@ and makes it available throughout @f@ as @N@. |
---|
119 | The example shows @dim@ adapting into a type-system managed length at the declarations of @x@, @y@, and @result@, @N@ adapting in the same way at @f@'s loop bound, and a pass-thru use of @dim@ at @f@'s declaration of @ret@. |
---|
120 | Except for the lifetime-management issue of @result@, \ie explicit @free@, this program has eliminated both the syntactic and semantic problems associated with C arrays and their usage. |
---|
121 | These benefits cannot be underestimated. |
---|
122 | |
---|
123 | In general, the @forall( ..., [N] )@ participates in the user-relevant declaration of the name @N@, which becomes usable in parameter/return declarations and within a function. |
---|
124 | The syntactic form is chosen to parallel other @forall@ forms: |
---|
125 | \begin{cfa} |
---|
126 | forall( @[N]@ ) ... $\C[1.5in]{// array kind}$ |
---|
127 | forall( T & ) ... $\C{// reference kind (dtype)}$ |
---|
128 | forall( T ) ... $\C{// value kind (otype)}\CRT$ |
---|
129 | \end{cfa} |
---|
130 | % The notation @array(thing, N)@ is a single-dimensional case, giving a generic type instance. |
---|
131 | In summary: |
---|
132 | \begin{itemize} |
---|
133 | \item |
---|
134 | @[N]@ within a forall declares the type variable @N@ to be a managed length. |
---|
135 | \item |
---|
136 | The type of @N@ within code is @size_t@. |
---|
137 | \item |
---|
138 | The value of @N@ within code is the acquired length derived from the usage site, \ie generic declaration or function call. |
---|
139 | \item |
---|
140 | @array( thing, N0, N1, ... )@ is a multi-dimensional type wrapping $\prod_i N_i$ adjacent occurrences of @thing@ objects. |
---|
141 | \end{itemize} |
---|
142 | |
---|
143 | \VRef[Figure]{f:TemplateVsGenericType} shows @N@ is not the same as a @size_t@ declaration in a \CC \lstinline[language=C++]{template}. |
---|
144 | \begin{enumerate}[leftmargin=*] |
---|
145 | \item |
---|
146 | The \CC template @N@ is a compile-time value, while the \CFA @N@ is a runtime value. |
---|
147 | \item |
---|
148 | The \CC template @N@ must be passed explicitly at the call, unless @N@ has a default value, even when \CC can deduct the type of @T@. |
---|
149 | The \CFA @N@ is part of the array type and passed implicitly at the call. |
---|
150 | \item |
---|
151 | \CC cannot have an array of references, but can have an array of pointers. |
---|
152 | \CC has a (mistaken) belief that references are not objects, but pointers are objects. |
---|
153 | In the \CC example, the arrays fall back on C arrays, which have a duality with references with respect to automatic dereferencing. |
---|
154 | The \CFA array is a contiguous object with an address, which can be stored as a reference or pointer. |
---|
155 | \item |
---|
156 | C/\CC arrays cannot be copied, while \CFA arrays can be copied, making them a first-class object (although array copy is often avoided for efficiency). |
---|
157 | \end{enumerate} |
---|
158 | |
---|
159 | \begin{figure} |
---|
160 | \begin{tabular}{@{}l@{\hspace{20pt}}l@{}} |
---|
161 | \begin{c++} |
---|
162 | |
---|
163 | @template< typename T, size_t N >@ |
---|
164 | void copy( T ret[@N@], T x[@N@] ) { |
---|
165 | for ( int i = 0; i < N; i += 1 ) ret[i] = x[i]; |
---|
166 | } |
---|
167 | int main() { |
---|
168 | int ret[10], x[10]; |
---|
169 | for ( int i = 0; i < 10; i += 1 ) x[i] = i; |
---|
170 | @copy<int, 10 >( ret, x );@ |
---|
171 | for ( int i = 0; i < 10; i += 1 ) |
---|
172 | cout << ret[i] << ' '; |
---|
173 | cout << endl; |
---|
174 | } |
---|
175 | \end{c++} |
---|
176 | & |
---|
177 | \begin{cfa} |
---|
178 | int main() { |
---|
179 | @forall( T, [N] )@ // nested function |
---|
180 | void copy( array( T, @N@ ) & ret, array( T, @N@ ) & x ) { |
---|
181 | for ( i; 10 ) ret[i] = x[i]; |
---|
182 | } |
---|
183 | |
---|
184 | array( int, 10 ) ret, x; |
---|
185 | for ( i; 10 ) x[i] = i; |
---|
186 | @copy( ret, x );@ |
---|
187 | for ( i; 10 ) |
---|
188 | sout | ret[i] | nonl; |
---|
189 | sout | nl; |
---|
190 | } |
---|
191 | \end{cfa} |
---|
192 | \end{tabular} |
---|
193 | \caption{\CC \lstinline[language=C++]{template} \vs \CFA generic type } |
---|
194 | \label{f:TemplateVsGenericType} |
---|
195 | \end{figure} |
---|
196 | |
---|
197 | Continuing the discussion of \VRef[Figure]{f:fHarness}, the example has @f@ expecting two arrays of the same length. |
---|
198 | As stated previous, a compile-time error occurs when attempting to call @f@ with arrays of differing lengths. |
---|
199 | % removing leading whitespace |
---|
200 | \lstinput[tabsize=1]{52-53}{hello-array.cfa} |
---|
201 | \lstinput[tabsize=1,aboveskip=0pt]{62-64}{hello-array.cfa} |
---|
202 | C allows casting to assert knowledge not shared with the type system. |
---|
203 | \lstinput{70-74}{hello-array.cfa} |
---|
204 | |
---|
205 | Orthogonally, the new @array@ type works with \CFA's generic types, providing argument safety and the associated implicit communication of array length. |
---|
206 | Specifically, \CFA allows aggregate types to be generalized with multiple type parameters, including parameterized element types and lengths. |
---|
207 | Doing so gives a refinement of C's ``flexible array member'' pattern, allowing nesting structures with array members anywhere within other structures. |
---|
208 | \lstinput{10-15}{hello-accordion.cfa} |
---|
209 | This structure's layout has the starting offset of @municipalities@ varying in @NprovTerty@, and the offset of @total_pt@ and @total_mun@ varying in both generic parameters. |
---|
210 | For a function that operates on a @CanPop@ structure, the type system handles this variation transparently. |
---|
211 | \lstinput{40-45}{hello-accordion.cfa} |
---|
212 | \VRef[Figure]{f:checkHarness} shows the @CanPop@ harness and results with different array sizes, if the municipalities changed after a census. |
---|
213 | |
---|
214 | \begin{figure} |
---|
215 | \lstinput{60-68}{hello-accordion.cfa} |
---|
216 | \lstinput{70-75}{hello-accordion.cfa} |
---|
217 | \caption{\lstinline{check} Harness} |
---|
218 | \label{f:checkHarness} |
---|
219 | \end{figure} |
---|
220 | |
---|
221 | |
---|
222 | \section{Multidimensional Arrays} |
---|
223 | \label{toc:mdimpl} |
---|
224 | |
---|
225 | % TODO: introduce multidimensional array feature and approaches |
---|
226 | |
---|
227 | When working with arrays, \eg linear algebra, array dimensions are referred to as ``rows'' and ``columns'' for a matrix, adding ``planes'' for a cube. |
---|
228 | (There is little terminology for higher dimensional arrays.) |
---|
229 | For example, an acrostic poem\footnote{A type of poetry where the first, last or other letters in a line spell out a particular word or phrase in a vertical column.} |
---|
230 | can be treated as a grid of characters, where the rows are the text and the columns are the embedded keyword(s). |
---|
231 | Within a poem, there is the concept of a \newterm{slice}, \eg a row is a slice for the poem text, a column is a slice for a keyword. |
---|
232 | In general, the dimensioning and subscripting for multidimensional arrays has two syntactic forms: @m[r,c]@ or @m[r][c]@. |
---|
233 | |
---|
234 | Commonly, an array, matrix, or cube, is visualized (especially in mathematics) as a contiguous row, rectangle, or block. |
---|
235 | This conceptualization is reenforced by subscript ordering, \eg $m_{r,c}$ for a matrix and $c_{p,r,c}$ for a cube. |
---|
236 | Few programming languages differ from the mathematical subscript ordering. |
---|
237 | However, computer memory is flat, and hence, array forms are structured in memory as appropriate for the runtime system. |
---|
238 | The closest representation to the conceptual visualization is for an array object to be contiguous, and the language structures this memory using pointer arithmetic to access the values using various subscripts. |
---|
239 | This approach still has degrees of layout freedom, such as row or column major order, \ie juxtaposed rows or columns in memory, even when the subscript order remains fixed. |
---|
240 | For example, programming languages like MATLAB, Fortran, Julia and R store matrices in column-major order since they are commonly used for processing column-vectors in tabular data sets but retain row-major subscripting. |
---|
241 | In general, storage layout is hidden by subscripting, and only appears when passing arrays among different programming languages or accessing specific hardware. |
---|
242 | |
---|
243 | \VRef[Figure]{f:FixedVariable} shows two C90 approaches for manipulating a contiguous matrix. |
---|
244 | Note, C90 does not support VLAs. |
---|
245 | The fixed-dimension approach (left) uses the type system; |
---|
246 | however, it requires all dimensions except the first to be specified at compile time, \eg @m[][6]@, allowing all subscripting stride calculations to be generated with constants. |
---|
247 | Hence, every matrix passed to @fp1@ must have exactly 6 columns but the row size can vary. |
---|
248 | The variable-dimension approach (right) ignores (violates) the type system, \ie argument and parameters types do not match, and subscripting is performed manually using pointer arithmetic in the macro @sub@. |
---|
249 | |
---|
250 | \begin{figure} |
---|
251 | \begin{tabular}{@{}l@{\hspace{40pt}}l@{}} |
---|
252 | \multicolumn{1}{c}{\textbf{Fixed Dimension}} & \multicolumn{1}{c}{\textbf{Variable Dimension}} \\ |
---|
253 | \begin{cfa} |
---|
254 | |
---|
255 | void fp1( int rows, int m[][@6@] ) { |
---|
256 | ... printf( "%d ", @m[r][c]@ ); ... |
---|
257 | } |
---|
258 | int fm1[4][@6@], fm2[6][@6@]; // no VLA |
---|
259 | // initialize matrixes |
---|
260 | fp1( 4, fm1 ); // implicit 6 columns |
---|
261 | fp1( 6, fm2 ); |
---|
262 | \end{cfa} |
---|
263 | & |
---|
264 | \begin{cfa} |
---|
265 | #define sub( m, r, c ) *(m + r * sizeof( m[0] ) + c) |
---|
266 | void fp2( int rows, int cols, int *m ) { |
---|
267 | ... printf( "%d ", @sub( m, r, c )@ ); ... |
---|
268 | } |
---|
269 | int vm1[@4@][@4@], vm2[@6@][@8@]; // no VLA |
---|
270 | // initialize matrixes |
---|
271 | fp2( 4, 4, vm1 ); |
---|
272 | fp2( 6, 8, vm2 ); |
---|
273 | \end{cfa} |
---|
274 | \end{tabular} |
---|
275 | \caption{C90 Fixed \vs Variable Contiguous Matrix Styles} |
---|
276 | \label{f:FixedVariable} |
---|
277 | \end{figure} |
---|
278 | |
---|
279 | Many languages allow multidimensional arrays-of-arrays, \eg in Pascal or \CC. |
---|
280 | \begin{cquote} |
---|
281 | \begin{tabular}{@{}ll@{}} |
---|
282 | \begin{pascal} |
---|
283 | var m : array[0..4, 0..4] of Integer; (* matrix *) |
---|
284 | type AT = array[0..4] of Integer; (* array type *) |
---|
285 | type MT = array[0..4] of AT; (* array of array type *) |
---|
286 | var aa : MT; (* array of array variable *) |
---|
287 | m@[1][2]@ := 1; aa@[1][2]@ := 1 (* same subscripting *) |
---|
288 | \end{pascal} |
---|
289 | & |
---|
290 | \begin{c++} |
---|
291 | int m[5][5]; |
---|
292 | |
---|
293 | typedef vector< vector<int> > MT; |
---|
294 | MT vm( 5, vector<int>( 5 ) ); |
---|
295 | m@[1][2]@ = 1; aa@[1][2]@ = 1; |
---|
296 | \end{c++} |
---|
297 | \end{tabular} |
---|
298 | \end{cquote} |
---|
299 | The language decides if the matrix and array-of-array are laid out the same or differently. |
---|
300 | For example, an array-of-array may be an array of row pointers to arrays of columns, so the rows may not be contiguous in memory nor even the same length (triangular matrix). |
---|
301 | Regardless, there is usually a uniform subscripting syntax masking the memory layout, even though a language could differentiated between the two forms using subscript syntax, \eg @m[1,2]@ \vs @aa[1][2]@. |
---|
302 | Nevertheless, controlling memory layout can make a difference in what operations are allowed and in performance (caching/NUMA effects). |
---|
303 | |
---|
304 | C also provides non-contiguous arrays-of-arrays. |
---|
305 | \begin{cfa} |
---|
306 | int m[5][5]; $\C{// contiguous}$ |
---|
307 | int * aa[5]; $\C{// non-contiguous}$ |
---|
308 | \end{cfa} |
---|
309 | both with different memory layout using the same subscripting, and both with different degrees of issues. |
---|
310 | The focus of this work is on the contiguous multidimensional arrays in C. |
---|
311 | The reason is that programmers are often forced to use the more complex array-of-array form when a contiguous array would be simpler, faster, and safer. |
---|
312 | Nevertheless, the C array-of-array form is still important for special circumstances. |
---|
313 | |
---|
314 | \VRef[Figure]{f:ContiguousNon-contiguous} shows the extensions made in C99 for manipulating contiguous \vs non-contiguous arrays.\footnote{C90 also supported non-contiguous arrays.} |
---|
315 | First, VLAs are supported. |
---|
316 | Second, for contiguous arrays, C99 conjoins one or more of the parameters as a downstream dimension(s), \eg @cols@, implicitly using this parameter to compute the row stride of @m@. |
---|
317 | If the declaration of @fc@ is changed to: |
---|
318 | \begin{cfa} |
---|
319 | void fc( int rows, int cols, int m[@rows@][@cols@] ) ... |
---|
320 | \end{cfa} |
---|
321 | it is possible for C to perform bound checking across all subscripting, but it does not. |
---|
322 | While this contiguous-array capability is a step forward, it is still the programmer's responsibility to manually manage the number of dimensions and their sizes, both at the function definition and call sites. |
---|
323 | That is, the array does not automatically carry its structure and sizes for use in computing subscripts. |
---|
324 | While the non-contiguous style in @faa@ looks very similar to @fc@, the compiler only understands the unknown-sized array of row pointers, and it relies on the programmer to traverse the columns in a row correctly with a correctly bounded loop index. |
---|
325 | Specifically, there is no requirement that the rows are the same length, like a poem with different length lines. |
---|
326 | |
---|
327 | \begin{figure} |
---|
328 | \begin{tabular}{@{}ll@{}} |
---|
329 | \multicolumn{1}{c}{\textbf{Contiguous}} & \multicolumn{1}{c}{\textbf{ Non-contiguous}} \\ |
---|
330 | \begin{cfa} |
---|
331 | void fc( int rows, @int cols@, int m[ /* rows */ ][@cols@] ) { |
---|
332 | ... printf( "%d ", @m[r][c]@ ); ... |
---|
333 | } |
---|
334 | int m@[5][5]@; |
---|
335 | for ( int r = 0; r < 5; r += 1 ) { |
---|
336 | |
---|
337 | for ( int c = 0; c < 5; c += 1 ) |
---|
338 | m[r][c] = r + c; |
---|
339 | } |
---|
340 | fc( 5, 5, m ); |
---|
341 | \end{cfa} |
---|
342 | & |
---|
343 | \begin{cfa} |
---|
344 | void faa( int rows, int cols, int * m[ @/* cols */@ ] ) { |
---|
345 | ... printf( "%d ", @m[r][c]@ ); ... |
---|
346 | } |
---|
347 | int @* aa[5]@; // row pointers |
---|
348 | for ( int r = 0; r < 5; r += 1 ) { |
---|
349 | @aa[r] = malloc( 5 * sizeof(int) );@ // create rows |
---|
350 | for ( int c = 0; c < 5; c += 1 ) |
---|
351 | aa[r][c] = r + c; |
---|
352 | } |
---|
353 | faa( 5, 5, aa ); |
---|
354 | \end{cfa} |
---|
355 | \end{tabular} |
---|
356 | \caption{C99 Contiguous \vs Non-contiguous Matrix Styles} |
---|
357 | \label{f:ContiguousNon-contiguous} |
---|
358 | \end{figure} |
---|
359 | |
---|
360 | |
---|
361 | \subsection{Multidimensional array implementation} |
---|
362 | |
---|
363 | A multidimensional array implementation has three relevant levels of abstraction, from highest to lowest, where the array occupies \emph{contiguous memory}. |
---|
364 | \begin{enumerate} |
---|
365 | \item |
---|
366 | Flexible-stride memory: |
---|
367 | this model has complete independence between subscripting ordering and memory layout, offering the ability to slice by (provide an index for) any dimension, \eg slice a plane, row, or column, \eg @c[3][*][*]@, @c[3][4][*]@, @c[3][*][5]@. |
---|
368 | \item |
---|
369 | Fixed-stride memory: |
---|
370 | this model binds the first subscript and the first memory layout dimension, offering the ability to slice by (provide an index for) only the coarsest dimension, @m[row][*]@ or @c[plane][*][*]@, \eg slice only by row (2D) or plane (3D). |
---|
371 | After which, subscripting and memory layout are independent. |
---|
372 | \item |
---|
373 | Explicit-displacement memory: |
---|
374 | this model has no awareness of dimensions just the ability to access memory at a distance from a reference point (base-displacement addressing), \eg @x + 23@ or @x[23}@ $\Rightarrow$ 23rd element from the start of @x@. |
---|
375 | A programmer must manually build any notion of dimensions using other tools; |
---|
376 | hence, this style is not offering multidimensional arrays \see{\VRef[Figure]{f:FixedVariable} right example}. |
---|
377 | \end{enumerate} |
---|
378 | |
---|
379 | There is some debate as to whether the abstraction ordering goes $\{1, 2\} < 3$, rather than my numerically-ordering. |
---|
380 | That is, styles 1 and 2 are at the same abstraction level, with 3 offering a limited set of functionality. |
---|
381 | I chose to build the \CFA style-1 array upon a style-2 abstraction. |
---|
382 | (Justification of the decision follows, after the description of the design.) |
---|
383 | |
---|
384 | Style 3 is the inevitable target of any array implementation. |
---|
385 | The hardware offers this model to the C compiler, with bytes as the unit of displacement. |
---|
386 | C offers this model to its programmer as pointer arithmetic, with arbitrary sizes as the unit. |
---|
387 | Casting a multidimensional array as a single-dimensional array/pointer, then using @x[i]@ syntax to access its elements, is still a form of pointer arithmetic. |
---|
388 | |
---|
389 | Now stepping into the implementation of \CFA's new type-1 multidimensional arrays in terms of C's existing type-2 multidimensional arrays, it helps to clarify that even the interface is quite low-level. |
---|
390 | A C/\CFA array interface includes the resulting memory layout. |
---|
391 | The defining requirement of a type-2 system is the ability to slice a column from a column-finest matrix. |
---|
392 | The required memory shape of such a slice is fixed, before any discussion of implementation. |
---|
393 | The implementation presented here is how the \CFA array library wrangles the C type system, to make it do memory steps that are consistent with this layout. |
---|
394 | TODO: do I have/need a presentation of just this layout, just the semantics of -[all]? |
---|
395 | |
---|
396 | The new \CFA standard library @array@ datatype supports richer multidimensional features than C. |
---|
397 | The new array implementation follows C's contiguous approach, \ie @float [r][c]@, with one contiguous object subscripted by coarsely-strided dimensions directly wrapping finely-strided dimensions. |
---|
398 | Beyond what C's array type offers, the new array brings direct support for working with a noncontiguous array slice, allowing a program to work with dimension subscripts given in a non-physical order. |
---|
399 | |
---|
400 | The following examples use the matrix declaration @array( float, 5, 7 ) m@, loaded with values incremented by $0.1$, when stepping across the length-7 finely-strided column dimension, and stepping across the length-5 coarsely-strided row dimension. |
---|
401 | \par |
---|
402 | \mbox{\lstinput{121-126}{hello-md.cfa}} |
---|
403 | \par\noindent |
---|
404 | The memory layout is 35 contiguous elements with strictly increasing addresses. |
---|
405 | |
---|
406 | A trivial form of slicing extracts a contiguous inner array, within an array-of-arrays. |
---|
407 | As for the C array, a lesser-dimensional array reference can be bound to the result of subscripting a greater-dimensional array by a prefix of its dimensions, \eg @m[2]@, giving the third row. |
---|
408 | This action first subscripts away the most coarsely strided dimensions, leaving a result that expects to be subscripted by the more finely strided dimensions, \eg @m[2][3]@, giving the value @2.3@. |
---|
409 | The following is an example slicing a row. |
---|
410 | \lstinput{60-64}{hello-md.cfa} |
---|
411 | \lstinput[aboveskip=0pt]{140-140}{hello-md.cfa} |
---|
412 | |
---|
413 | However, function @print1d@ is asserting too much knowledge about its parameter @r@ for printing either a row slice or a column slice. |
---|
414 | Specifically, declaring the parameter @r@ with type @array@ means that @r@ is contiguous, which is unnecessarily restrictive. |
---|
415 | That is, @r@ need only be of a container type that offers a subscript operator (of type @ptrdiff_t@ $\rightarrow$ @float@) with managed length @N@. |
---|
416 | The new-array library provides the trait @ar@, so-defined. |
---|
417 | With it, the original declaration can be generalized with the same body. |
---|
418 | \lstinput{43-44}{hello-md.cfa} |
---|
419 | \lstinput[aboveskip=0pt]{145-145}{hello-md.cfa} |
---|
420 | The nontrivial slicing in this example now allows passing a \emph{noncontiguous} slice to @print1d@, where the new-array library provides a ``subscript by all'' operation for this purpose. |
---|
421 | In a multi-dimensional subscript operation, any dimension given as @all@ is a placeholder, \ie ``not yet subscripted by a value'', waiting for such a value, implementing the @ar@ trait. |
---|
422 | \lstinput{150-151}{hello-md.cfa} |
---|
423 | |
---|
424 | The example shows @x[2]@ and @x[[2, all]]@ both refer to the same, ``2.*'' slice. |
---|
425 | Indeed, the various @print1d@ calls under discussion access the entry with value @2.3@ as @x[2][3]@, @x[[2,all]][3]@, and @x[[all,3]][2]@. |
---|
426 | This design preserves (and extends) C array semantics by defining @x[[i,j]]@ to be @x[i][j]@ for numeric subscripts, but also for ``subscripting by all''. |
---|
427 | That is: |
---|
428 | \begin{cquote} |
---|
429 | \begin{tabular}{@{}cccccl@{}} |
---|
430 | @x[[2,all]][3]@ & $\equiv$ & @x[2][all][3]@ & $\equiv$ & @x[2][3]@ & (here, @all@ is redundant) \\ |
---|
431 | @x[[all,3]][2]@ & $\equiv$ & @x[all][3][2]@ & $\equiv$ & @x[2][3]@ & (here, @all@ is effective) |
---|
432 | \end{tabular} |
---|
433 | \end{cquote} |
---|
434 | |
---|
435 | Narrating progress through each of the @-[-][-][-]@\footnote{ |
---|
436 | The first ``\lstinline{-}'' is a variable expression and the remaining ``\lstinline{-}'' are subscript expressions.} |
---|
437 | expressions gives, firstly, a definition of @-[all]@, and secondly, a generalization of C's @-[i]@. |
---|
438 | Where @all@ is redundant: |
---|
439 | \begin{cquote} |
---|
440 | \begin{tabular}{@{}ll@{}} |
---|
441 | @x@ & 2-dimensional, want subscripts for coarse then fine \\ |
---|
442 | @x[2]@ & 1-dimensional, want subscript for fine; lock coarse == 2 \\ |
---|
443 | @x[2][all]@ & 1-dimensional, want subscript for fine \\ |
---|
444 | @x[2][all][3]@ & 0-dimensional; lock fine == 3 |
---|
445 | \end{tabular} |
---|
446 | \end{cquote} |
---|
447 | Where @all@ is effective: |
---|
448 | \begin{cquote} |
---|
449 | \begin{tabular}{@{}ll@{}} |
---|
450 | @x@ & 2-dimensional, want subscripts for coarse then fine \\ |
---|
451 | @x[all]@ & 2-dimensional, want subscripts for fine then coarse \\ |
---|
452 | @x[all][3]@ & 1-dimensional, want subscript for coarse; lock fine == 3 \\ |
---|
453 | @x[all][3][2]@ & 0-dimensional; lock coarse == 2 |
---|
454 | \end{tabular} |
---|
455 | \end{cquote} |
---|
456 | The semantics of @-[all]@ is to dequeue from the front of the ``want subscripts'' list and re-enqueue at its back. |
---|
457 | For example, in a two dimensional matrix, this semantics conceptually transposes the matrix by reversing the subscripts. |
---|
458 | The semantics of @-[i]@ is to dequeue from the front of the ``want subscripts'' list and lock its value to be @i@. |
---|
459 | |
---|
460 | Contiguous arrays, and slices of them, are all represented by the same underlying parameterized type, which includes stride information in its metatdata. |
---|
461 | \PAB{Do not understand this sentence: The \lstinline{-[all]} operation is a conversion from a reference to one instantiation to a reference to another instantiation.} |
---|
462 | The running example's @all@-effective step, stated more concretely, is: |
---|
463 | \begin{cquote} |
---|
464 | \begin{tabular}{@{}ll@{}} |
---|
465 | @x@ & : 5 of ( 7 of @float@ each spaced 1 @float@ apart ) each spaced 7 @floats@ apart \\ |
---|
466 | @x[all]@ & : 7 of ( 5 of @float@ each spaced 7 @float@s apart ) each spaced 1 @float@ apart |
---|
467 | \end{tabular} |
---|
468 | \end{cquote} |
---|
469 | |
---|
470 | \begin{figure} |
---|
471 | \includegraphics{measuring-like-layout} |
---|
472 | \caption{Visualization of subscripting by value and by \lstinline[language=CFA]{all}, for \lstinline{x} of type \lstinline{array( float, 5, 7 )} understood as 5 rows by 7 columns. |
---|
473 | The horizontal layout represents contiguous memory addresses while the vertical layout is conceptual. |
---|
474 | The vertical shaded band highlights the location of the targeted element, 2.3. |
---|
475 | Any such vertical slice contains various interpretations of a single address.} |
---|
476 | \label{fig:subscr-all} |
---|
477 | \end{figure} |
---|
478 | |
---|
479 | Figure~\ref{fig:subscr-all} shows one element (in the shaded band) accessed two different ways: as @x[2][3]@ and as @x[all][3][2]@. |
---|
480 | In both cases, value 2 selects from the coarser dimension (rows of @x@), |
---|
481 | while the value 3 selects from the finer dimension (columns of @x@). |
---|
482 | The figure illustrates the value of each subexpression, comparing how numeric subscripting proceeds from @x@, \vs from @x[all]@. |
---|
483 | Proceeding from @x@ gives the numeric indices as coarse then fine, while proceeding from @x[all]@ gives them fine then coarse. |
---|
484 | These two starting expressions, which are the example's only multidimensional subexpressions |
---|
485 | (those that received zero numeric indices so far), are illustrated with vertical steps where a \emph{first} numeric index would select. |
---|
486 | |
---|
487 | The figure's presentation offers an intuition answering to: What is an atomic element of @x[all]@? |
---|
488 | From there, @x[all]@ itself is simply a two-dimensional array, in the strict C sense, of these building blocks. |
---|
489 | An atom (like the bottommost value, @x[all][3][2]@), is the contained value (in the square box) |
---|
490 | and a lie about its size (the wedge above it, growing upward). |
---|
491 | An array of these atoms (like the intermediate @x[all][3]@) is just a contiguous arrangement of them, done according to their size; |
---|
492 | call such an array a column. |
---|
493 | A column is almost ready to be arranged into a matrix; |
---|
494 | it is the \emph{contained value} of the next-level building block, but another lie about size is required. |
---|
495 | At first, an atom needs to be arranged as if it were bigger, but now a column needs to be arranged as if it is smaller (the wedge above it, shrinking upward). |
---|
496 | These lying columns, arranged contiguously according to their size (as announced) form the matrix @x[all]@. |
---|
497 | Because @x[all]@ takes indices, first for the fine stride, then for the coarse stride, it achieves the requirement of representing the transpose of @x@. |
---|
498 | Yet every time the programmer presents an index, a C-array subscript is achieving the offset calculation. |
---|
499 | |
---|
500 | In the @x[all]@ case, after the finely strided subscript is done (column 3 is selected), |
---|
501 | the locations referenced by the coarse subscript options (rows 0..4) are offset by 3 floats, |
---|
502 | compared with where analogous rows appear when the row-level option is presented for @x@. |
---|
503 | |
---|
504 | \PAB{I don't understand this paragraph: These size lies create an appearance of overlap. |
---|
505 | For example, in \lstinline{x[all]}, the shaded band touches atoms 2.0, 2.1, 2.2, 2.3, 1.4, 1.5 and 1.6. |
---|
506 | But only the atom 2.3 is storing its value there. |
---|
507 | The rest are lying about (conflicting) claims on this location, but never exercising these alleged claims.} |
---|
508 | |
---|
509 | Lying is implemented as casting. |
---|
510 | The arrangement just described is implemented in the structure @arpk@. |
---|
511 | This structure uses one type in its internal field declaration and offers a different type as the return of its subscript operator. |
---|
512 | The field within is a plain-C array of the fictional type, which is 7 floats long for @x[all][3][2]@ and 1 float long for @x[all][3]@. |
---|
513 | The subscript operator presents what is really inside, by casting to the type below the wedge of the lie. |
---|
514 | |
---|
515 | % Does x[all] have to lie too? The picture currently glosses over how it it advertises a size of 7 floats. I'm leaving that as an edge case benignly misrepresented in the picture. Edge cases only have to be handled right in the code. |
---|
516 | |
---|
517 | Casting, overlapping, and lying are unsafe. |
---|
518 | The mission is to implement a style-1 feature in the type system for safe use by a programmer. |
---|
519 | The offered style-1 system is allowed to be internally unsafe, |
---|
520 | just as C's implementation of a style-2 system (upon a style-3 system) is unsafe within, even when the programmer is using it without casts or pointer arithmetic. |
---|
521 | Having a style-1 system relieves the programmer from resorting to unsafe pointer arithmetic when working with noncontiguous slices. |
---|
522 | |
---|
523 | % PAB: repeat from previous paragraph. |
---|
524 | % The choice to implement this style-1 system upon C's style-2 arrays, rather than its style-3 pointer arithmetic, reduces the attack surface of unsafe code. |
---|
525 | % My casting is unsafe, but I do not do any pointer arithmetic. |
---|
526 | % When a programmer works in the common-case style-2 subset (in the no-@[all]@ top of Figure~\ref{fig:subscr-all}), my casts are identities, and the C compiler is doing its usual displacement calculations. |
---|
527 | % If I had implemented my system upon style-3 pointer arithmetic, then this common case would be circumventing C's battle-hardened displacement calculations in favour of my own. |
---|
528 | |
---|
529 | % \noindent END: Paste looking for a home |
---|
530 | |
---|
531 | The new-array library defines types and operations that ensure proper elements are accessed soundly in spite of the overlapping. |
---|
532 | The @arpk@ structure and its @-[i]@ operator are defined as: |
---|
533 | \begin{cfa} |
---|
534 | forall( |
---|
535 | [N], $\C{// length of current dimension}$ |
---|
536 | S & | sized(S), $\C{// masquerading-as}$ |
---|
537 | Timmed &, $\C{// immediate element, often another array}$ |
---|
538 | Tbase & $\C{// base element, e.g. float, never array}$ |
---|
539 | ) { // distribute forall to each element |
---|
540 | struct arpk { |
---|
541 | S strides[N]; $\C{// so that sizeof(this) is N of S}$ |
---|
542 | }; |
---|
543 | // expose Timmed, stride by S |
---|
544 | static inline Timmed & ?[?]( arpk( N, S, Timmed, Tbase ) & a, long int i ) { |
---|
545 | subcheck( a, i, 0, N ); |
---|
546 | return (Timmed &)a.strides[i]; |
---|
547 | } |
---|
548 | } |
---|
549 | \end{cfa} |
---|
550 | The private @arpk@ structure (array with explicit packing) is generic over four types: dimension length, masquerading-as, ... |
---|
551 | This structure's public interface is hidden behind the @array(...)@ macro and the subscript operator. |
---|
552 | Construction by @array@ initializes the masquerading-as type information to be equal to the contained-element information. |
---|
553 | Subscripting by @all@ rearranges the order of masquerading-as types to achieve, in general, nontrivial striding. |
---|
554 | Subscripting by a number consumes the masquerading-as size of the contained element type, does normal array stepping according to that size, and returns there element found there, in unmasked form. |
---|
555 | |
---|
556 | An instantiation of the @arpk@ generic is given by the @array(E_base, N0, N1, ...)@ expansion, which is @arpk( N0, Rec, Rec, E_base )@, where @Rec@ is @array(E_base, N1, ...)@. |
---|
557 | In the base case, @array(E_base)@ is just @E_base@. |
---|
558 | Because this construction uses the same value for the generic parameters @S@ and @E_im@, the resulting layout has trivial strides. |
---|
559 | |
---|
560 | Subscripting by @all@, to operate on nontrivial strides, is a dequeue-enqueue operation on the @E_im@ chain, which carries @S@ instantiations, intact, to new positions. |
---|
561 | Expressed as an operation on types, this rotation is: |
---|
562 | \begin{eqnarray*} |
---|
563 | suball( arpk(N, S, E_i, E_b) ) & = & enq( N, S, E_i, E_b ) \\ |
---|
564 | enq( N, S, E_b, E_b ) & = & arpk( N, S, E_b, E_b ) \\ |
---|
565 | enq( N, S, arpk(N', S', E_i', E_b), E_b ) & = & arpk( N', S', enq(N, S, E_i', E_b), E_b ) |
---|
566 | \end{eqnarray*} |
---|
567 | |
---|
568 | |
---|
569 | \section{Bound checks, added and removed} |
---|
570 | |
---|
571 | \CFA array subscripting is protected with runtime bound checks. |
---|
572 | Having dependent typing causes the optimizer to remove more of these bound checks than it would without them. |
---|
573 | This section provides a demonstration of the effect. |
---|
574 | |
---|
575 | The experiment compares the \CFA array system with the padded-room system [TODO:xref] most typically exemplified by Java arrays, but also reflected in the \CC pattern where restricted vector usage models a checked array. |
---|
576 | The essential feature of this padded-room system is the one-to-one correspondence between array instances and the symbolic bounds on which dynamic checks are based. |
---|
577 | The experiment compares with the \CC version to keep access to generated assembly code simple. |
---|
578 | |
---|
579 | As a control case, a simple loop (with no reused dimension sizes) is seen to get the same optimization treatment in both the \CFA and \CC versions. |
---|
580 | When the programmer treats the array's bound correctly (making the subscript ``obviously fine''), no dynamic bound check is observed in the program's optimized assembly code. |
---|
581 | But when the bounds are adjusted, such that the subscript is possibly invalid, the bound check appears in the optimized assembly, ready to catch an occurrence the mistake. |
---|
582 | |
---|
583 | TODO: paste source and assembly codes |
---|
584 | |
---|
585 | Incorporating reuse among dimension sizes is seen to give \CFA an advantage at being optimized. |
---|
586 | The case is naive matrix multiplication over a row-major encoding. |
---|
587 | |
---|
588 | TODO: paste source codes |
---|
589 | |
---|
590 | |
---|
591 | |
---|
592 | |
---|
593 | |
---|
594 | \section{Comparison with other arrays} |
---|
595 | |
---|
596 | |
---|
597 | \subsection{Rust} |
---|
598 | |
---|
599 | \CFA's array is the first lightweight application of dependently-typed bound tracking to an extension of C. |
---|
600 | Other extensions of C that apply dependently-typed bound tracking are heavyweight, in that the bound tracking is part of a linearly-typed ownership-system, which further helps guarantee statically the validity of every pointer deference. |
---|
601 | These systems, therefore, ask the programmer to convince the type checker that every pointer dereference is valid. |
---|
602 | \CFA imposes the lighter-weight obligation, with the more limited guarantee, that initially-declared bounds are respected thereafter. |
---|
603 | |
---|
604 | \CFA's array is also the first extension of C to use its tracked bounds to generate the pointer arithmetic implied by advanced allocation patterns. |
---|
605 | Other bound-tracked extensions of C either forbid certain C patterns entirely, or address the problem of \emph{verifying} that the user's provided pointer arithmetic is self-consistent. |
---|
606 | The \CFA array, applied to accordion structures [TOD: cross-reference] \emph{implies} the necessary pointer arithmetic, generated automatically, and not appearing at all in a user's program. |
---|
607 | |
---|
608 | |
---|
609 | \subsection{Java} |
---|
610 | |
---|
611 | Java arrays are arrays-of-arrays because all objects are references \see{\VRef{toc:mdimpl}}. |
---|
612 | For each array, Java implicitly storages the array dimension in a descriptor, supporting array length, subscript checking, and allowing dynamically-sized array-parameter declarations. |
---|
613 | \begin{cquote} |
---|
614 | \begin{tabular}{rl} |
---|
615 | C & @void f( size_t n, size_t m, float x[n][m] );@ \\ |
---|
616 | Java & @void f( float x[][] );@ |
---|
617 | \end{tabular} |
---|
618 | \end{cquote} |
---|
619 | However, in the C prototype, the parameters @n@ and @m@ are documentation only as the intended size of the first and second dimension of @x@. |
---|
620 | \VRef[Figure]{f:JavaVsCTriangularMatrix} compares a triangular matrix (array-of-arrays) in dynamically safe Java to unsafe C. |
---|
621 | Each dynamically sized row in Java stores its dimension, while C requires the programmer to manage these sizes explicitly (@rlnth@). |
---|
622 | All subscripting is Java has bounds checking, while C has none. |
---|
623 | Both Java and C require explicit null checking, otherwise there is a runtime failure. |
---|
624 | |
---|
625 | \begin{figure} |
---|
626 | \setlength{\tabcolsep}{15pt} |
---|
627 | \begin{tabular}{ll@{}} |
---|
628 | \begin{java} |
---|
629 | int m[][] = { // triangular matrix |
---|
630 | new int [4], |
---|
631 | new int [3], |
---|
632 | new int [2], |
---|
633 | new int [1], |
---|
634 | null |
---|
635 | }; |
---|
636 | |
---|
637 | for ( int r = 0; r < m.length; r += 1 ) { |
---|
638 | if ( m[r] == null ) continue; |
---|
639 | for ( int c = 0; c < m[r].length; c += 1 ) { |
---|
640 | m[r][c] = c + r; // subscript checking |
---|
641 | } |
---|
642 | |
---|
643 | } |
---|
644 | |
---|
645 | for ( int r = 0; r < m.length; r += 1 ) { |
---|
646 | if ( m[r] == null ) { |
---|
647 | System.out.println( "null row" ); |
---|
648 | continue; |
---|
649 | } |
---|
650 | for ( int c = 0; c < m[r].length; c += 1 ) { |
---|
651 | System.out.print( m[r][c] + " " ); |
---|
652 | } |
---|
653 | System.out.println(); |
---|
654 | |
---|
655 | } |
---|
656 | \end{java} |
---|
657 | & |
---|
658 | \begin{cfa} |
---|
659 | int * m[5] = { // triangular matrix |
---|
660 | calloc( 4, sizeof(int) ), |
---|
661 | calloc( 3, sizeof(int) ), |
---|
662 | calloc( 2, sizeof(int) ), |
---|
663 | calloc( 1, sizeof(int) ), |
---|
664 | NULL |
---|
665 | }; |
---|
666 | int rlnth = 4; |
---|
667 | for ( int r = 0; r < 5; r += 1 ) { |
---|
668 | if ( m[r] == NULL ) continue; |
---|
669 | for ( int c = 0; c < rlnth; c += 1 ) { |
---|
670 | m[r][c] = c + r; // no subscript checking |
---|
671 | } |
---|
672 | rlnth -= 1; |
---|
673 | } |
---|
674 | rlnth = 4; |
---|
675 | for ( int r = 0; r < 5; r += 1 ) { |
---|
676 | if ( m[r] == NULL ) { |
---|
677 | printf( "null row\n" ); |
---|
678 | continue; |
---|
679 | } |
---|
680 | for ( int c = 0; c < rlnth; c += 1 ) { |
---|
681 | printf( "%d ", m[r][c] ); |
---|
682 | } |
---|
683 | printf( "\n" ); |
---|
684 | rlnth -= 1; |
---|
685 | } |
---|
686 | \end{cfa} |
---|
687 | \end{tabular} |
---|
688 | \caption{Java (left) \vs C (right) Triangular Matrix} |
---|
689 | \label{f:JavaVsCTriangularMatrix} |
---|
690 | \end{figure} |
---|
691 | |
---|
692 | The downside of the arrays-of-arrays approach is performance due to pointer chasing versus pointer arithmetic for a contiguous arrays. |
---|
693 | Furthermore, there is the cost of managing the implicit array descriptor. |
---|
694 | It is unlikely that a JIT can dynamically rewrite an arrays-of-arrays form into a contiguous form. |
---|
695 | |
---|
696 | |
---|
697 | \subsection{\CC} |
---|
698 | |
---|
699 | Because C arrays are difficult and dangerous, the mantra for \CC programmers is to use @std::vector@ in place of the C array. |
---|
700 | While the vector size can grow and shrink dynamically, \vs a fixed-size dynamic size with VLAs, the cost of this extra feature is mitigated by preallocating the maximum size (like the VLA) at the declaration (one dynamic call) to avoid using @push_back@. |
---|
701 | \begin{c++} |
---|
702 | vector< vector< int > > m( 5, vector<int>(8) ); // initialize size of 5 x 8 with 6 dynamic allocations |
---|
703 | \end{c++} |
---|
704 | Multidimensional arrays are arrays-of-arrays with associated costs. |
---|
705 | Each @vector@ array has an array descriptor contain the dimension, which allows bound checked using @x.at(i)@ in place of @x[i]@. |
---|
706 | Used with these restrictions, out-of-bound accesses are caught, and in-bound accesses never exercise the vector's ability to grow, preventing costly reallocate and copy, and never invalidate references to contained values. |
---|
707 | This scheme matches Java's safety and expressiveness exactly, but with the inherent costs. |
---|
708 | |
---|
709 | |
---|
710 | \subsection{Levels of dependently typed arrays} |
---|
711 | |
---|
712 | The \CFA array and the field of ``array language'' comparators all leverage dependent types to improve on the expressiveness over C and Java, accommodating examples such as: |
---|
713 | \begin{itemize} |
---|
714 | \item a \emph{zip}-style operation that consumes two arrays of equal length |
---|
715 | \item a \emph{map}-style operation whose produced length matches the consumed length |
---|
716 | \item a formulation of matrix multiplication, where the two operands must agree on a middle dimension, and where the result dimensions match the operands' outer dimensions |
---|
717 | \end{itemize} |
---|
718 | Across this field, this expressiveness is not just an available place to document such assumption, but these requirements are strongly guaranteed by default, with varying levels of statically/dynamically checked and ability to opt out. |
---|
719 | Along the way, the \CFA array also closes the safety gap (with respect to bounds) that Java has over C. |
---|
720 | |
---|
721 | Dependent type systems, considered for the purpose of bound-tracking, can be full-strength or restricted. |
---|
722 | In a full-strength dependent type system, a type can encode an arbitrarily complex predicate, with bound-tracking being an easy example. |
---|
723 | The tradeoff of this expressiveness is complexity in the checker, even typically, a potential for its nontermination. |
---|
724 | In a restricted dependent type system (purposed for bound tracking), the goal is to check helpful properties, while keeping the checker well-behaved; the other restricted checkers surveyed here, including \CFA's, always terminate. |
---|
725 | [TODO: clarify how even Idris type checking terminates] |
---|
726 | |
---|
727 | Idris is a current, general-purpose dependently typed programming language. |
---|
728 | Length checking is a common benchmark for full dependent type systems. |
---|
729 | Here, the capability being considered is to track lengths that adjust during the execution of a program, such as when an \emph{add} operation produces a collection one element longer than the one on which it started. |
---|
730 | [TODO: finish explaining what Data.Vect is and then the essence of the comparison] |
---|
731 | |
---|
732 | POINTS: |
---|
733 | here is how our basic checks look (on a system that does not have to compromise); |
---|
734 | it can also do these other cool checks, but watch how I can mess with its conservativeness and termination |
---|
735 | |
---|
736 | Two current, state-of-the-art array languages, Dex\cite{arr:dex:long} and Futhark\cite{arr:futhark:tytheory}, offer novel contributions concerning similar, restricted dependent types for tracking array length. |
---|
737 | Unlike \CFA, both are garbage-collected functional languages. |
---|
738 | Because they are garbage-collected, referential integrity is built-in, meaning that the heavyweight analysis, that \CFA aims to avoid, is unnecessary. |
---|
739 | So, like \CFA, the checking in question is a lightweight bounds-only analysis. |
---|
740 | Like \CFA, their checks that are conservatively limited by forbidding arithmetic in the depended-upon expression. |
---|
741 | |
---|
742 | |
---|
743 | |
---|
744 | The Futhark work discusses the working language's connection to a lambda calculus, with typing rules and a safety theorem proven in reference to an operational semantics. |
---|
745 | There is a particular emphasis on an existential type, enabling callee-determined return shapes. |
---|
746 | |
---|
747 | |
---|
748 | Dex uses a novel conception of size, embedding its quantitative information completely into an ordinary type. |
---|
749 | |
---|
750 | Futhark and full-strength dependently typed languages treat array sizes are ordinary values. |
---|
751 | Futhark restricts these expressions syntactically to variables and constants, while a full-strength dependent system does not. |
---|
752 | |
---|
753 | \CFA's hybrid presentation, @forall( [N] )@, has @N@ belonging to the type system, yet has no instances. |
---|
754 | Belonging to the type system means it is inferred at a call site and communicated implicitly, like in Dex and unlike in Futhark. |
---|
755 | Having no instances means there is no type for a variable @i@ that constrains @i@ to be in the range for @N@, unlike Dex, [TODO: verify], but like Futhark. |
---|
756 | |
---|
757 | \subsection{Static safety in C extensions} |
---|
758 | |
---|
759 | |
---|
760 | \section{Future work} |
---|
761 | |
---|
762 | \subsection{Declaration syntax} |
---|
763 | |
---|
764 | \subsection{Range slicing} |
---|
765 | |
---|
766 | \subsection{With a module system} |
---|
767 | |
---|
768 | \subsection{With described enumerations} |
---|
769 | |
---|
770 | A project in \CFA's current portfolio will improve enumerations. |
---|
771 | In the incumbent state, \CFA has C's enumerations, unmodified. |
---|
772 | I will not discuss the core of this project, which has a tall mission already, to improve type safety, maintain appropriate C compatibility and offer more flexibility about storage use. |
---|
773 | It also has a candidate stretch goal, to adapt \CFA's @forall@ generic system to communicate generalized enumerations: |
---|
774 | \begin{cfa} |
---|
775 | forall( T | is_enum(T) ) |
---|
776 | void show_in_context( T val ) { |
---|
777 | for( T i ) { |
---|
778 | string decorator = ""; |
---|
779 | if ( i == val-1 ) decorator = "< ready"; |
---|
780 | if ( i == val ) decorator = "< go" ; |
---|
781 | sout | i | decorator; |
---|
782 | } |
---|
783 | } |
---|
784 | enum weekday { mon, tue, wed = 500, thu, fri }; |
---|
785 | show_in_context( wed ); |
---|
786 | \end{cfa} |
---|
787 | with output |
---|
788 | \begin{cfa} |
---|
789 | mon |
---|
790 | tue < ready |
---|
791 | wed < go |
---|
792 | thu |
---|
793 | fri |
---|
794 | \end{cfa} |
---|
795 | The details in this presentation aren't meant to be taken too precisely as suggestions for how it should look in \CFA. |
---|
796 | But the example shows these abilities: |
---|
797 | \begin{itemize} |
---|
798 | \item a built-in way (the @is_enum@ trait) for a generic routine to require enumeration-like information about its instantiating type |
---|
799 | \item an implicit implementation of the trait whenever a user-written enum occurs (@weekday@'s declaration implies @is_enum@) |
---|
800 | \item a total order over the enumeration constants, with predecessor/successor (@val-1@) available, and valid across gaps in values (@tue == 1 && wed == 500 && tue == wed - 1@) |
---|
801 | \item a provision for looping (the @for@ form used) over the values of the type. |
---|
802 | \end{itemize} |
---|
803 | |
---|
804 | If \CFA gets such a system for describing the list of values in a type, then \CFA arrays are poised to move from the Futhark level of expressiveness, up to the Dex level. |
---|
805 | |
---|
806 | [TODO: introduce Ada in the comparators] |
---|
807 | |
---|
808 | In Ada and Dex, an array is conceived as a function whose domain must satisfy only certain structural assumptions, while in C, \CC, Java, Futhark and \CFA today, the domain is a prefix of the natural numbers. |
---|
809 | The generality has obvious aesthetic benefits for programmers working on scheduling resources to weekdays, and for programmers who prefer to count from an initial number of their own choosing. |
---|
810 | |
---|
811 | This change of perspective also lets us remove ubiquitous dynamic bound checks. |
---|
812 | [TODO: xref] discusses how automatically inserted bound checks can often be optimized away. |
---|
813 | But this approach is unsatisfying to a programmer who believes she has written code in which dynamic checks are unnecessary, but now seeks confirmation. |
---|
814 | To remove the ubiquitous dynamic checking is to say that an ordinary subscript operation is only valid when it can be statically verified to be in-bound (and so the ordinary subscript is not dynamically checked), and an explicit dynamic check is available when the static criterion is impractical to meet. |
---|
815 | |
---|
816 | [TODO, fix confusion: Idris has this arrangement of checks, but still the natural numbers as the domain.] |
---|
817 | |
---|
818 | The structural assumptions required for the domain of an array in Dex are given by the trait (there, ``interface'') @Ix@, which says that the parameter @n@ is a type (which could take an argument like @weekday@) that provides two-way conversion with the integers and a report on the number of values. |
---|
819 | Dex's @Ix@ is analogous the @is_enum@ proposed for \CFA above. |
---|
820 | \begin{cfa} |
---|
821 | interface Ix n |
---|
822 | get_size n : Unit -> Int |
---|
823 | ordinal : n -> Int |
---|
824 | unsafe_from_ordinal n : Int -> n |
---|
825 | \end{cfa} |
---|
826 | |
---|
827 | Dex uses this foundation of a trait (as an array type's domain) to achieve polymorphism over shapes. |
---|
828 | This flavour of polymorphism lets a function be generic over how many (and the order of) dimensions a caller uses when interacting with arrays communicated with this function. |
---|
829 | Dex's example is a routine that calculates pointwise differences between two samples. |
---|
830 | Done with shape polymorphism, one function body is equally applicable to a pair of single-dimensional audio clips (giving a single-dimensional result) and a pair of two-dimensional photographs (giving a two-dimensional result). |
---|
831 | In both cases, but with respectively dimensioned interpretations of ``size,'' this function requires the argument sizes to match, and it produces a result of the that size. |
---|
832 | |
---|
833 | The polymorphism plays out with the pointwise-difference routine advertising a single-dimensional interface whose domain type is generic. |
---|
834 | In the audio instantiation, the duration-of-clip type argument is used for the domain. |
---|
835 | In the photograph instantiation, it's the tuple-type of $ \langle \mathrm{img\_wd}, \mathrm{img\_ht} \rangle $. |
---|
836 | This use of a tuple-as-index is made possible by the built-in rule for implementing @Ix@ on a pair, given @Ix@ implementations for its elements |
---|
837 | \begin{cfa} |
---|
838 | instance {a b} [Ix a, Ix b] Ix (a & b) |
---|
839 | get_size = \(). size a * size b |
---|
840 | ordinal = \(i, j). (ordinal i * size b) + ordinal j |
---|
841 | unsafe_from_ordinal = \o. |
---|
842 | bs = size b |
---|
843 | (unsafe_from_ordinal a (idiv o bs), unsafe_from_ordinal b (rem o bs)) |
---|
844 | \end{cfa} |
---|
845 | and by a user-provided adapter expression at the call site that shows how to indexing with a tuple is backed by indexing each dimension at a time |
---|
846 | \begin{cfa} |
---|
847 | img_trans :: (img_wd,img_ht)=>Real |
---|
848 | img_trans.(i,j) = img.i.j |
---|
849 | result = pairwise img_trans |
---|
850 | \end{cfa} |
---|
851 | [TODO: cite as simplification of example from https://openreview.net/pdf?id=rJxd7vsWPS section 4] |
---|
852 | |
---|
853 | In the case of adapting this pattern to \CFA, my current work provides an adapter from ``successively subscripted'' to ``subscripted by tuple,'' so it is likely that generalizing my adapter beyond ``subscripted by @ptrdiff_t@'' is sufficient to make a user-provided adapter unnecessary. |
---|
854 | |
---|
855 | \subsection{Retire pointer arithmetic} |
---|
856 | |
---|
857 | |
---|
858 | \section{\CFA} |
---|
859 | |
---|
860 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\ |
---|
861 | moved from background chapter \\ |
---|
862 | XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX \\ |
---|
863 | |
---|
864 | Traditionally, fixing C meant leaving the C-ism alone, while providing a better alternative beside it. |
---|
865 | (For later: That's what I offer with array.hfa, but in the future-work vision for arrays, the fix includes helping programmers stop accidentally using a broken C-ism.) |
---|
866 | |
---|
867 | \subsection{\CFA features interacting with arrays} |
---|
868 | |
---|
869 | Prior work on \CFA included making C arrays, as used in C code from the wild, |
---|
870 | work, if this code is fed into @cfacc@. |
---|
871 | The quality of this this treatment was fine, with no more or fewer bugs than is typical. |
---|
872 | |
---|
873 | More mixed results arose with feeding these ``C'' arrays into preexisting \CFA features. |
---|
874 | |
---|
875 | A notable success was with the \CFA @alloc@ function, |
---|
876 | which type information associated with a polymorphic return type |
---|
877 | replaces @malloc@'s use of programmer-supplied size information. |
---|
878 | \begin{cfa} |
---|
879 | // C, library |
---|
880 | void * malloc( size_t ); |
---|
881 | // C, user |
---|
882 | struct tm * el1 = malloc( sizeof(struct tm) ); |
---|
883 | struct tm * ar1 = malloc( 10 * sizeof(struct tm) ); |
---|
884 | |
---|
885 | // CFA, library |
---|
886 | forall( T * ) T * alloc(); |
---|
887 | // CFA, user |
---|
888 | tm * el2 = alloc(); |
---|
889 | tm (*ar2)[10] = alloc(); |
---|
890 | \end{cfa} |
---|
891 | The alloc polymorphic return compiles into a hidden parameter, which receives a compiler-generated argument. |
---|
892 | This compiler's argument generation uses type information from the left-hand side of the initialization to obtain the intended type. |
---|
893 | Using a compiler-produced value eliminates an opportunity for user error. |
---|
894 | |
---|
895 | TODO: fix in following: even the alloc call gives bad code gen: verify it was always this way; walk back the wording about things just working here; assignment (rebind) seems to offer workaround, as in bkgd-cfa-arrayinteract.cfa |
---|
896 | |
---|
897 | Bringing in another \CFA feature, reference types, both resolves a sore spot of the last example, and gives a first example of an array-interaction bug. |
---|
898 | In the last example, the choice of ``pointer to array'' @ar2@ breaks a parallel with @ar1@. |
---|
899 | They are not subscripted in the same way. |
---|
900 | \begin{cfa} |
---|
901 | ar1[5]; |
---|
902 | (*ar2)[5]; |
---|
903 | \end{cfa} |
---|
904 | Using ``reference to array'' works at resolving this issue. TODO: discuss connection with Doug-Lea \CC proposal. |
---|
905 | \begin{cfa} |
---|
906 | tm (&ar3)[10] = *alloc(); |
---|
907 | ar3[5]; |
---|
908 | \end{cfa} |
---|
909 | The implicit size communication to @alloc@ still works in the same ways as for @ar2@. |
---|
910 | |
---|
911 | Using proper array types (@ar2@ and @ar3@) addresses a concern about using raw element pointers (@ar1@), albeit a theoretical one. |
---|
912 | TODO xref C standard does not claim that @ar1@ may be subscripted, |
---|
913 | because no stage of interpreting the construction of @ar1@ has it be that ``there is an \emph{array object} here.'' |
---|
914 | But both @*ar2@ and the referent of @ar3@ are the results of \emph{typed} @alloc@ calls, |
---|
915 | where the type requested is an array, making the result, much more obviously, an array object. |
---|
916 | |
---|
917 | The ``reference to array'' type has its sore spots too. |
---|
918 | TODO see also @dimexpr-match-c/REFPARAM_CALL@ (under @TRY_BUG_1@) |
---|
919 | |
---|
920 | TODO: I fixed a bug associated with using an array as a T. I think. Did I really? What was the bug? |
---|